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

implement is_zeroes for checking all-zero hex strings #16

Closed
wants to merge 1 commit into from
Closed
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
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(""));
}