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 Integer::MAX_STR_LEN and use it to tell the compiler about the max buffer size #45

Merged
merged 1 commit into from
Nov 20, 2024
Merged
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
21 changes: 16 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,17 +95,24 @@ impl Buffer {
/// representation within the buffer.
#[cfg_attr(feature = "no-panic", no_panic)]
pub fn format<I: Integer>(&mut self, i: I) -> &str {
i.write(unsafe {
let str = i.write(unsafe {
&mut *(&mut self.bytes as *mut [MaybeUninit<u8>; I128_MAX_LEN]
as *mut <I as private::Sealed>::Buffer)
})
});
if str.len() > I::MAX_STR_LEN {
unsafe { core::hint::unreachable_unchecked() }
}
str
}
}

/// An integer that can be written into an [`itoa::Buffer`][Buffer].
///
/// This trait is sealed and cannot be implemented for types outside of itoa.
pub trait Integer: private::Sealed {}
pub trait Integer: private::Sealed {
/// The maximum length of the formated str for this integer.
const MAX_STR_LEN: usize;
}

// Seal to prevent downstream implementations of the Integer trait.
mod private {
Expand All @@ -126,7 +133,9 @@ const DEC_DIGITS_LUT: &[u8] = b"\
// https://github.com/rust-lang/rust/blob/b8214dc6c6fc20d0a660fb5700dca9ebf51ebe89/src/libcore/fmt/num.rs#L188-L266
macro_rules! impl_Integer {
($($max_len:expr => $t:ident),* as $conv_fn:ident) => {$(
impl Integer for $t {}
impl Integer for $t {
const MAX_STR_LEN: usize = $max_len;
}

impl private::Sealed for $t {
type Buffer = [MaybeUninit<u8>; $max_len];
Expand Down Expand Up @@ -236,7 +245,9 @@ impl_Integer!(I64_MAX_LEN => isize, U64_MAX_LEN => usize as u64);

macro_rules! impl_Integer128 {
($($max_len:expr => $t:ident),*) => {$(
impl Integer for $t {}
impl Integer for $t {
const MAX_STR_LEN: usize = $max_len;
}

impl private::Sealed for $t {
type Buffer = [MaybeUninit<u8>; $max_len];
Expand Down