@@ -21,6 +21,10 @@ use arbitrary::{Arbitrary, Unstructured};
2121/// let data = [0x48, 0x45, 0x4c, 0x4c, 0x4f, 0x00, 0x57, 0x4f, 0x52, 0x4c, 0x44, 0x00, 0x00, 0x00];
2222/// let ca = CharArray::new(data);
2323/// assert_eq!(ca.to_str().unwrap(), "HELLO");
24+ /// // or using the from str method
25+ /// let ca: CharArray<10> = "HELLO!".into();
26+ /// assert_eq!(ca.to_str().unwrap(), "HELLO!");
27+ ///
2428/// ```
2529#[ cfg_attr( feature = "serde" , derive( Serialize ) ) ]
2630#[ cfg_attr( feature = "serde" , serde( transparent) ) ]
@@ -101,6 +105,16 @@ impl<const N: usize> From<CharArray<N>> for [u8; N] {
101105 }
102106}
103107
108+ impl < const N : usize > From < & str > for CharArray < N > {
109+ fn from ( s : & str ) -> Self {
110+ let mut data = [ 0u8 ; N ] ;
111+ let bytes = s. as_bytes ( ) ;
112+ let len = bytes. len ( ) . min ( N ) ;
113+ data[ ..len] . copy_from_slice ( & bytes[ ..len] ) ;
114+ Self :: new ( data)
115+ }
116+ }
117+
104118impl < const N : usize > crate :: utils:: RustDefault for CharArray < N > {
105119 #[ inline( always) ]
106120 fn rust_default ( ) -> Self {
@@ -149,4 +163,15 @@ mod tests {
149163 assert_eq ! ( ca. len( ) , 10 ) ;
150164 assert_eq ! ( ca. to_str( ) . unwrap( ) , "abc" ) ;
151165 }
166+
167+ #[ test]
168+ fn char_array_from_str_into_str ( ) {
169+ let ca: CharArray < 10 > = "HELLOWORLD" . into ( ) ;
170+ assert_eq ! ( ca. len( ) , 10 ) ;
171+ assert_eq ! ( ca. to_str( ) . unwrap( ) , "HELLOWORLD" ) ;
172+
173+ let ca: CharArray < 10 > = "abc" . into ( ) ;
174+ assert_eq ! ( ca. len( ) , 10 ) ;
175+ assert_eq ! ( ca. to_str( ) . unwrap( ) , "abc" ) ;
176+ }
152177}
0 commit comments