Skip to content

Commit 1735cb3

Browse files
committed
Use a constant for checksum length
1 parent 9a57c97 commit 1735cb3

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

src/lib.rs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,8 @@ pub trait WriteBase32 {
128128
fn write_u5(&mut self, data: u5) -> Result<(), Self::Err>;
129129
}
130130

131+
const CHECKSUM_LENGTH: usize = 6;
132+
131133
/// Allocationless Bech32 writer that accumulates the checksum data internally and writes them out
132134
/// in the end.
133135
pub struct Bech32Writer<'a> {
@@ -187,13 +189,13 @@ impl<'a> Bech32Writer<'a> {
187189

188190
fn inner_finalize(&mut self) -> fmt::Result {
189191
// Pad with 6 zeros
190-
for _ in 0..6 {
192+
for _ in 0..CHECKSUM_LENGTH {
191193
self.polymod_step(u5(0))
192194
}
193195

194196
let plm: u32 = self.chk ^ self.variant.constant();
195197

196-
for p in 0..6 {
198+
for p in 0..CHECKSUM_LENGTH {
197199
self.formatter
198200
.write_char(u5(((plm >> (5 * (5 - p))) & 0x1f) as u8).to_char())?;
199201
}
@@ -469,7 +471,7 @@ pub fn encode<T: AsRef<[u5]>>(hrp: &str, data: T, variant: Variant) -> Result<St
469471
/// Returns the HRP in lowercase..
470472
pub fn decode(s: &str) -> Result<(String, Vec<u5>, Variant), Error> {
471473
// Ensure overall length is within bounds
472-
if s.len() < 8 {
474+
if s.len() < CHECKSUM_LENGTH + 2 {
473475
return Err(Error::InvalidLength);
474476
}
475477

@@ -481,7 +483,7 @@ pub fn decode(s: &str) -> Result<(String, Vec<u5>, Variant), Error> {
481483
(hrp, &data[1..])
482484
}
483485
};
484-
if raw_data.len() < 6 {
486+
if raw_data.len() < CHECKSUM_LENGTH {
485487
return Err(Error::InvalidLength);
486488
}
487489

@@ -533,7 +535,7 @@ pub fn decode(s: &str) -> Result<(String, Vec<u5>, Variant), Error> {
533535
Some(variant) => {
534536
// Remove checksum from data payload
535537
let dbl: usize = data.len();
536-
data.truncate(dbl - 6);
538+
data.truncate(dbl - CHECKSUM_LENGTH);
537539

538540
Ok((hrp_lower, data, variant))
539541
}

0 commit comments

Comments
 (0)