@@ -36,16 +36,10 @@ where
36
36
}
37
37
38
38
fn validate_channel_id ( s : & str ) -> Result < [ u8 ; 32 ] , FromHexError > {
39
- match ( s. get ( 0 ..2 ) , s. get ( 2 ..) ) {
40
- ( Some ( prefix) , Some ( hex) ) => {
41
- if hex. len ( ) != 64 || prefix != "0x" {
42
- Err ( FromHexError :: InvalidStringLength )
43
- } else {
44
- Ok ( <[ u8 ; 32 ] as FromHex >:: from_hex ( s) ?)
45
- }
46
- }
47
- _ => Err ( FromHexError :: InvalidStringLength ) ,
48
- }
39
+ // strip `0x` prefix
40
+ let hex = s. strip_prefix ( "0x" ) . unwrap_or ( s) ;
41
+ // FromHex will make sure to check the length and match it to 32 bytes
42
+ <[ u8 ; 32 ] as FromHex >:: from_hex ( hex)
49
43
}
50
44
51
45
impl Deref for ChannelId {
@@ -88,7 +82,7 @@ impl FromStr for ChannelId {
88
82
type Err = FromHexError ;
89
83
90
84
fn from_str ( s : & str ) -> Result < Self , Self :: Err > {
91
- ChannelId :: from_hex ( validate_channel_id ( s) ? )
85
+ validate_channel_id ( s) . map ( ChannelId )
92
86
}
93
87
}
94
88
@@ -331,6 +325,44 @@ impl Error for ChannelError {
331
325
}
332
326
}
333
327
328
+ #[ cfg( test) ]
329
+ mod test {
330
+ use super :: * ;
331
+
332
+ #[ test]
333
+ fn test_channel_id_ ( ) {
334
+ let hex_string = "061d5e2a67d0a9a10f1c732bca12a676d83f79663a396f7d87b3e30b9b411088" ;
335
+ let prefixed_string = format ! ( "0x{}" , hex_string) ;
336
+
337
+ let expected_id = ChannelId ( [
338
+ 0x06 , 0x1d , 0x5e , 0x2a , 0x67 , 0xd0 , 0xa9 , 0xa1 , 0x0f , 0x1c , 0x73 , 0x2b , 0xca , 0x12 ,
339
+ 0xa6 , 0x76 , 0xd8 , 0x3f , 0x79 , 0x66 , 0x3a , 0x39 , 0x6f , 0x7d , 0x87 , 0xb3 , 0xe3 , 0x0b ,
340
+ 0x9b , 0x41 , 0x10 , 0x88 ,
341
+ ] ) ;
342
+
343
+ assert_eq ! ( ChannelId :: from_str( hex_string) . unwrap( ) , expected_id) ;
344
+ assert_eq ! ( ChannelId :: from_str( & prefixed_string) . unwrap( ) , expected_id) ;
345
+ assert_eq ! ( ChannelId :: from_hex( hex_string) . unwrap( ) , expected_id) ;
346
+
347
+ let hex_value = serde_json:: Value :: String ( hex_string. to_string ( ) ) ;
348
+ let prefixed_value = serde_json:: Value :: String ( prefixed_string. clone ( ) ) ;
349
+
350
+ // Deserialization from JSON
351
+ let de_hex_json = serde_json:: from_value :: < ChannelId > ( hex_value. clone ( ) )
352
+ . expect ( "Should deserialize" ) ;
353
+ let de_prefixed_json =
354
+ serde_json:: from_value :: < ChannelId > ( prefixed_value. clone ( ) ) . expect ( "Should deserialize" ) ;
355
+
356
+ assert_eq ! ( de_hex_json, expected_id) ;
357
+ assert_eq ! ( de_prefixed_json, expected_id) ;
358
+
359
+ // Serialization to JSON
360
+ let actual_serialized = serde_json:: to_value ( expected_id) . expect ( "Should Serialize" ) ;
361
+ // we don't expect any capitalization
362
+ assert_eq ! ( actual_serialized, serde_json:: Value :: String ( prefixed_string) )
363
+ }
364
+ }
365
+
334
366
#[ cfg( feature = "postgres" ) ]
335
367
pub mod postgres {
336
368
use super :: ChannelId ;
0 commit comments