0
0
Fork 0
mirror of https://github.com/denoland/rusty_v8.git synced 2024-11-24 15:19:31 -05:00

fix: add const as_str to OneByteConst and make empty slices sound (#1453)

This commit is contained in:
Matt Mastracci 2024-04-15 07:49:32 -06:00 committed by GitHub
parent 777dfa6ac6
commit 44ea45d9cb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -126,22 +126,41 @@ pub struct OneByteConst {
length: usize,
}
impl OneByteConst {
/// `const` function that returns this string as a string reference.
#[inline(always)]
pub const fn as_str(&self) -> &str {
if self.length == 0 {
""
} else {
// SAFETY: We know this is ASCII and length > 0
unsafe {
std::str::from_utf8_unchecked(std::slice::from_raw_parts(
self.cached_data as _,
self.length,
))
}
}
}
}
impl AsRef<str> for OneByteConst {
#[inline(always)]
fn as_ref(&self) -> &str {
// SAFETY: We know this is ASCII
unsafe { std::str::from_utf8_unchecked(AsRef::<[u8]>::as_ref(self)) }
self.as_str()
}
}
impl AsRef<[u8]> for OneByteConst {
#[inline(always)]
fn as_ref(&self) -> &[u8] {
// SAFETY: Returning to the slice from which this came
unsafe { std::slice::from_raw_parts(self.cached_data as _, self.length) }
self.as_str().as_bytes()
}
}
impl std::ops::Deref for OneByteConst {
type Target = str;
#[inline(always)]
fn deref(&self) -> &Self::Target {
self.as_ref()
}