@@ -400,28 +400,25 @@ fn check_hrp(hrp: &str) -> Result<Case, Error> {
400
400
///
401
401
/// # Errors
402
402
/// * If [check_hrp] returns an error for the given HRP.
403
+ /// * If `fmt` fails on write
403
404
/// # Deviations from standard
404
405
/// * No length limits are enforced for the data part
405
406
pub fn encode_to_fmt < T : AsRef < [ u5 ] > > (
406
407
fmt : & mut fmt:: Write ,
407
408
hrp : & str ,
408
409
data : T ,
409
410
variant : Variant ,
410
- ) -> Result < fmt :: Result , Error > {
411
+ ) -> Result < ( ) , Error > {
411
412
let hrp_lower = match check_hrp ( hrp) ? {
412
413
Case :: Upper => Cow :: Owned ( hrp. to_lowercase ( ) ) ,
413
414
Case :: Lower | Case :: None => Cow :: Borrowed ( hrp) ,
414
415
} ;
415
416
416
- match Bech32Writer :: new ( & hrp_lower, variant, fmt) {
417
- Ok ( mut writer) => {
418
- Ok ( writer. write ( data. as_ref ( ) ) . and_then ( |_| {
419
- // Finalize manually to avoid panic on drop if write fails
420
- writer. finalize ( )
421
- } ) )
422
- }
423
- Err ( e) => Ok ( Err ( e) ) ,
424
- }
417
+ let mut writer = Bech32Writer :: new ( & hrp_lower, variant, fmt) ?;
418
+ Ok ( writer. write ( data. as_ref ( ) ) . and_then ( |_| {
419
+ // Finalize manually to avoid panic on drop if write fails
420
+ writer. finalize ( )
421
+ } ) ?)
425
422
}
426
423
427
424
/// Used for encode/decode operations for the two variants of Bech32
@@ -462,7 +459,7 @@ impl Variant {
462
459
/// * No length limits are enforced for the data part
463
460
pub fn encode < T : AsRef < [ u5 ] > > ( hrp : & str , data : T , variant : Variant ) -> Result < String , Error > {
464
461
let mut buf = String :: new ( ) ;
465
- encode_to_fmt ( & mut buf, hrp, data, variant) ?. unwrap ( ) ;
462
+ encode_to_fmt ( & mut buf, hrp, data, variant) ?;
466
463
Ok ( buf)
467
464
}
468
465
@@ -624,6 +621,14 @@ pub enum Error {
624
621
InvalidPadding ,
625
622
/// The whole string must be of one case
626
623
MixedCase ,
624
+ /// Writing UTF-8 data failed
625
+ WriteFailure ( fmt:: Error ) ,
626
+ }
627
+
628
+ impl From < fmt:: Error > for Error {
629
+ fn from ( error : fmt:: Error ) -> Self {
630
+ Self :: WriteFailure ( error)
631
+ }
627
632
}
628
633
629
634
impl fmt:: Display for Error {
@@ -636,6 +641,7 @@ impl fmt::Display for Error {
636
641
Error :: InvalidData ( n) => write ! ( f, "invalid data point ({})" , n) ,
637
642
Error :: InvalidPadding => write ! ( f, "invalid padding" ) ,
638
643
Error :: MixedCase => write ! ( f, "mixed-case strings not allowed" ) ,
644
+ Error :: WriteFailure ( _) => write ! ( f, "failed writing utf-8 data" ) ,
639
645
}
640
646
}
641
647
}
@@ -651,6 +657,7 @@ impl std::error::Error for Error {
651
657
Error :: InvalidData ( _) => "invalid data point" ,
652
658
Error :: InvalidPadding => "invalid padding" ,
653
659
Error :: MixedCase => "mixed-case strings not allowed" ,
660
+ Error :: WriteFailure ( _) => "failed writing utf-8 data" ,
654
661
}
655
662
}
656
663
}
0 commit comments