Skip to content
Open
Show file tree
Hide file tree
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: 4 additions & 17 deletions src/uucore/src/lib/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -591,23 +591,10 @@ pub enum CharByte {
Byte(u8),
}

impl From<char> for CharByte {
fn from(value: char) -> Self {
Self::Char(value)
}
}

impl From<u8> for CharByte {
fn from(value: u8) -> Self {
Self::Byte(value)
}
}

impl From<&u8> for CharByte {
fn from(value: &u8) -> Self {
Self::Byte(*value)
}
}
impl_from_for_enum!(CharByte:
char => Char;
u8 => Byte, ref
);

struct Utf8ChunkIterator<'a> {
iter: Box<dyn Iterator<Item = CharByte> + 'a>,
Expand Down
65 changes: 65 additions & 0 deletions src/uucore/src/lib/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,3 +194,68 @@ macro_rules! show_warning_caps(
let _ = writeln!(error, $($args)+);
})
);

/// Implement [`From`] for an enum with simple variant mappings.
///
/// This macro generates `From<T>` implementations for the specified enum,
/// mapping each input type to a corresponding enum variant. Optionally,
/// it can also generate `From<&T>` implementations by copying the value.
///
/// # Syntax
///
/// ```ignore
/// impl_from_for_enum!(EnumName:
/// Type1 => Variant1,
/// Type2 => Variant2, ref
/// );
/// ```
///
/// - `Type => Variant` generates `impl From<Type> for Enum`.
/// - Adding `, ref` additionally generates `impl From<&Type> for Enum`,
/// dereferencing the input value.
///
/// # Examples
///
/// ```ignore
/// impl_from_for_enum!(CharByte:
/// char => Char,
/// u8 => Byte, ref
/// );
/// ```
///
/// This expands roughly to:
///
/// ```ignore
/// impl From<char> for CharByte { ... }
/// impl From<u8> for CharByte { ... }
/// impl From<&u8> for CharByte { ... }
/// ```
///
/// # Notes
///
/// - The referenced implementations (`From<&T>`) require `T: Copy`.
/// - This macro is intended for simple enum wrappers where variants
/// directly wrap the input type.
#[macro_export]
macro_rules! impl_from_for_enum {
( @step $enum:ident, $type:ty => $variant:ident, ref ) => {
impl From<$type> for $enum {
fn from(value: $type) -> Self { $enum::$variant(value) }
}
impl From<&$type> for $enum {
fn from(value: &$type) -> Self { $enum::$variant(*value) }
}
};

( @step $enum:ident, $type:ty => $variant:ident ) => {
impl From<$type> for $enum {
fn from(value: $type) -> Self { $enum::$variant(value) }
}
};

( $enum:ident : $( $type:ty => $variant:ident $(, $r:ident)? );* $(;)? ) => {
$(
$crate::impl_from_for_enum!(@step $enum, $type => $variant $(, $r)?);
)*
};
}
Loading