1pub fn decode_latin1(bytes: &[u8]) -> String {
13 bytes.iter().map(|&b| b as char).collect()
14}
15
16pub fn decode_utf8_or_latin1(bytes: &[u8]) -> String {
21 match std::str::from_utf8(bytes) {
22 Ok(s) => s.to_string(),
23 Err(_) => decode_latin1(bytes),
24 }
25}
26
27#[cfg(test)]
28mod tests {
29 use super::*;
30
31 #[test]
32 fn test_decode_latin1_ascii() {
33 assert_eq!(decode_latin1(b"hello"), "hello");
34 }
35
36 #[test]
37 fn test_decode_latin1_high_bytes() {
38 assert_eq!(decode_latin1(&[0xE9, 0xFC, 0xF1]), "éüñ");
40 }
41
42 #[test]
43 fn test_decode_latin1_full_range() {
44 assert_eq!(decode_latin1(&[0xA9, 0xAE, 0xF6]), "©®ö");
46 }
47
48 #[test]
49 fn test_decode_utf8_or_latin1_valid_utf8() {
50 assert_eq!(decode_utf8_or_latin1("café".as_bytes()), "café");
51 }
52
53 #[test]
54 fn test_decode_utf8_or_latin1_latin1_fallback() {
55 assert_eq!(decode_utf8_or_latin1(&[0x63, 0x61, 0x66, 0xE9]), "café");
57 }
58
59 #[test]
60 fn test_decode_utf8_or_latin1_pure_ascii() {
61 assert_eq!(decode_utf8_or_latin1(b"hello"), "hello");
62 }
63
64 #[test]
65 fn test_decode_utf8_or_latin1_empty() {
66 assert_eq!(decode_utf8_or_latin1(b""), "");
67 assert_eq!(decode_latin1(b""), "");
68 }
69}