Skip to content

Commit

Permalink
Merge pull request #45 from SUPERCILEX/max-str-len
Browse files Browse the repository at this point in the history
Add Integer::MAX_STR_LEN and use it to tell the compiler about the max buffer size
  • Loading branch information
dtolnay authored Nov 20, 2024
2 parents 6c84006 + 72361cb commit e7b5808
Showing 1 changed file with 16 additions and 5 deletions.
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

0 comments on commit e7b5808

Please sign in to comment.