@@ -116,6 +116,23 @@ impl<const N: usize> Hex for FixedSizeData<N> {
116116 }
117117}
118118
119+ impl < const N : usize > std:: str:: FromStr for FixedSizeData < N > {
120+ type Err = Error ;
121+
122+ fn from_str ( s : & str ) -> StdResult < Self , Self :: Err > {
123+ // Use your existing decode logic
124+ let bytes = decode_hex ( s) ?;
125+ FixedSizeData :: try_from ( bytes)
126+ }
127+ }
128+
129+ impl < const N : usize > fmt:: Display for FixedSizeData < N > {
130+ fn fmt ( & self , f : & mut fmt:: Formatter < ' _ > ) -> fmt:: Result {
131+ // Reuse your existing `encode_hex` function for printing
132+ write ! ( f, "{}" , self . encode_hex( ) )
133+ }
134+ }
135+
119136struct FixedSizeDataVisitor < const N : usize > ;
120137
121138impl < ' de , const N : usize > Visitor < ' de > for FixedSizeDataVisitor < N > {
@@ -197,4 +214,33 @@ mod tests {
197214 & [ Token :: Str ( "0x00000042" ) ] ,
198215 ) ;
199216 }
217+
218+ /// test from_string
219+ #[ test]
220+ fn test_from_str_valid ( ) {
221+ let data = FSD4 :: from_str ( "0x00420000" ) . expect ( "valid 4-byte hex" ) ;
222+ assert_eq ! ( data, FSD4 :: from( hex!( "00420000" ) ) ) ;
223+ }
224+
225+ #[ test]
226+ fn test_from_str_missing_prefix ( ) {
227+ // Missing "0x" prefix: should fail
228+ let data = FSD4 :: from_str ( "00420000" ) ;
229+ assert ! ( data. is_err( ) ) ;
230+ }
231+
232+ #[ test]
233+ fn test_from_str_wrong_length ( ) {
234+ // Only 3 bytes (0x004200) instead of 4
235+ let data = FSD4 :: from_str ( "0x004200" ) ;
236+ assert ! ( data. is_err( ) ) ;
237+ }
238+
239+ /// test to_string
240+ #[ test]
241+ fn test_display ( ) {
242+ let data = FSD4 :: from ( hex ! ( "42feed00" ) ) ;
243+ // Check that Display prints the 0x-prefixed hex
244+ assert_eq ! ( data. to_string( ) , "0x42feed00" ) ;
245+ }
200246}
0 commit comments