//! Source files as text, whatever encoding the tool that wrote them chose. //! //! Visual Studio writes UTF-8 with a byte-order mark (BOM) or UTF-16, older //! .NET and PLC tools write Windows-1252. `std::fs::read_to_string` accepts //! only UTF-8 (and keeps a UTF-8 BOM as a leading `U+FEFF`), so every reader //! of source files decodes through [`read_source`] instead: //! //! 1. a BOM (UTF-8 `EF BB BF`, UTF-16 LE `FF FE`, UTF-16 BE `FE FF`) names the //! encoding; the BOM itself is dropped; //! 2. without one, the bytes are UTF-8 if they are valid UTF-8; //! 3. otherwise they are Windows-1252, unless they contain a NUL byte: no //! 1252 text does, but binaries and UTF-16 without a BOM do. use std::path::Path; use encoding_rs::{Encoding, UTF_8, WINDOWS_1252}; /// Why a file could not be read as text. #[derive(Debug, thiserror::Error)] pub enum SourceTextError { /// The file could not be read at all (missing, no permission, ...). #[error("cannot read the file: {0}")] Io(#[from] std::io::Error), /// The file's BOM names an encoding its bytes don't follow, e.g. UTF-16 /// with an odd byte count or an unpaired surrogate. #[error("the file is not valid {0} although its byte-order mark says so")] Malformed(&'static str), /// The file has no BOM, is not UTF-8 and contains a NUL byte: a binary /// file, or UTF-16 we can't tell the byte order of. #[error("the file is binary or of an unknown encoding")] Binary, } /// Read the file at `path` as text, decoded as the module docs describe. /// /// # Arguments /// /// * `path` - the file to read /// /// # Returns /// /// The file's text, without a byte-order mark. /// /// # Errors /// /// Returns [`SourceTextError::Io`] when the file can't be read, and the /// errors of [`decode`] when its bytes aren't text. pub fn read_source(path: &Path) -> Result { decode(std::fs::read(path)?) } /// Decode a source file's bytes, as the module docs describe. /// /// Takes the bytes by value so that the common case, UTF-8 without a BOM, /// becomes the `String` without copying: a Rust `String` is a UTF-8 byte /// buffer, so `String::from_utf8` only validates and reuses the `Vec`. /// /// # Arguments /// /// * `bytes` - the whole file /// /// # Returns /// /// The text, without a byte-order mark. /// /// # Errors /// /// Returns [`SourceTextError::Malformed`] when a BOM names an encoding the /// bytes don't follow, and [`SourceTextError::Binary`] for non-UTF-8 bytes /// that contain a NUL. /// /// # Examples /// /// ``` /// use compliance_core::encoding::decode; /// /// // "€" is 0x80 in Windows-1252. /// assert_eq!(decode(b"// 5 \x80".to_vec()).ok().as_deref(), Some("// 5 €")); /// ``` pub fn decode(mut bytes: Vec) -> Result { if let Some((encoding, bom_len)) = Encoding::for_bom(&bytes) { if encoding == UTF_8 { // Drop the BOM in place, then validate without another copy. bytes.drain(..bom_len); return String::from_utf8(bytes).map_err(|_| SourceTextError::Malformed("UTF-8")); } // UTF-16 LE or BE: `None` on an odd byte count or unpaired surrogate. return encoding .decode_without_bom_handling_and_without_replacement(&bytes[bom_len..]) .map(|text| text.into_owned()) .ok_or(SourceTextError::Malformed(encoding.name())); } match String::from_utf8(bytes) { Ok(text) => Ok(text), Err(not_utf8) => { // Hand the buffer back; `from_utf8` gave up ownership on failure. let bytes = not_utf8.into_bytes(); if bytes.contains(&0) { return Err(SourceTextError::Binary); } // Windows-1252 maps every byte, so this decoding can't fail. let (text, _had_errors) = WINDOWS_1252.decode_without_bom_handling(&bytes); Ok(text.into_owned()) } } } #[cfg(test)] mod tests { use super::*; /// `text` as UTF-16 with its BOM, in the byte order asked for. fn utf16(text: &str, little_endian: bool) -> Vec { let bom: [u8; 2] = if little_endian { [0xFF, 0xFE] } else { [0xFE, 0xFF] }; let units = text.encode_utf16().flat_map(|unit| { if little_endian { unit.to_le_bytes() } else { unit.to_be_bytes() } }); bom.into_iter().chain(units).collect() } #[test] fn utf8_without_a_bom_is_kept_as_it_is() { let text = decode("int größe = 1; // €".as_bytes().to_vec()); assert_eq!(text.ok().as_deref(), Some("int größe = 1; // €")); } #[test] fn a_utf8_bom_is_dropped() { let mut bytes = vec![0xEF, 0xBB, 0xBF]; bytes.extend_from_slice(b"class A {}"); assert_eq!(decode(bytes).ok().as_deref(), Some("class A {}")); } #[test] fn utf16_with_a_bom_is_decoded_in_both_byte_orders() { for little_endian in [true, false] { let text = decode(utf16("class Größe {}", little_endian)); assert_eq!(text.ok().as_deref(), Some("class Größe {}")); } } #[test] fn windows_1252_is_the_fallback() { // "Größe" and "€" as Windows-1252 writes them: 0xF6 0xDF and 0x80. let text = decode(b"// Gr\xF6\xDFe in \x80".to_vec()); assert_eq!(text.ok().as_deref(), Some("// Größe in €")); } #[test] fn malformed_utf16_and_binaries_are_not_text() { // An odd byte count after a UTF-16 LE BOM. assert!(matches!( decode(vec![0xFF, 0xFE, 0x41]), Err(SourceTextError::Malformed("UTF-16LE")) )); // An unpaired high surrogate (D800) in UTF-16 BE. assert!(matches!( decode(vec![0xFE, 0xFF, 0xD8, 0x00, 0x00, 0x41]), Err(SourceTextError::Malformed("UTF-16BE")) )); // Invalid UTF-8 after a UTF-8 BOM. assert!(matches!( decode(vec![0xEF, 0xBB, 0xBF, 0xFF]), Err(SourceTextError::Malformed("UTF-8")) )); // Not UTF-8 and a NUL: a binary. assert!(matches!( decode(vec![0x7F, b'E', b'L', b'F', 0x00, 0xFF]), Err(SourceTextError::Binary) )); } #[test] fn a_missing_file_is_an_io_error() { let missing = std::env::temp_dir().join("compliance-core-no-such-file.cs"); assert!(matches!(read_source(&missing), Err(SourceTextError::Io(_)))); } }