Skip to main content

smol_bytes/buffer/
from.rs

1use super::*;
2
3impl<'a> TryFrom<&'a Buffer> for &'a str {
4  type Error = core::str::Utf8Error;
5
6  fn try_from(value: &'a Buffer) -> Result<Self, Self::Error> {
7    core::str::from_utf8(value.as_slice())
8  }
9}
10
11#[cfg(any(feature = "std", feature = "alloc"))]
12impl TryFrom<Buffer> for std::string::String {
13  type Error = core::str::Utf8Error;
14
15  fn try_from(value: Buffer) -> Result<Self, Self::Error> {
16    use std::string::ToString;
17    let s = core::str::from_utf8(value.as_slice())?;
18    Ok(s.to_string())
19  }
20}
21
22macro_rules! from_array {
23  ($($size:literal),+$(,)?) => {
24    $(
25      impl From<[u8; $size]> for Buffer {
26        fn from(value: [u8; $size]) -> Self {
27          let mut this = Self::new();
28          this.put_slice(value.as_slice());
29          this
30        }
31      }
32    )*
33  };
34}
35
36impl From<[u8; INLINE_CAP]> for Buffer {
37  fn from(value: [u8; INLINE_CAP]) -> Self {
38    Self {
39      end: InlineSize::_V62,
40      cur: InlineSize::_V0,
41      // SAFETY: `u8` and `MaybeUninit<u8>` have identical layout, and every
42      // source byte is initialized, establishing the Buffer invariant.
43      buf: unsafe { transmute::<[u8; INLINE_CAP], [MaybeUninit<u8>; INLINE_CAP]>(value) },
44    }
45  }
46}
47
48from_array!(
49  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
50  27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
51  51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
52);
53
54macro_rules! try_from {
55  ($($method:ident($ty: ty)),+$(,)?) => {
56    $(
57      impl TryFrom<$ty> for Buffer {
58        type Error = TryPutError;
59
60        fn try_from(value: $ty) -> Result<Self, Self::Error> {
61          let mut this = Self::new();
62          this.try_put_slice(value.$method()).map(|_| this)
63        }
64      }
65    )*
66  };
67}
68
69try_from!(as_bytes(&str), as_ref(&[u8]),);
70
71#[cfg(any(feature = "std", feature = "alloc"))]
72const _: () = {
73  use std::{boxed::Box, rc::Rc, string::String, sync::Arc, vec::Vec};
74
75  try_from!(
76    as_slice(Vec<u8>),
77    as_bytes(String),
78    as_ref(Arc<[u8]>),
79    as_ref(Rc<[u8]>),
80    as_ref(Box<[u8]>),
81    as_bytes(Arc<str>),
82    as_bytes(Rc<str>),
83    as_bytes(Box<str>),
84    as_ref(::bytes::Bytes),
85    as_ref(::bytes::BytesMut),
86  );
87};