| 1 | use append_only_bytes::{AppendOnlyBytes, BytesSlice}; |
| 2 | |
| 3 | |
| 4 | |
| 5 | pub(crate) struct StrSlice(BytesSlice); |
| 6 | |
| 7 | impl 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 | |
| 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 | |
| 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 | } |