//! Text helpers: decoding, hashing, the text fingerprint, ISBNs. use sha2::{Digest, Sha256}; use unicode_normalization::UnicodeNormalization; pub fn sha256_hex(bytes: &[u8]) -> String { let d = Sha256::digest(bytes); let mut s = String::with_capacity(64); for b in d { s.push_str(&format!("{b:02x}")); } s } /// SHA-256 of the text, NFKC-normalised, lowercased, letters and digits only (docs/FORMATS.md §6). pub fn fingerprint(text: &str) -> String { let mut h = Sha256::new(); let mut buf = [0u8; 4]; for c in text.nfkc() { if c.is_alphanumeric() { for l in c.to_lowercase() { h.update(l.encode_utf8(&mut buf).as_bytes()); } } } let d = h.finalize(); d.iter().map(|b| format!("{b:02x}")).collect() } /// The first position of `needle` in `hay`. pub fn find(hay: &[u8], needle: &[u8]) -> Option { if needle.is_empty() || hay.len() < needle.len() { return None; } hay.windows(needle.len()).position(|w| w == needle) } /// Whitespace runs to one space, trimmed. pub fn collapse(s: &str) -> String { let mut out = String::with_capacity(s.len()); let mut space = false; for c in s.chars() { if c.is_whitespace() { space = !out.is_empty(); } else { if space { out.push(' '); space = false; } out.push(c); } } out } pub fn utf16_len(s: &str) -> usize { s.chars().map(char::len_utf16).sum() } /// The byte index in `s` of UTF-16 offset `u`, or `None` past the end or inside a surrogate pair. pub fn byte_at_utf16(s: &str, u: usize) -> Option { let mut n = 0; for (i, c) in s.char_indices() { if n == u { return Some(i); } n += c.len_utf16(); if n > u { return None; } } (n == u).then_some(s.len()) } /// Decodes a text file: BOM, then strict UTF-8, then detection with the Czech hint (Windows-1250 and friends). /// Returns the text and the encoding's name. pub fn decode_text(bytes: &[u8]) -> (String, &'static str) { if let Some((enc, bom)) = encoding_rs::Encoding::for_bom(bytes) { let (s, _) = enc.decode_without_bom_handling(&bytes[bom..]); return (s.into_owned(), enc.name()); } if let Ok(s) = std::str::from_utf8(bytes) { return (s.to_owned(), "UTF-8"); } let mut det = chardetng::EncodingDetector::new(chardetng::Iso2022JpDetection::Deny); det.feed(bytes, true); let enc = det.guess(Some(b"cz"), chardetng::Utf8Detection::Allow); let (s, _) = enc.decode_without_bom_handling(bytes); (s.into_owned(), enc.name()) } /// Decodes an XML document: BOM, then the declaration's `encoding`, else UTF-8 (lossy). pub fn decode_xml(bytes: &[u8]) -> String { if let Some((enc, bom)) = encoding_rs::Encoding::for_bom(bytes) { return enc.decode_without_bom_handling(&bytes[bom..]).0.into_owned(); } let head = &bytes[..bytes.len().min(512)]; if head.starts_with(b"") { let decl = String::from_utf8_lossy(&head[..end]).to_lowercase(); if let Some(p) = decl.find("encoding") { let rest = &decl[p + 8..]; let rest = rest.trim_start().strip_prefix('=').unwrap_or(rest).trim_start(); let q = rest.chars().next().unwrap_or('"'); let label: String = rest.chars().skip(1).take_while(|&c| c != q).collect(); if let Some(enc) = encoding_rs::Encoding::for_label(label.trim().as_bytes()) && enc != encoding_rs::UTF_8 { return enc.decode_without_bom_handling(bytes).0.into_owned(); } } } String::from_utf8_lossy(bytes).into_owned() } /// An ISBN-10 or ISBN-13 (with or without hyphens, `urn:isbn:` or `isbn:`), check digit verified, as ISBN-13. pub fn isbn13(s: &str) -> Option { let s = s.trim(); let lower = s.to_lowercase(); let s = lower.strip_prefix("urn:isbn:").or_else(|| lower.strip_prefix("isbn:")).unwrap_or(&lower).trim(); let chars: Vec = s.chars().filter(|c| !matches!(c, '-' | ' ')).collect(); if chars.len() == 13 && chars.iter().all(char::is_ascii_digit) { let d: Vec = chars.iter().map(|c| c.to_digit(10).unwrap_or(0)).collect(); let sum: u32 = d[..12].iter().enumerate().map(|(i, v)| if i % 2 == 0 { *v } else { v * 3 }).sum(); let check = (10 - sum % 10) % 10; if check == d[12] && (chars.starts_with(&['9', '7', '8']) || chars.starts_with(&['9', '7', '9'])) { return Some(chars.iter().collect()); } return None; } if chars.len() == 10 && chars[..9].iter().all(char::is_ascii_digit) && (chars[9].is_ascii_digit() || chars[9] == 'x') { let sum: u32 = chars .iter() .enumerate() .map(|(i, c)| (10 - i as u32) * if *c == 'x' { 10 } else { c.to_digit(10).unwrap_or(0) }) .sum(); if !sum.is_multiple_of(11) { return None; } let body: String = std::iter::once("978".to_owned()).chain(chars[..9].iter().map(|c| c.to_string())).collect(); let d: Vec = body.chars().map(|c| c.to_digit(10).unwrap_or(0)).collect(); let sum: u32 = d.iter().enumerate().map(|(i, v)| if i % 2 == 0 { *v } else { v * 3 }).sum(); return Some(format!("{body}{}", (10 - sum % 10) % 10)); } None } #[cfg(test)] mod tests { use super::*; #[test] fn isbns() { assert_eq!(isbn13("978-0-441-17271-9").as_deref(), Some("9780441172719")); assert_eq!(isbn13("0441172717").as_deref(), Some("9780441172719")); assert_eq!(isbn13("urn:isbn:080442957X").as_deref(), Some("9780804429573")); assert_eq!(isbn13("9780441172718"), None); assert_eq!(isbn13("urn:uuid:1234"), None); } #[test] fn utf16() { let s = "a😀b"; assert_eq!(utf16_len(s), 4); assert_eq!(byte_at_utf16(s, 3), Some(5)); assert_eq!(byte_at_utf16(s, 2), None); assert_eq!(byte_at_utf16(s, 4), Some(6)); } #[test] fn windows_1250() { let (enc_bytes, _, _) = encoding_rs::WINDOWS_1250.encode("Příliš žluťoučký kůň úpěl ďábelské ódy. Šťastný Řehoř."); let (s, name) = decode_text(&enc_bytes); assert!(s.starts_with("Příliš žluťoučký"), "{s} ({name})"); } }