Skip to main content

proctor_libc/strings/
mod.rs

1//! Safe equivalents of functions declared in C's `strings.h` header.
2
3use std::mem;
4
5const WORD_BYTES: usize = mem::size_of::<usize>();
6const LOW_BITS: usize = usize::MAX / 0xff;
7const HIGH_BITS: usize = LOW_BITS * 0x80;
8
9fn has_null_byte(word: usize) -> bool {
10    word.wrapping_sub(LOW_BITS) & !word & HIGH_BITS != 0
11}
12
13fn lowercase(byte: u8) -> u8 {
14    if byte.is_ascii_uppercase() {
15        byte | 0x20
16    } else {
17        byte
18    }
19}
20
21fn bytes_less_than(word: usize, byte: u8) -> usize {
22    let byte = LOW_BITS * usize::from(byte);
23    !word & !(word | HIGH_BITS).wrapping_sub(byte) & HIGH_BITS
24}
25
26fn lowercase_word(word: usize) -> usize {
27    let below_a = bytes_less_than(word, b'A');
28    let at_most_z = bytes_less_than(word, b'Z' + 1);
29    let uppercase = at_most_z & !below_a;
30
31    word | (uppercase >> 2)
32}
33
34fn compare(s1: &[i8], s2: &[i8], n: usize) -> i32 {
35    let s1: &[u8] = bytemuck::cast_slice(s1);
36    let s2: &[u8] = bytemuck::cast_slice(s2);
37    let word_end = n.min(s1.len()).min(s2.len()) / WORD_BYTES * WORD_BYTES;
38    let mut index = 0;
39
40    while index < word_end {
41        let word1 = usize::from_ne_bytes(s1[index..index + WORD_BYTES].try_into().unwrap());
42        let word2 = usize::from_ne_bytes(s2[index..index + WORD_BYTES].try_into().unwrap());
43
44        if lowercase_word(word1) == lowercase_word(word2) && !has_null_byte(word1) {
45            index += WORD_BYTES;
46            continue;
47        }
48
49        for offset in 0..WORD_BYTES {
50            let byte1 = lowercase(s1[index + offset]);
51            let byte2 = lowercase(s2[index + offset]);
52
53            if byte1 != byte2 {
54                return i32::from(byte1) - i32::from(byte2);
55            }
56            if byte1 == 0 {
57                return 0;
58            }
59        }
60
61        index += WORD_BYTES;
62    }
63
64    while index < n {
65        let byte1 = lowercase(s1[index]);
66        let byte2 = lowercase(s2[index]);
67
68        if byte1 != byte2 {
69            return i32::from(byte1) - i32::from(byte2);
70        }
71        if byte1 == 0 {
72            return 0;
73        }
74
75        index += 1;
76    }
77
78    0
79}
80
81/// Compares two null-terminated byte strings while ignoring ASCII case.
82pub fn strcasecmp(s1: &[i8], s2: &[i8]) -> i32 {
83    compare(s1, s2, usize::MAX)
84}
85
86/// Compares at most `n` bytes of two byte strings while ignoring ASCII case.
87pub fn strncasecmp(s1: &[i8], s2: &[i8], n: usize) -> i32 {
88    compare(s1, s2, n)
89}
90
91#[cfg(test)]
92mod tests;