Created
July 20, 2023 15:59
-
-
Save sam0x17/8fa690ac2f235a9a09d98d547fac9ce5 to your computer and use it in GitHub Desktop.
Rust const_str_eq
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(can't use for loops in const context, so we we manually increment
i
in a while loop)