Skip to content

Instantly share code, notes, and snippets.

@sam0x17
Created July 20, 2023 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sam0x17/8fa690ac2f235a9a09d98d547fac9ce5 to your computer and use it in GitHub Desktop.
Save sam0x17/8fa690ac2f235a9a09d98d547fac9ce5 to your computer and use it in GitHub Desktop.
Rust const_str_eq
pub const fn const_str_eq(a: &str, b: &str) -> bool {
if a.as_bytes().len() != b.as_bytes().len() {
return false;
}
let mut i = 0;
while i < a.as_bytes().len() {
if a.as_bytes()[i] != b.as_bytes()[i] {
return false;
}
i += 1;
}
true
}
#[test]
fn test_const_str_eq() {
const ARE_THEY: bool = const_str_eq("hello", "world");
assert_eq!(ARE_THEY, false);
const ARE_THEY2: bool = const_str_eq("hello world", "hello world");
assert_eq!(ARE_THEY2, true);
const ARE_THEY3: bool = const_str_eq("hello_world", "hello world");
assert_eq!(ARE_THEY3, false);
}
@sam0x17
Copy link
Author

sam0x17 commented Jul 20, 2023

(can't use for loops in const context, so we we manually increment i in a while loop)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment