Skip to content

Commit

Permalink
feat(base32ct): add const encoded_len fn (#1424)
Browse files Browse the repository at this point in the history
This can be handy to avoid an heap allocation, because it is possible to
use the result of the const fn to allocate an array of the right size.
  • Loading branch information
dodomorandi authored May 29, 2024
1 parent dbca6c2 commit 56d3775
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
20 changes: 13 additions & 7 deletions base32ct/src/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,14 +220,9 @@ impl<T: Alphabet> Encoding for T {
}
}

#[inline]
fn encoded_len(bytes: &[u8]) -> usize {
if bytes.is_empty() {
0
} else if Self::PADDED {
((bytes.len() - 1) / 5 + 1) * 8
} else {
(bytes.len() * 8 + 4) / 5
}
encoded_len::<Self>(bytes.len())
}
}

Expand Down Expand Up @@ -259,6 +254,17 @@ fn remove_padding(mut input: &[u8]) -> Result<&[u8]> {
Ok(input)
}

/// Get the length of Base32 produced by encoding the given amount of bytes.
pub const fn encoded_len<T: Encoding>(length: usize) -> usize {
if length == 0 {
0
} else if T::PADDED {
((length - 1) / 5 + 1) * 8
} else {
(length * 8 + 4) / 5
}
}

#[cfg(all(test, feature = "alloc"))]
mod tests {
use crate::{Base32, Base32Unpadded, Encoding};
Expand Down
2 changes: 1 addition & 1 deletion base32ct/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,6 @@ mod error;

pub use crate::{
alphabet::rfc4648::{Base32, Base32Unpadded, Base32Upper, Base32UpperUnpadded},
encoding::Encoding,
encoding::{encoded_len, Encoding},
error::{Error, Result},
};

0 comments on commit 56d3775

Please sign in to comment.