//! Small byte and text helpers shared by the format readers. /// The first position of `needle` in `hay`. pub(crate) fn find(hay: &[u8], needle: &[u8]) -> Option { if needle.is_empty() || needle.len() > hay.len() { return None; } hay.windows(needle.len()).position(|w| w == needle) } pub(crate) fn be16(b: &[u8], at: usize) -> Option { let s = b.get(at..at.checked_add(2)?)?; Some(u16::from_be_bytes([s[0], s[1]])) } pub(crate) fn be32(b: &[u8], at: usize) -> Option { let s = b.get(at..at.checked_add(4)?)?; Some(u32::from_be_bytes([s[0], s[1], s[2], s[3]])) } pub(crate) fn le32(b: &[u8], at: usize) -> Option { let s = b.get(at..at.checked_add(4)?)?; Some(u32::from_le_bytes([s[0], s[1], s[2], s[3]])) } /// Cuts a string to `max` characters, adding an ellipsis, and replaces control characters with spaces. pub(crate) fn clip(s: &str, max: usize) -> String { let mut out = String::with_capacity(s.len().min(max * 4)); for (n, c) in s.chars().enumerate() { if n == max { out.push('…'); break; } out.push(if c.is_control() { ' ' } else { c }); } out.trim().to_string() } /// Bytes as text: UTF-8 where valid, otherwise Latin-1; trailing NULs dropped. pub(crate) fn lossy(b: &[u8]) -> String { let b = trim_nul(b); match std::str::from_utf8(b) { Ok(s) => s.to_string(), Err(_) => latin1(b), } } pub(crate) fn latin1(b: &[u8]) -> String { trim_nul(b).iter().map(|&c| c as char).collect() } fn trim_nul(mut b: &[u8]) -> &[u8] { while let [rest @ .., 0] = b { b = rest; } b } /// A PDF text string: UTF-16BE (or LE) with a byte order mark, UTF-8 with a BOM, or PDFDocEncoding. pub(crate) fn pdf_text(b: &[u8]) -> String { if let Some(rest) = b.strip_prefix(&[0xFE, 0xFF]) { let units = rest.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)); return char::decode_utf16(units).map(|r| r.unwrap_or('\u{FFFD}')).collect(); } if let Some(rest) = b.strip_prefix(&[0xFF, 0xFE]) { let units = rest.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)); return char::decode_utf16(units).map(|r| r.unwrap_or('\u{FFFD}')).collect(); } if let Some(rest) = b.strip_prefix(&[0xEF, 0xBB, 0xBF]) { return String::from_utf8_lossy(rest).into_owned(); } b.iter().map(|&c| pdf_doc_char(c)).collect() } fn pdf_doc_char(c: u8) -> char { const LOW: [char; 8] = ['\u{02D8}', '\u{02C7}', '\u{02C6}', '\u{02D9}', '\u{02DD}', '\u{02DB}', '\u{02DA}', '\u{02DC}']; const HIGH: [char; 33] = [ '\u{2022}', '\u{2020}', '\u{2021}', '\u{2026}', '\u{2014}', '\u{2013}', '\u{0192}', '\u{2044}', '\u{2039}', '\u{203A}', '\u{2212}', '\u{2030}', '\u{201E}', '\u{201C}', '\u{201D}', '\u{2018}', '\u{2019}', '\u{201A}', '\u{2122}', '\u{FB01}', '\u{FB02}', '\u{0141}', '\u{0152}', '\u{0160}', '\u{0178}', '\u{017D}', '\u{0131}', '\u{0142}', '\u{0153}', '\u{0161}', '\u{017E}', '\u{FFFD}', '\u{20AC}', ]; match c { 0x18..=0x1F => LOW[usize::from(c - 0x18)], 0x7F | 0xAD => '\u{FFFD}', 0x80..=0xA0 => HIGH[usize::from(c - 0x80)], _ => c as char, } } /// Makes "D:20240501102030+02'00'" readable as "2024-05-01 10:20:30 +02:00"; anything else is returned as is. pub(crate) fn pdf_date(s: &str) -> String { let body = s.strip_prefix("D:").unwrap_or(s); let digits: String = body.chars().take_while(|c| c.is_ascii_digit()).collect(); if digits.len() < 4 || !s.starts_with("D:") { return s.to_string(); } let part = |from: usize, to: usize, default: &str| digits.get(from..to).unwrap_or(default).to_string(); let mut out = format!( "{}-{}-{} {}:{}:{}", part(0, 4, "0000"), part(4, 6, "01"), part(6, 8, "01"), part(8, 10, "00"), part(10, 12, "00"), part(12, 14, "00") ); let rest: String = body.chars().skip(digits.chars().count()).collect(); let rest = rest.trim(); if rest.starts_with('Z') { out.push_str(" UTC"); } else if rest.starts_with('+') || rest.starts_with('-') { let tz: String = rest.chars().filter(|c| c.is_ascii_digit()).take(4).collect(); if tz.len() == 4 { out.push_str(&format!(" {}{}:{}", &rest[..1], &tz[..2], &tz[2..])); } } out } /// Decodes the five XML entities and numeric character references. pub(crate) fn xml_unescape(s: &str) -> String { if !s.contains('&') { return s.to_string(); } let mut out = String::with_capacity(s.len()); let mut rest = s; while let Some(i) = rest.find('&') { out.push_str(&rest[..i]); rest = &rest[i..]; let end = rest.find(';').filter(|&e| e <= 12); let decoded = end.and_then(|e| { let ent = &rest[1..e]; let c = match ent { "amp" => Some('&'), "lt" => Some('<'), "gt" => Some('>'), "quot" => Some('"'), "apos" => Some('\''), _ if ent.starts_with("#x") || ent.starts_with("#X") => { u32::from_str_radix(&ent[2..], 16).ok().and_then(char::from_u32) } _ if ent.starts_with('#') => ent[1..].parse::().ok().and_then(char::from_u32), _ => None, }; c.map(|c| (c, e)) }); match decoded { Some((c, e)) => { out.push(c); rest = &rest[e + 1..]; } None => { out.push('&'); rest = &rest[1..]; } } } out.push_str(rest); out } #[cfg(test)] mod tests { use super::*; #[test] fn pdf_strings() { assert_eq!(pdf_text(&[0xFE, 0xFF, 0x00, 0x4A, 0x00, 0xE1]), "Já"); assert_eq!(pdf_text(b"Caf\xE9 \x84"), "Café —"); assert_eq!(pdf_date("D:20240501102030+02'00'"), "2024-05-01 10:20:30 +02:00"); assert_eq!(pdf_date("D:2024"), "2024-01-01 00:00:00"); assert_eq!(pdf_date("yesterday"), "yesterday"); } #[test] fn unescape() { assert_eq!(xml_unescape("a & b AB &bogus; &"), "a & b AB &bogus; &"); } #[test] fn clipping() { assert_eq!(clip("abcdef", 3), "abc…"); assert_eq!(clip("a\nb", 10), "a b"); } }