Skip to content

Commit

Permalink
Add an Error variant for fmt::Error
Browse files Browse the repository at this point in the history
This simplifies the return type of encode_to_fmt, which used a nested
Result type.
  • Loading branch information
jkczyz committed Aug 6, 2022
1 parent 1735cb3 commit 0ef5bb9
Showing 1 changed file with 18 additions and 11 deletions.
29 changes: 18 additions & 11 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -400,28 +400,25 @@ fn check_hrp(hrp: &str) -> Result<Case, Error> {
///
/// # Errors
/// * If [check_hrp] returns an error for the given HRP.
/// * If `fmt` fails on write
/// # Deviations from standard
/// * No length limits are enforced for the data part
pub fn encode_to_fmt<T: AsRef<[u5]>>(
fmt: &mut fmt::Write,
hrp: &str,
data: T,
variant: Variant,
) -> Result<fmt::Result, Error> {
) -> Result<(), Error> {
let hrp_lower = match check_hrp(hrp)? {
Case::Upper => Cow::Owned(hrp.to_lowercase()),
Case::Lower | Case::None => Cow::Borrowed(hrp),
};

match Bech32Writer::new(&hrp_lower, variant, fmt) {
Ok(mut writer) => {
Ok(writer.write(data.as_ref()).and_then(|_| {
// Finalize manually to avoid panic on drop if write fails
writer.finalize()
}))
}
Err(e) => Ok(Err(e)),
}
let mut writer = Bech32Writer::new(&hrp_lower, variant, fmt)?;
Ok(writer.write(data.as_ref()).and_then(|_| {
// Finalize manually to avoid panic on drop if write fails
writer.finalize()
})?)
}

/// Used for encode/decode operations for the two variants of Bech32
Expand Down Expand Up @@ -462,7 +459,7 @@ impl Variant {
/// * No length limits are enforced for the data part
pub fn encode<T: AsRef<[u5]>>(hrp: &str, data: T, variant: Variant) -> Result<String, Error> {
let mut buf = String::new();
encode_to_fmt(&mut buf, hrp, data, variant)?.unwrap();
encode_to_fmt(&mut buf, hrp, data, variant)?;
Ok(buf)
}

Expand Down Expand Up @@ -624,6 +621,14 @@ pub enum Error {
InvalidPadding,
/// The whole string must be of one case
MixedCase,
/// Writing UTF-8 data failed
WriteFailure(fmt::Error),
}

impl From<fmt::Error> for Error {
fn from(error: fmt::Error) -> Self {
Self::WriteFailure(error)
}
}

impl fmt::Display for Error {
Expand All @@ -636,6 +641,7 @@ impl fmt::Display for Error {
Error::InvalidData(n) => write!(f, "invalid data point ({})", n),
Error::InvalidPadding => write!(f, "invalid padding"),
Error::MixedCase => write!(f, "mixed-case strings not allowed"),
Error::WriteFailure(_) => write!(f, "failed writing utf-8 data"),
}
}
}
Expand All @@ -651,6 +657,7 @@ impl std::error::Error for Error {
Error::InvalidData(_) => "invalid data point",
Error::InvalidPadding => "invalid padding",
Error::MixedCase => "mixed-case strings not allowed",
Error::WriteFailure(_) => "failed writing utf-8 data",
}
}
}
Expand Down

0 comments on commit 0ef5bb9

Please sign in to comment.