Skip to content

Commit

Permalink
unsafe
Browse files Browse the repository at this point in the history
  • Loading branch information
Manishearth committed Oct 23, 2024
1 parent 1ab3fde commit 067fadc
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 11 deletions.
9 changes: 4 additions & 5 deletions components/locale_core/src/langid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,11 +189,10 @@ impl LanguageIdentifier {
let lang_id = Self::try_from_utf8(input.as_ref())?;
let cow = lang_id.write_to_string();
if cow.as_bytes() == input {
if let Ok(s) = core::str::from_utf8(input) {
Ok(s.into())
} else {
Ok(cow.into_owned().into())
}
// Safety: input is known to be valid UTF-8 since it has the same
// bytes as `cow`, which is a `str`.
let s = unsafe { core::str::from_utf8_unchecked(input) };
Ok(s.into())
} else {
Ok(cow.into_owned().into())
}
Expand Down
11 changes: 5 additions & 6 deletions components/locale_core/src/locale.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,13 +171,12 @@ impl Locale {
/// ```
pub fn canonicalize_utf8(input: &[u8]) -> Result<Cow<str>, ParseError> {
let locale = Self::try_from_utf8(input)?;
let cow = locale.write_to_string();
let cow: Cow<str> = locale.write_to_string();
if cow.as_bytes() == input {
if let Ok(s) = core::str::from_utf8(input) {
Ok(s.into())
} else {
Ok(cow.into_owned().into())
}
// Safety: input is known to be valid UTF-8 since it has the same
// bytes as `cow`, which is a `str`.
let s = unsafe { core::str::from_utf8_unchecked(input) };
Ok(s.into())
} else {
Ok(cow.into_owned().into())
}
Expand Down

0 comments on commit 067fadc

Please sign in to comment.