strip_slice_prefix/
lib.rs

1#![no_std]
2
3/// Strips a prefix from a slice
4///
5/// Returns the remaining sequence if `data` starts with `prefix`.
6///
7/// If `data` does not start with this prefix, `None` is returned.
8/// 
9/// ```
10/// use strip_slice_prefix::strip_prefix;
11/// 
12/// let auth_header = b"Basic VGhlIGFuc3dlciBpcyA0Mi4K";
13/// let credentials = strip_prefix(auth_header, b"Basic ").unwrap();
14/// assert_eq!(credentials, b"VGhlIGFuc3dlciBpcyA0Mi4K");
15/// ```
16pub fn strip_prefix<'a, T>(data: &'a [T], prefix: &[T]) -> Option<&'a [T]>
17where T: Eq {
18    let mut remaining = data;
19    for prefix_char in prefix {
20        if prefix_char == remaining.first()? {
21            remaining = &remaining[1..];
22        } else {
23            return None;
24        }
25    }
26    Some(remaining)
27}
28
29
30#[cfg(test)]
31mod tests {
32    use super::*;
33
34    #[test]
35    fn test_empty_suffix() {
36        let result = strip_prefix(b"Hello", b"Hello").unwrap();
37        assert_eq!(result, b"");
38    }
39
40    #[test]
41    fn test_nonempty_suffix() {
42        let result = strip_prefix(b"Hello world", b"Hello").unwrap();
43        assert_eq!(result, b" world");
44    }
45
46    #[test]
47    fn test_too_long_prefix() {
48        let result = strip_prefix(b"Hell", b"Hello");
49        assert!(result.is_none());
50    }
51
52    #[test]
53    fn test_wrong_prefix() {
54        let result = strip_prefix(b"Hello", b"world");
55        assert!(result.is_none());
56    }
57
58    #[test]
59    fn test_empty_prefix() {
60        let result = strip_prefix(b"Hello", b"").unwrap();
61        assert_eq!(result, b"Hello");
62    }
63}