Skip to content

Commit b28985b

Browse files
committed
feat: add methods to Str
Signed-off-by: YdrMaster <[email protected]>
1 parent d383382 commit b28985b

File tree

2 files changed

+51
-34
lines changed

2 files changed

+51
-34
lines changed

src/lib.rs

Lines changed: 2 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,11 @@ mod header;
1919
mod indent;
2020
mod path;
2121
mod property;
22+
mod str;
2223
mod structure_block;
2324
mod walker;
2425

26+
pub use self::str::Str;
2527
pub use path::Path;
2628
pub use property::{PHandle, Property, Reg, StrList};
2729
pub mod utils {
@@ -167,40 +169,6 @@ pub enum WalkOperation {
167169
Terminate,
168170
}
169171

170-
/// 地址空间上的一个字符串,但未检查是否符合 utf-8 编码。
171-
#[derive(Clone, Copy)]
172-
pub struct Str<'a>(&'a [u8]);
173-
174-
impl Str<'_> {
175-
/// Converts to `&[u8]`.
176-
#[inline]
177-
pub fn as_bytes(&self) -> &[u8] {
178-
self.0
179-
}
180-
181-
/// Converts to [`str`].
182-
#[inline]
183-
pub fn as_str(&self) -> Result<&str, core::str::Utf8Error> {
184-
core::str::from_utf8(self.0)
185-
}
186-
187-
/// Converts to [`str`] without checking utf-8 validity.
188-
///
189-
/// # Safety
190-
///
191-
/// see [`core::str::from_utf8_unchecked`].
192-
#[inline]
193-
pub unsafe fn as_str_unchecked(&self) -> &str {
194-
core::str::from_utf8_unchecked(self.0)
195-
}
196-
}
197-
198-
impl fmt::Display for Str<'_> {
199-
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
200-
unsafe { self.as_str_unchecked() }.fmt(f)
201-
}
202-
}
203-
204172
#[repr(transparent)]
205173
#[derive(Clone, Copy, PartialEq, Eq)]
206174
struct U32BigEndian(u32);

src/str.rs

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
use core::{fmt, str};
2+
3+
/// 地址空间上的一个字符串,但未检查是否符合 utf-8 编码。
4+
#[derive(Clone, Copy, PartialEq, Eq)]
5+
pub struct Str<'a>(pub(crate) &'a [u8]);
6+
7+
impl Str<'_> {
8+
/// Converts to `&[u8]`.
9+
#[inline]
10+
pub fn as_bytes(&self) -> &[u8] {
11+
self.0
12+
}
13+
14+
/// Converts to [`str`].
15+
#[inline]
16+
pub fn as_str(&self) -> Result<&str, str::Utf8Error> {
17+
str::from_utf8(self.0)
18+
}
19+
20+
/// Converts to [`str`] without checking utf-8 validity.
21+
///
22+
/// # Safety
23+
///
24+
/// see [`core::str::from_utf8_unchecked`].
25+
#[inline]
26+
pub unsafe fn as_str_unchecked(&self) -> &str {
27+
str::from_utf8_unchecked(self.0)
28+
}
29+
30+
/// Returns `true` if `needle` is a prefix of this string.
31+
#[inline]
32+
pub fn starts_with(&self, needle: &str) -> bool {
33+
self.0.starts_with(needle.as_bytes())
34+
}
35+
}
36+
37+
impl<'a> From<&'a str> for Str<'a> {
38+
#[inline]
39+
fn from(s: &'a str) -> Self {
40+
Str(s.as_bytes())
41+
}
42+
}
43+
44+
impl fmt::Display for Str<'_> {
45+
#[inline]
46+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47+
unsafe { self.as_str_unchecked() }.fmt(f)
48+
}
49+
}

0 commit comments

Comments
 (0)