Skip to content

Commit

Permalink
refactor: remove the only unsafe block (#9)
Browse files Browse the repository at this point in the history
This does not result in any performance penalty, when running the
existing benchmarks.
  • Loading branch information
dmb-ish authored Aug 15, 2024
1 parent 2a8e2eb commit 13bcded
Showing 1 changed file with 8 additions and 10 deletions.
18 changes: 8 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,25 +30,25 @@ pub fn slugify_owned(s: String) -> String {

// avoid unnecessary monomorphizations
fn _slugify(s: &str) -> String {
let mut slug: Vec<u8> = Vec::with_capacity(s.len());
let mut slug = String::with_capacity(s.len());
// Starts with true to avoid leading -
let mut prev_is_dash = true;
{
let mut push_char = |x: u8| {
match x {
b'a'..=b'z' | b'0'..=b'9' => {
prev_is_dash = false;
slug.push(x);
slug.push(x.into());
}
b'A'..=b'Z' => {
prev_is_dash = false;
// Manual lowercasing as Rust to_lowercase() is unicode
// aware and therefore much slower
slug.push(x - b'A' + b'a');
slug.push((x - b'A' + b'a').into());
}
_ => {
if !prev_is_dash {
slug.push(b'-');
slug.push('-');
prev_is_dash = true;
}
}
Expand All @@ -66,12 +66,10 @@ fn _slugify(s: &str) -> String {
}
}

// It's not really unsafe in practice, we know we have ASCII
let mut string = unsafe { String::from_utf8_unchecked(slug) };
if string.ends_with('-') {
string.pop();
if slug.ends_with('-') {
slug.pop();
}
// We likely reserved more space than needed.
string.shrink_to_fit();
string
slug.shrink_to_fit();
slug
}

0 comments on commit 13bcded

Please sign in to comment.