0
0
Fork 0
mirror of https://github.com/denoland/rusty_v8.git synced 2024-11-21 15:04:33 -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, 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 { impl AsRef<str> for OneByteConst {
#[inline(always)]
fn as_ref(&self) -> &str { fn as_ref(&self) -> &str {
// SAFETY: We know this is ASCII self.as_str()
unsafe { std::str::from_utf8_unchecked(AsRef::<[u8]>::as_ref(self)) }
} }
} }
impl AsRef<[u8]> for OneByteConst { impl AsRef<[u8]> for OneByteConst {
#[inline(always)]
fn as_ref(&self) -> &[u8] { fn as_ref(&self) -> &[u8] {
// SAFETY: Returning to the slice from which this came self.as_str().as_bytes()
unsafe { std::slice::from_raw_parts(self.cached_data as _, self.length) }
} }
} }
impl std::ops::Deref for OneByteConst { impl std::ops::Deref for OneByteConst {
type Target = str; type Target = str;
#[inline(always)]
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
self.as_ref() self.as_ref()
} }