Skip to content

Commit

Permalink
[Breaking] Add MAX_LENGTH associated constant
Browse files Browse the repository at this point in the history
  • Loading branch information
GnomedDev committed May 8, 2024
1 parent ddd6be8 commit acd140a
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ mod macros;

/// A no-alloc version of [`ToString`] implemented for bool/integer/float types formatting into an [`ArrayString`].
pub trait ToArrayString: Copy {
/// The maximum length that Self can be formatted into. This is used for the capacity generic of [`ArrayString`].
///
/// # Note for implementors
/// This must match the capacity generic used in [`ArrayString`], otherwise logic bugs and panics may occur.
const MAX_LENGTH: usize;

/// An associated type to turn [`ArrayString`]'s const generic into a type generic,
/// working around limitations of the current type system.
///
Expand All @@ -33,6 +39,7 @@ pub trait ToArrayString: Copy {
}

impl<const MAX_LENGTH: usize> ToArrayString for ArrayString<MAX_LENGTH> {
const MAX_LENGTH: usize = MAX_LENGTH;
type ArrayString = ArrayString<MAX_LENGTH>;

fn to_arraystring(self) -> Self::ArrayString {
Expand All @@ -41,6 +48,7 @@ impl<const MAX_LENGTH: usize> ToArrayString for ArrayString<MAX_LENGTH> {
}

impl ToArrayString for char {
const MAX_LENGTH: usize = 4;
type ArrayString = ArrayString<4>;

fn to_arraystring(self) -> Self::ArrayString {
Expand All @@ -52,6 +60,7 @@ impl ToArrayString for char {
}

impl ToArrayString for bool {
const MAX_LENGTH: usize = 5;
type ArrayString = ArrayString<5>;

fn to_arraystring(self) -> Self::ArrayString {
Expand Down
2 changes: 2 additions & 0 deletions src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ macro_rules! gen_impl {
macro_rules! $name {
(ToArrayString<$len:literal> for $type:ty) => {
impl ToArrayString for $type {
const MAX_LENGTH: usize = $len;
type ArrayString = ArrayString<$len>;

fn to_arraystring(self) -> Self::ArrayString {
$body(self)
}
Expand Down

0 comments on commit acd140a

Please sign in to comment.