forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

str_slice.rs48 lines, 1.4 KiBHistoryRawDownload
1use append_only_bytes::{AppendOnlyBytes, BytesSlice};
2
3/// It's just a wrapper around [BytesSlice] that makes sure
4/// the content of the bytes is a valid utf-8 string
5pub(crate) struct StrSlice(BytesSlice);
6
7impl StrSlice {
8 #[allow(unused)]
9 pub fn new(bytes: BytesSlice) -> Option<Self> {
10 let _str = std::str::from_utf8(&bytes).ok()?;
11 Some(Self(bytes))
12 }
13
14 pub fn new_from_str(str: &str) -> Self {
15 let mut a = AppendOnlyBytes::new();
16 a.push_str(str);
17 Self(a.slice(..))
18 }
19
20 pub fn bytes(&self) -> &BytesSlice {
21 &self.0
22 }
23
24 pub fn as_str(&self) -> &str {
25 // SAFETY: We ensure that the content is always valid utf8
26 unsafe { std::str::from_utf8_unchecked(&self.0) }
27 }
28
29 pub fn split_at_unicode_pos(&self, pos: usize) -> (Self, Self) {
30 let s = self.as_str();
31 let mut split_at = self.0.len();
32 // ASCII: chars are bytes. (project_note patch)
33 if pos <= s.len() && s.as_bytes()[..pos].is_ascii() {
34 return (Self(self.0.slice_clone(..pos)), Self(self.0.slice_clone(pos..)));
35 }
36 for (u, (i, _)) in s.char_indices().enumerate() {
37 if u == pos {
38 split_at = i;
39 break;
40 }
41 }
42
43 (
44 Self(self.0.slice_clone(..split_at)),
45 Self(self.0.slice_clone(split_at..)),
46 )
47 }
48}