text_fx/transform.rs
1/// In-place translation of a C-style NUL-terminated string, replacing all occurrences of one byte with another.
2///
3/// This function mutates the given pointer to a NUL-terminated string (`*mut i8`), replacing every occurrence
4/// of the byte `from` with the byte `to`. The operation stops at the first NUL byte (`\0`).
5///
6/// # Safety
7///
8/// - The pointer `s` must be valid and point to a mutable, NUL-terminated string.
9/// - The memory must be writable and large enough to contain the string and the NUL terminator.
10/// - Behavior is undefined if `s` is not properly NUL-terminated or is invalid.
11///
12/// # Arguments
13///
14/// * `s` - Pointer to the mutable NUL-terminated string.
15/// * `from` - The byte value to replace.
16/// * `to` - The byte value to substitute.
17///
18/// # Examples
19///
20/// ```
21/// use text_fx::transform::tr;
22///
23/// let mut buf = *b"hello\0";
24/// tr(buf.as_mut_ptr() as *mut _, b'l' as i8, b'p' as i8);
25/// assert_eq!(buf, *b"heppo\0");
26/// ```
27pub fn tr(mut s: *mut i8, from: i8, to: i8) {
28 unsafe {
29 while *s != b'\0' as i8 {
30 if *s == from {
31 *s = to;
32 }
33 s = s.add(1);
34 }
35 }
36}
37
38#[cfg(test)]
39mod tests {
40 use super::*;
41
42 #[test]
43 fn test_tr() {
44 let mut s = *b"hello\0";
45 tr(s.as_mut_ptr() as *mut _, b'l' as i8, b'p' as i8);
46 assert_eq!(s, *b"heppo\0");
47 }
48}