@@ -3,7 +3,7 @@ use std::{cmp::PartialEq, fmt::Write as _, hash::Hash};
3
3
use crate :: {
4
4
array:: FixedArray ,
5
5
inline:: InlineString ,
6
- length:: { get_heap_threshold, SmallLen , ValidLength } ,
6
+ length:: { get_heap_threshold, InvalidStrLength , SmallLen , ValidLength } ,
7
7
} ;
8
8
9
9
#[ cfg_attr( feature = "typesize" , derive( typesize:: derive:: TypeSize ) ) ]
@@ -165,6 +165,24 @@ impl<LenT: ValidLength> std::fmt::Debug for FixedString<LenT> {
165
165
}
166
166
}
167
167
168
+ impl < LenT : ValidLength > TryFrom < Box < str > > for FixedString < LenT > {
169
+ type Error = InvalidStrLength ;
170
+
171
+ fn try_from ( value : Box < str > ) -> Result < Self , Self :: Error > {
172
+ if value. len ( ) <= get_heap_threshold :: < LenT > ( ) {
173
+ let inner = InlineString :: from_str ( & value) ;
174
+ return Ok ( Self ( FixedStringRepr :: Inline ( inner) ) ) ;
175
+ }
176
+
177
+ match value. into_boxed_bytes ( ) . try_into ( ) {
178
+ Ok ( val) => Ok ( Self ( FixedStringRepr :: Heap ( val) ) ) ,
179
+ Err ( err) => Err ( err
180
+ . try_into ( )
181
+ . expect ( "Box<str> -> Box<[u8]> should stay valid UTF8" ) ) ,
182
+ }
183
+ }
184
+ }
185
+
168
186
#[ cfg( any( feature = "log_using_log" , feature = "log_using_tracing" ) ) ]
169
187
impl < LenT : ValidLength > From < String > for FixedString < LenT > {
170
188
fn from ( value : String ) -> Self {
@@ -228,15 +246,15 @@ impl<LenT: ValidLength> serde::Serialize for FixedString<LenT> {
228
246
}
229
247
}
230
248
231
- #[ cfg( all ( test, any ( feature = "log_using_log" , feature = "log_using_tracing" ) ) ) ]
249
+ #[ cfg( test) ]
232
250
mod test {
233
251
use super :: * ;
234
252
235
253
#[ test]
236
254
fn check_u8_roundtrip ( ) {
237
255
for i in 0 ..=u8:: MAX {
238
- let original = "a" . repeat ( i. into ( ) ) ;
239
- let fixed = FixedString :: < u8 > :: from ( original) ;
256
+ let original = "a" . repeat ( i. into ( ) ) . into_boxed_str ( ) ;
257
+ let fixed = FixedString :: < u8 > :: try_from ( original) . unwrap ( ) ;
240
258
241
259
assert ! ( fixed. bytes( ) . all( |c| c == b'a' ) ) ;
242
260
assert_eq ! ( fixed. len( ) , i. into( ) ) ;
0 commit comments