rustolio_utils/bytes/
utf8.rs1use std::ops::Deref;
12
13use super::Bytes;
14
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct Utf8Bytes(Bytes);
17
18impl Deref for Utf8Bytes {
19 type Target = Bytes;
20 fn deref(&self) -> &Self::Target {
21 &self.0
22 }
23}
24
25impl Utf8Bytes {
26 pub fn as_str(&self) -> &str {
27 unsafe { str::from_utf8_unchecked(&self.0) }
28 }
29}
30
31impl From<Utf8Bytes> for String {
32 fn from(val: Utf8Bytes) -> Self {
33 unsafe { String::from_utf8_unchecked(val.to_vec()) }
34 }
35}
36
37impl From<Utf8Bytes> for Bytes {
38 fn from(val: Utf8Bytes) -> Self {
39 val.0
40 }
41}
42
43pub trait IntoUtf8Bytes: Into<Bytes> + AsRef<str> {
44 fn into_utf8_bytes(self) -> Utf8Bytes {
45 Utf8Bytes(self.into())
46 }
47}
48impl<T> IntoUtf8Bytes for T where T: Into<Bytes> + AsRef<str> {}
49
50#[cfg(test)]
51mod tests {
52 use super::*;
53
54 #[test]
55 fn test_into_utf8_bytes() {
56 fn f(b: impl IntoUtf8Bytes) {
57 let b = b.into();
58 let _ = unsafe { str::from_utf8_unchecked(&b) };
59 }
60
61 let s = "str";
62 f(s);
63 let s = String::from("string");
64 f(s);
65
66 }
69}