Skip to content

Commit

Permalink
feat: add methods to Str
Browse files Browse the repository at this point in the history
Signed-off-by: YdrMaster <[email protected]>
  • Loading branch information
YdrMaster committed Jul 12, 2022
1 parent d383382 commit b28985b
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 34 deletions.
36 changes: 2 additions & 34 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@ mod header;
mod indent;
mod path;
mod property;
mod str;
mod structure_block;
mod walker;

pub use self::str::Str;
pub use path::Path;
pub use property::{PHandle, Property, Reg, StrList};
pub mod utils {
Expand Down Expand Up @@ -167,40 +169,6 @@ pub enum WalkOperation {
Terminate,
}

/// 地址空间上的一个字符串,但未检查是否符合 utf-8 编码。
#[derive(Clone, Copy)]
pub struct Str<'a>(&'a [u8]);

impl Str<'_> {
/// Converts to `&[u8]`.
#[inline]
pub fn as_bytes(&self) -> &[u8] {
self.0
}

/// Converts to [`str`].
#[inline]
pub fn as_str(&self) -> Result<&str, core::str::Utf8Error> {
core::str::from_utf8(self.0)
}

/// Converts to [`str`] without checking utf-8 validity.
///
/// # Safety
///
/// see [`core::str::from_utf8_unchecked`].
#[inline]
pub unsafe fn as_str_unchecked(&self) -> &str {
core::str::from_utf8_unchecked(self.0)
}
}

impl fmt::Display for Str<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
unsafe { self.as_str_unchecked() }.fmt(f)
}
}

#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Eq)]
struct U32BigEndian(u32);
Expand Down
49 changes: 49 additions & 0 deletions src/str.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use core::{fmt, str};

/// 地址空间上的一个字符串,但未检查是否符合 utf-8 编码。
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Str<'a>(pub(crate) &'a [u8]);

impl Str<'_> {
/// Converts to `&[u8]`.
#[inline]
pub fn as_bytes(&self) -> &[u8] {
self.0
}

/// Converts to [`str`].
#[inline]
pub fn as_str(&self) -> Result<&str, str::Utf8Error> {
str::from_utf8(self.0)
}

/// Converts to [`str`] without checking utf-8 validity.
///
/// # Safety
///
/// see [`core::str::from_utf8_unchecked`].
#[inline]
pub unsafe fn as_str_unchecked(&self) -> &str {
str::from_utf8_unchecked(self.0)
}

/// Returns `true` if `needle` is a prefix of this string.
#[inline]
pub fn starts_with(&self, needle: &str) -> bool {
self.0.starts_with(needle.as_bytes())
}
}

impl<'a> From<&'a str> for Str<'a> {
#[inline]
fn from(s: &'a str) -> Self {
Str(s.as_bytes())
}
}

impl fmt::Display for Str<'_> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
unsafe { self.as_str_unchecked() }.fmt(f)
}
}

0 comments on commit b28985b

Please sign in to comment.