@@ -67,7 +67,7 @@ extern crate core;
6767use alloc:: borrow:: Cow ;
6868#[ cfg( all( not( feature = "std" ) , not( test) ) ) ]
6969use alloc:: { string:: String , vec:: Vec } ;
70- use core:: convert:: Infallible ;
70+ use core:: convert:: { Infallible , TryFrom } ;
7171use core:: { fmt, mem} ;
7272#[ cfg( any( feature = "std" , test) ) ]
7373use std:: borrow:: Cow ;
@@ -78,15 +78,6 @@ use std::borrow::Cow;
7878pub struct u5 ( u8 ) ;
7979
8080impl u5 {
81- /// Convert a `u8` to `u5` if in range, return `Error` otherwise
82- pub fn try_from_u8 ( value : u8 ) -> Result < u5 , Error > {
83- if value > 31 {
84- Err ( Error :: InvalidData ( value) )
85- } else {
86- Ok ( u5 ( value) )
87- }
88- }
89-
9081 /// Returns a copy of the underlying `u8` value
9182 pub fn to_u8 ( self ) -> u8 { self . 0 }
9283
@@ -98,6 +89,19 @@ impl From<u5> for u8 {
9889 fn from ( v : u5 ) -> u8 { v. 0 }
9990}
10091
92+ impl TryFrom < u8 > for u5 {
93+ type Error = Error ;
94+
95+ /// Errors if `value` is out of range.
96+ fn try_from ( value : u8 ) -> Result < Self , Self :: Error > {
97+ if value > 31 {
98+ Err ( Error :: InvalidData ( value) )
99+ } else {
100+ Ok ( u5 ( value) )
101+ }
102+ }
103+ }
104+
101105impl AsRef < u8 > for u5 {
102106 fn as_ref ( & self ) -> & u8 { & self . 0 }
103107}
@@ -327,7 +331,7 @@ impl<T: AsRef<[u8]>> CheckBase32<Vec<u5>> for T {
327331 type Err = Error ;
328332
329333 fn check_base32 ( self ) -> Result < Vec < u5 > , Self :: Err > {
330- self . as_ref ( ) . iter ( ) . map ( |x| u5:: try_from_u8 ( * x) ) . collect :: < Result < Vec < u5 > , Error > > ( )
334+ self . as_ref ( ) . iter ( ) . map ( |x| u5:: try_from ( * x) ) . collect :: < Result < Vec < u5 > , Error > > ( )
331335 }
332336}
333337
@@ -566,7 +570,7 @@ fn split_and_decode(s: &str) -> Result<(String, Vec<u5>), Error> {
566570 return Err ( Error :: InvalidChar ( c) ) ;
567571 }
568572
569- Ok ( u5:: try_from_u8 ( num_value as u8 ) . expect ( "range checked above, num_value <= 31" ) )
573+ Ok ( u5:: try_from ( num_value as u8 ) . expect ( "range checked above, num_value <= 31" ) )
570574 } )
571575 . collect :: < Result < Vec < u5 > , Error > > ( ) ?;
572576
@@ -582,11 +586,11 @@ fn verify_checksum(hrp: &[u8], data: &[u5]) -> Option<Variant> {
582586fn hrp_expand ( hrp : & [ u8 ] ) -> Vec < u5 > {
583587 let mut v: Vec < u5 > = Vec :: new ( ) ;
584588 for b in hrp {
585- v. push ( u5:: try_from_u8 ( * b >> 5 ) . expect ( "can't be out of range, max. 7" ) ) ;
589+ v. push ( u5:: try_from ( * b >> 5 ) . expect ( "can't be out of range, max. 7" ) ) ;
586590 }
587- v. push ( u5:: try_from_u8 ( 0 ) . unwrap ( ) ) ;
591+ v. push ( u5:: try_from ( 0 ) . unwrap ( ) ) ;
588592 for b in hrp {
589- v. push ( u5:: try_from_u8 ( * b & 0x1f ) . expect ( "can't be out of range, max. 31" ) ) ;
593+ v. push ( u5:: try_from ( * b & 0x1f ) . expect ( "can't be out of range, max. 31" ) ) ;
590594 }
591595 v
592596}
0 commit comments