Skip to content
Myr

jsont.rs

This file

Path

crates/printer/src/jsont.rs

294 lines · 9.7 KiB · Rust

Last changed by

lint: fix a few Clippy errorsLucas Trzesniewskibefore adoptiona7b7d81

History of this file

Take it

1// This module defines the types we use for JSON serialization. We specifically2// omit deserialization, partially because there isn't a clear use case for3// them at this time, but also because deserialization will complicate things.4// Namely, the types below are designed in a way that permits JSON5// serialization with little or no allocation. Allocation is often quite6// convenient for deserialization however, so these types would become a bit7// more complex.89use std::{borrow::Cow, path::Path};1011pub(crate) enum Message<'a> {12    Begin(Begin<'a>),13    End(End<'a>),14    Match(Match<'a>),15    Context(Context<'a>),16}1718impl<'a> serde::Serialize for Message<'a> {19    fn serialize<S: serde::Serializer>(20        &self,21        s: S,22    ) -> Result<S::Ok, S::Error> {23        use serde::ser::SerializeStruct;2425        let mut state = s.serialize_struct("Message", 2)?;26        match *self {27            Message::Begin(ref msg) => {28                state.serialize_field("type", &"begin")?;29                state.serialize_field("data", msg)?;30            }31            Message::End(ref msg) => {32                state.serialize_field("type", &"end")?;33                state.serialize_field("data", msg)?;34            }35            Message::Match(ref msg) => {36                state.serialize_field("type", &"match")?;37                state.serialize_field("data", msg)?;38            }39            Message::Context(ref msg) => {40                state.serialize_field("type", &"context")?;41                state.serialize_field("data", msg)?;42            }43        }44        state.end()45    }46}4748pub(crate) struct Begin<'a> {49    pub(crate) path: Option<&'a Path>,50}5152impl<'a> serde::Serialize for Begin<'a> {53    fn serialize<S: serde::Serializer>(54        &self,55        s: S,56    ) -> Result<S::Ok, S::Error> {57        use serde::ser::SerializeStruct;5859        let mut state = s.serialize_struct("Begin", 1)?;60        state.serialize_field("path", &self.path.map(Data::from_path))?;61        state.end()62    }63}6465pub(crate) struct End<'a> {66    pub(crate) path: Option<&'a Path>,67    pub(crate) binary_offset: Option<u64>,68    pub(crate) stats: crate::stats::Stats,69}7071impl<'a> serde::Serialize for End<'a> {72    fn serialize<S: serde::Serializer>(73        &self,74        s: S,75    ) -> Result<S::Ok, S::Error> {76        use serde::ser::SerializeStruct;7778        let mut state = s.serialize_struct("End", 3)?;79        state.serialize_field("path", &self.path.map(Data::from_path))?;80        state.serialize_field("binary_offset", &self.binary_offset)?;81        state.serialize_field("stats", &self.stats)?;82        state.end()83    }84}8586pub(crate) struct Match<'a> {87    pub(crate) path: Option<&'a Path>,88    pub(crate) lines: &'a [u8],89    pub(crate) line_number: Option<u64>,90    pub(crate) absolute_offset: u64,91    pub(crate) submatches: &'a [SubMatch<'a>],92}9394impl<'a> serde::Serialize for Match<'a> {95    fn serialize<S: serde::Serializer>(96        &self,97        s: S,98    ) -> Result<S::Ok, S::Error> {99        use serde::ser::SerializeStruct;100101        let mut state = s.serialize_struct("Match", 5)?;102        state.serialize_field("path", &self.path.map(Data::from_path))?;103        state.serialize_field("lines", &Data::from_bytes(self.lines))?;104        state.serialize_field("line_number", &self.line_number)?;105        state.serialize_field("absolute_offset", &self.absolute_offset)?;106        state.serialize_field("submatches", &self.submatches)?;107        state.end()108    }109}110111pub(crate) struct Context<'a> {112    pub(crate) path: Option<&'a Path>,113    pub(crate) lines: &'a [u8],114    pub(crate) line_number: Option<u64>,115    pub(crate) absolute_offset: u64,116    pub(crate) submatches: &'a [SubMatch<'a>],117}118119impl<'a> serde::Serialize for Context<'a> {120    fn serialize<S: serde::Serializer>(121        &self,122        s: S,123    ) -> Result<S::Ok, S::Error> {124        use serde::ser::SerializeStruct;125126        let mut state = s.serialize_struct("Context", 5)?;127        state.serialize_field("path", &self.path.map(Data::from_path))?;128        state.serialize_field("lines", &Data::from_bytes(self.lines))?;129        state.serialize_field("line_number", &self.line_number)?;130        state.serialize_field("absolute_offset", &self.absolute_offset)?;131        state.serialize_field("submatches", &self.submatches)?;132        state.end()133    }134}135136pub(crate) struct SubMatch<'a> {137    pub(crate) m: &'a [u8],138    pub(crate) replacement: Option<&'a [u8]>,139    pub(crate) start: usize,140    pub(crate) end: usize,141}142143impl<'a> serde::Serialize for SubMatch<'a> {144    fn serialize<S: serde::Serializer>(145        &self,146        s: S,147    ) -> Result<S::Ok, S::Error> {148        use serde::ser::SerializeStruct;149150        let mut state = s.serialize_struct("SubMatch", 3)?;151        state.serialize_field("match", &Data::from_bytes(self.m))?;152        if let Some(r) = self.replacement {153            state.serialize_field("replacement", &Data::from_bytes(r))?;154        }155        state.serialize_field("start", &self.start)?;156        state.serialize_field("end", &self.end)?;157        state.end()158    }159}160161/// Data represents things that look like strings, but may actually not be162/// valid UTF-8. To handle this, `Data` is serialized as an object with one163/// of two keys: `text` (for valid UTF-8) or `bytes` (for invalid UTF-8).164///165/// The happy path is valid UTF-8, which streams right through as-is, since166/// it is natively supported by JSON. When invalid UTF-8 is found, then it is167/// represented as arbitrary bytes and base64 encoded.168#[derive(Clone, Debug, Hash, PartialEq, Eq)]169enum Data<'a> {170    Text { text: Cow<'a, str> },171    Bytes { bytes: &'a [u8] },172}173174impl<'a> Data<'a> {175    fn from_bytes(bytes: &[u8]) -> Data<'_> {176        match std::str::from_utf8(bytes) {177            Ok(text) => Data::Text { text: Cow::Borrowed(text) },178            Err(_) => Data::Bytes { bytes },179        }180    }181182    #[cfg(unix)]183    fn from_path(path: &Path) -> Data<'_> {184        use std::os::unix::ffi::OsStrExt;185186        match path.to_str() {187            Some(text) => Data::Text { text: Cow::Borrowed(text) },188            None => Data::Bytes { bytes: path.as_os_str().as_bytes() },189        }190    }191192    #[cfg(not(unix))]193    fn from_path(path: &Path) -> Data<'_> {194        // Using lossy conversion means some paths won't round trip precisely,195        // but it's not clear what we should actually do. Serde rejects196        // non-UTF-8 paths, and OsStr's are serialized as a sequence of UTF-16197        // code units on Windows. Neither seem appropriate for this use case,198        // so we do the easy thing for now.199        Data::Text { text: path.to_string_lossy() }200    }201}202203impl<'a> serde::Serialize for Data<'a> {204    fn serialize<S: serde::Serializer>(205        &self,206        s: S,207    ) -> Result<S::Ok, S::Error> {208        use serde::ser::SerializeStruct;209210        let mut state = s.serialize_struct("Data", 1)?;211        match *self {212            Data::Text { ref text } => state.serialize_field("text", text)?,213            Data::Bytes { bytes } => {214                // use base64::engine::{general_purpose::STANDARD, Engine};215                // let encoded = STANDARD.encode(bytes);216                state.serialize_field("bytes", &base64_standard(bytes))?;217            }218        }219        state.end()220    }221}222223/// Implements "standard" base64 encoding as described in RFC 3548[1].224///225/// We roll our own here instead of bringing in something heavier weight like226/// the `base64` crate. In particular, we really don't care about perf much227/// here, since this is only used for data or file paths that are not valid228/// UTF-8.229///230/// [1]: https://tools.ietf.org/html/rfc3548#section-3231fn base64_standard(bytes: &[u8]) -> String {232    const ALPHABET: &[u8] =233        b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";234235    let mut out = String::new();236    let mut it = bytes.chunks_exact(3);237    while let Some(chunk) = it.next() {238        let group24 = (usize::from(chunk[0]) << 16)239            | (usize::from(chunk[1]) << 8)240            | usize::from(chunk[2]);241        let index1 = (group24 >> 18) & 0b111_111;242        let index2 = (group24 >> 12) & 0b111_111;243        let index3 = (group24 >> 6) & 0b111_111;244        let index4 = (group24 >> 0) & 0b111_111;245        out.push(char::from(ALPHABET[index1]));246        out.push(char::from(ALPHABET[index2]));247        out.push(char::from(ALPHABET[index3]));248        out.push(char::from(ALPHABET[index4]));249    }250    match it.remainder() {251        &[] => {}252        &[byte0] => {253            let group8 = usize::from(byte0);254            let index1 = (group8 >> 2) & 0b111_111;255            let index2 = (group8 << 4) & 0b111_111;256            out.push(char::from(ALPHABET[index1]));257            out.push(char::from(ALPHABET[index2]));258            out.push('=');259            out.push('=');260        }261        &[byte0, byte1] => {262            let group16 = (usize::from(byte0) << 8) | usize::from(byte1);263            let index1 = (group16 >> 10) & 0b111_111;264            let index2 = (group16 >> 4) & 0b111_111;265            let index3 = (group16 << 2) & 0b111_111;266            out.push(char::from(ALPHABET[index1]));267            out.push(char::from(ALPHABET[index2]));268            out.push(char::from(ALPHABET[index3]));269            out.push('=');270        }271        _ => unreachable!("remainder must have length < 3"),272    }273    out274}275276#[cfg(test)]277mod tests {278    use super::*;279280    // Tests taken from RFC 4648[1].281    //282    // [1]: https://datatracker.ietf.org/doc/html/rfc4648#section-10283    #[test]284    fn base64_basic() {285        let b64 = |s: &str| base64_standard(s.as_bytes());286        assert_eq!(b64(""), "");287        assert_eq!(b64("f"), "Zg==");288        assert_eq!(b64("fo"), "Zm8=");289        assert_eq!(b64("foo"), "Zm9v");290        assert_eq!(b64("foob"), "Zm9vYg==");291        assert_eq!(b64("fooba"), "Zm9vYmE=");292        assert_eq!(b64("foobar"), "Zm9vYmFy");293    }294}