use crate::label::Encoding;
#[must_use]
pub fn detect_bom(bytes: &[u8]) -> Option<(Encoding, usize)> {
if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
Some((Encoding::Utf8, 3))
} else if bytes.starts_with(&[0xFE, 0xFF]) {
Some((Encoding::Utf16Be, 2))
} else if bytes.starts_with(&[0xFF, 0xFE]) {
Some((Encoding::Utf16Le, 2))
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detects_utf8_bom() {
assert_eq!(detect_bom(&[0xEF, 0xBB, 0xBF]), Some((Encoding::Utf8, 3)));
assert_eq!(
detect_bom(&[0xEF, 0xBB, 0xBF, b'a', b'b']),
Some((Encoding::Utf8, 3))
);
}
#[test]
fn detects_utf16_be_bom() {
assert_eq!(detect_bom(&[0xFE, 0xFF]), Some((Encoding::Utf16Be, 2)));
}
#[test]
fn detects_utf16_le_bom() {
assert_eq!(detect_bom(&[0xFF, 0xFE]), Some((Encoding::Utf16Le, 2)));
}
#[test]
fn no_bom_returns_none() {
assert_eq!(detect_bom(b"<?xml version=\"1.0\"?>"), None);
assert_eq!(detect_bom(b""), None);
assert_eq!(detect_bom(&[0x00]), None);
}
#[test]
fn utf32_bom_is_not_recognized() {
assert_eq!(detect_bom(&[0x00, 0x00, 0xFE, 0xFF]), None);
}
}