Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add encode_to_fmt method for efficient encoding #30

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 18 additions & 11 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,19 +226,26 @@ impl Bech32 {
}
}

/// Encode a bech32 payload to an [fmt::Formatter].
pub fn encode_to_fmt<T: AsRef<[u5]>>(fmt: &mut fmt::Formatter, hrp: &str, data: T) -> fmt::Result {
let hrp_bytes: &[u8] = hrp.as_bytes();
let checksum = create_checksum(hrp_bytes, data.as_ref());
let data_part = data.as_ref().iter().chain(checksum.iter());

write!(
fmt,
"{}{}{}",
hrp,
SEP,
data_part
.map(|p| CHARSET[*p.as_ref() as usize])
.collect::<String>()
)
}

impl Display for Bech32 {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let hrp_bytes: &[u8] = self.hrp.as_bytes();
let checksum = create_checksum(hrp_bytes, &self.data);
let data_part = self.data.iter().chain(checksum.iter());

write!(
f,
"{}{}{}",
self.hrp,
SEP,
data_part.map(|p| CHARSET[*p.as_ref() as usize]).collect::<String>()
)
encode_to_fmt(f, &self.hrp, &self.data)
}
}

Expand Down