Skip to content

Commit

Permalink
Replac uses of from_utf8_unchecked with from_utf8.
Browse files Browse the repository at this point in the history
Fixes #43.
  • Loading branch information
gz committed Jul 4, 2021
1 parent 0ebd1da commit 936ab41
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 20 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]

- Use more idiomatic rust code in readme/doc.rs example.
- Use `str::from_utf8` instead of `str::from_utf8_unchecked` to avoid potential
panics with the Deserialize trait (Fixes #43).

## [9.1.0] - 2021-07-03

Expand Down
30 changes: 10 additions & 20 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -712,16 +712,13 @@ impl VendorInfo {
/// Return vendor identification as human readable string.
pub fn as_string<'a>(&'a self) -> &'a str {
let brand_string_start = self as *const VendorInfo as *const u8;
unsafe {
let slice = unsafe {
// Safety: VendorInfo is laid out with repr(C) and exactly
// 12 byte long without any padding.
let slice: &'a [u8] =
slice::from_raw_parts(brand_string_start, size_of::<VendorInfo>());
// Safety: The field is specified to be ASCII, and the only safe
// way to construct VendorInfo is from real CPUID data or the
// Default implementation.
str::from_utf8_unchecked(slice)
}
slice::from_raw_parts(brand_string_start, size_of::<VendorInfo>())
};

str::from_utf8(slice).unwrap_or("InvalidVendorString")
}
}

Expand Down Expand Up @@ -4193,15 +4190,11 @@ pub struct SoCVendorBrand {
impl SoCVendorBrand {
pub fn as_string<'a>(&'a self) -> &'a str {
let brand_string_start = self as *const SoCVendorBrand as *const u8;
unsafe {
let slice = unsafe {
// Safety: SoCVendorBrand is laid out with repr(C).
let slice: &'a [u8] =
slice::from_raw_parts(brand_string_start, size_of::<SoCVendorBrand>());
// Safety: The field is specified to be ASCII, and the only safe
// way to construct SoCVendorBrand is from real CPUID data or the
// Default implementation.
str::from_utf8_unchecked(slice)
}
slice::from_raw_parts(brand_string_start, size_of::<SoCVendorBrand>())
};
str::from_utf8(slice).unwrap_or("InvalidSoCVendorString")
}
}

Expand Down Expand Up @@ -4329,10 +4322,7 @@ impl ExtendedFunctionInfo {
// Brand terminated at nul byte or end, whichever comes first.
let slice = slice.split(|&x| x == 0).next().unwrap();

// Safety: Field is specified to be ASCII, and the only safe way
// to construct ExtendedFunctionInfo is from real CPUID data
// or the Default implementation.
Some(unsafe { str::from_utf8_unchecked(slice) })
str::from_utf8(slice).ok()
} else {
None
}
Expand Down

0 comments on commit 936ab41

Please sign in to comment.