1#![no_std]
2use core::cmp::Ordering;
3
4pub const fn compare_str(a: &str, b: &str) -> Ordering {
5 let a = a.as_bytes();
6 let b = b.as_bytes();
7 let mut i = 0;
8 loop {
9 match (i >= a.len(), i >= b.len()) {
10 (true, true) => break,
11 (true, false) => return Ordering::Less,
12 (false, true) => return Ordering::Greater,
13 (false, false) => (),
14 }
15 if a[i] > b[i] {
16 return Ordering::Greater;
17 }
18 if a[i] < b[i] {
19 return Ordering::Less;
20 }
21 i += 1;
22 }
23 Ordering::Equal
24}
25
26#[cfg(test)]
27mod tests {
28 use crate::compare_str;
29
30 #[test]
31 const fn test_some_strings() {
32 assert!(compare_str("a", "b").is_lt());
33 assert!(!compare_str("a", "b").is_gt());
34 assert!(!compare_str("a", "b").is_eq());
35 assert!(compare_str("a", "a").is_eq());
36 assert!(compare_str("a", "aa").is_lt());
37 assert!(compare_str("b", "aa").is_gt());
38 assert!(compare_str("ba", "aa").is_gt());
39 assert!(compare_str("baa", "aa").is_gt());
40 assert!(compare_str("aaa", "aa").is_gt());
41 assert!(compare_str("aaa", "ab").is_lt());
42 }
43}