Skip to content

Commit

Permalink
impl is_zeroes feature
Browse files Browse the repository at this point in the history
  • Loading branch information
borngraced committed Nov 2, 2024
1 parent ce406b5 commit 88c7b69
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -627,6 +627,40 @@ unsafe fn decode_checked(input: &[u8], output: &mut [u8]) -> Result<(), FromHexE
Err(unsafe { invalid_hex_error(input) })
}

/// Checks if a hex string contains only zeros ('0' characters).
///
/// Both uppercase and lowercase hex strings are supported, and can be mixed.
/// The '0x' prefix is automatically stripped if present.
///
/// Returns true only if the entire string (after removing any '0x' prefix)
/// consists of '0' characters. Returns false if any non-zero hex digit is found.
///
/// # Example
///
/// ```
/// assert!(const_hex::is_zeroes("000000"));
/// assert!(const_hex::is_zeroes("0x000000"));
///
/// assert!(!const_hex::is_zeroes("100000"));
/// assert!(!const_hex::is_zeroes("0x100000"));
/// assert!(!const_hex::is_zeroes("000100"));
/// assert!(!const_hex::is_zeroes(""));
/// ```
#[cfg(feature = "alloc")]
#[inline]
pub fn is_zeroes(hex: &str) -> bool {
if hex.is_empty() {
return false;
}
let bytes = strip_prefix(hex.as_bytes());
for &b in bytes {
if b != b'0' {
return false;
}
}
true
}

#[inline]
const fn byte2hex<const UPPER: bool>(byte: u8) -> (u8, u8) {
let table = get_chars_table::<UPPER>();
Expand Down
19 changes: 19 additions & 0 deletions tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,3 +214,22 @@ fn assert_upper(s: &str) {
assert_eq!(ALL_UPPER, expected);
assert_eq!(s, expected);
}

#[cfg(feature = "alloc")]
#[test]
fn test_is_zeroes() {
// Test with standard zero-only strings
assert!(const_hex::is_zeroes("00000000"));
assert!(const_hex::is_zeroes("0x00000000"));
assert!(const_hex::is_zeroes("00000000000000000000000000000000"));
assert!(const_hex::is_zeroes("0x00000000000000000000000000000000"));

// Test with non-zero hex strings
assert!(!const_hex::is_zeroes("00000001"));
assert!(!const_hex::is_zeroes("0x00000001"));
assert!(!const_hex::is_zeroes("1234567890abcdef"));
assert!(!const_hex::is_zeroes("0x1234567890abcdef"));

// Test with empty string (could be considered as not zeroes)
assert!(!const_hex::is_zeroes(""));
}

0 comments on commit 88c7b69

Please sign in to comment.