hyper_old_types/common/
str.rs

1use std::ops::Deref;
2use std::str;
3
4use bytes::Bytes;
5
6#[derive(Debug, Clone, PartialEq, Eq, Hash)]
7pub struct ByteStr(Bytes);
8
9impl ByteStr {
10    pub unsafe fn from_utf8_unchecked(slice: Bytes) -> ByteStr {
11        ByteStr(slice)
12    }
13
14    pub fn from_static(s: &'static str) -> ByteStr {
15        ByteStr(Bytes::from_static(s.as_bytes()))
16    }
17
18    pub fn slice(&self, from: usize, to: usize) -> ByteStr {
19        assert!(self.as_str().is_char_boundary(from));
20        assert!(self.as_str().is_char_boundary(to));
21        ByteStr(self.0.slice(from, to))
22    }
23
24    pub fn slice_to(&self, idx: usize) -> ByteStr {
25        assert!(self.as_str().is_char_boundary(idx));
26        ByteStr(self.0.slice_to(idx))
27    }
28
29    pub fn as_str(&self) -> &str {
30        unsafe { str::from_utf8_unchecked(self.0.as_ref()) }
31    }
32
33    pub fn insert(&mut self, idx: usize, ch: char) {
34        let mut s = self.as_str().to_owned();
35        s.insert(idx, ch);
36        let bytes = Bytes::from(s);
37        self.0 = bytes;
38    }
39
40    #[cfg(feature = "compat")]
41    pub fn into_bytes(self) -> Bytes {
42        self.0
43    }
44}
45
46impl Deref for ByteStr {
47    type Target = str;
48    fn deref(&self) -> &str {
49        self.as_str()
50    }
51}
52
53impl<'a> From<&'a str> for ByteStr {
54    fn from(s: &'a str) -> ByteStr {
55        ByteStr(Bytes::from(s))
56    }
57}