smol_bytes/utf8_buffer/
from.rs1use core::str::FromStr;
2#[cfg(any(feature = "std", feature = "alloc"))]
3use std::string::ToString;
4
5use super::*;
6
7impl From<&str> for Utf8Buffer {
8 fn from(s: &str) -> Self {
9 let inner = Buffer::try_from(s.as_bytes()).expect("string too large for inline buffer");
10 Self { inner }
11 }
12}
13
14impl Utf8Buffer {
15 pub fn try_from_str(s: &str) -> Result<Self, TryPutError> {
17 let inner = Buffer::try_from(s.as_bytes())?;
18 Ok(Self { inner })
19 }
20}
21
22impl FromStr for Utf8Buffer {
23 type Err = TryPutError;
24
25 fn from_str(s: &str) -> Result<Self, Self::Err> {
26 Self::try_from_str(s)
27 }
28}
29
30impl From<Utf8Buffer> for Buffer {
31 #[cfg_attr(not(coverage), inline(always))]
32 fn from(value: Utf8Buffer) -> Self {
33 value.inner
34 }
35}
36
37impl TryFrom<Buffer> for Utf8Buffer {
38 type Error = core::str::Utf8Error;
39
40 fn try_from(buffer: Buffer) -> Result<Self, Self::Error> {
41 core::str::from_utf8(buffer.as_slice())?;
43 Ok(Self { inner: buffer })
44 }
45}
46
47impl TryFrom<&[u8]> for Utf8Buffer {
48 type Error = FromBytesError;
49
50 fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
53 let s = core::str::from_utf8(bytes)?;
54 Ok(Self::try_from_str(s)?)
55 }
56}
57
58#[cfg(any(feature = "std", feature = "alloc"))]
59const _: () = {
60 use std::{boxed::Box, rc::Rc, string::String, sync::Arc};
61
62 impl From<Utf8Buffer> for String {
63 fn from(value: Utf8Buffer) -> Self {
64 value.as_str().to_string()
65 }
66 }
67
68 impl From<Utf8Buffer> for Box<str> {
69 fn from(value: Utf8Buffer) -> Self {
70 value.as_str().into()
71 }
72 }
73
74 impl From<Utf8Buffer> for Arc<str> {
75 fn from(value: Utf8Buffer) -> Self {
76 value.as_str().into()
77 }
78 }
79
80 impl From<Utf8Buffer> for Rc<str> {
81 fn from(value: Utf8Buffer) -> Self {
82 value.as_str().into()
83 }
84 }
85
86 impl TryFrom<String> for Utf8Buffer {
87 type Error = TryPutError;
88
89 fn try_from(s: String) -> Result<Self, Self::Error> {
90 Self::try_from_str(s.as_str())
91 }
92 }
93
94 impl TryFrom<&String> for Utf8Buffer {
95 type Error = TryPutError;
96
97 fn try_from(s: &String) -> Result<Self, Self::Error> {
98 Self::try_from_str(s.as_str())
99 }
100 }
101
102 impl TryFrom<Box<str>> for Utf8Buffer {
103 type Error = TryPutError;
104
105 fn try_from(s: Box<str>) -> Result<Self, Self::Error> {
106 Self::try_from_str(s.as_ref())
107 }
108 }
109
110 impl TryFrom<Arc<str>> for Utf8Buffer {
111 type Error = TryPutError;
112
113 fn try_from(s: Arc<str>) -> Result<Self, Self::Error> {
114 Self::try_from_str(s.as_ref())
115 }
116 }
117
118 impl TryFrom<Rc<str>> for Utf8Buffer {
119 type Error = TryPutError;
120
121 fn try_from(s: Rc<str>) -> Result<Self, Self::Error> {
122 Self::try_from_str(s.as_ref())
123 }
124 }
125};