flow-abi 0.1.0-rc.5

The host boundary's value encoding: the binary encoding and the JSON form, the canonical form and its hash, JSON Schemas, Tool signatures, and the answers a Tool call passes.
Documentation
//! std's `media.MediaType` (`stdlib.md`, *`media`*): a media type by RFC 9110
//! §8.3.1 in its normal form, which `media.parse` makes and decoding holds a
//! `MediaType` to (`abi.md`, *Decoding*).

use std::fmt;

/// A media type in its normal form: the type, subtype and parameter names in
/// lowercase, and each parameter's value as written once unquoted. Its text
/// is [`fmt::Display`].
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct MediaType {
    top: String,
    subtype: String,
    parameters: Vec<(String, String)>,
}

impl MediaType {
    /// The media type `text` spells, or `None` when it spells none:
    /// `type "/" subtype *( OWS ";" OWS [ parameter ] )`, in ASCII.
    ///
    /// ```
    /// let media = flow_abi::MediaType::parse("Text/HTML ; Charset=\"utf-8\"").unwrap();
    /// assert_eq!(media.to_string(), "text/html;charset=utf-8");
    /// ```
    pub fn parse(text: &str) -> Option<MediaType> {
        let mut reader = Reader {
            bytes: text.as_bytes(),
            at: 0,
        };
        let top = reader.token()?.to_ascii_lowercase();
        reader.expect(b'/')?;
        let subtype = reader.token()?.to_ascii_lowercase();
        let mut parameters = Vec::new();
        loop {
            let before = reader.at;
            reader.whitespace();
            if reader.done() {
                // Whitespace is allowed only before a `;`.
                if reader.at != before {
                    return None;
                }
                break;
            }
            reader.expect(b';')?;
            reader.whitespace();
            // A parameter may be empty, and is then dropped.
            if reader.peek().is_some_and(is_tchar) {
                let name = reader.token()?.to_ascii_lowercase();
                reader.expect(b'=')?;
                let value = if reader.peek() == Some(b'"') {
                    reader.quoted()?
                } else {
                    reader.token()?
                };
                parameters.push((name, value));
            }
        }
        Some(MediaType {
            top,
            subtype,
            parameters,
        })
    }

    /// The value of the first parameter named `name` in lowercase, unquoted.
    pub fn parameter(&self, name: &str) -> Option<&str> {
        let name = name.to_ascii_lowercase();
        self.parameters
            .iter()
            .find(|(written, _)| *written == name)
            .map(|(_, value)| value.as_str())
    }
}

impl fmt::Display for MediaType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}/{}", self.top, self.subtype)?;
        for (name, value) in &self.parameters {
            write!(f, ";{name}=")?;
            if !value.is_empty() && value.bytes().all(is_tchar) {
                f.write_str(value)?;
            } else {
                f.write_str("\"")?;
                for ch in value.chars() {
                    if matches!(ch, '"' | '\\') {
                        f.write_str("\\")?;
                    }
                    write!(f, "{ch}")?;
                }
                f.write_str("\"")?;
            }
        }
        Ok(())
    }
}

/// The normal text of the media type `text` spells, or `None` when it
/// spells none.
pub fn normal_media_type(text: &str) -> Option<String> {
    MediaType::parse(text).map(|media| media.to_string())
}

/// RFC 9110 §5.6.2's `tchar`.
fn is_tchar(byte: u8) -> bool {
    byte.is_ascii_alphanumeric()
        || matches!(
            byte,
            b'!' | b'#'
                | b'$'
                | b'%'
                | b'&'
                | b'\''
                | b'*'
                | b'+'
                | b'-'
                | b'.'
                | b'^'
                | b'_'
                | b'`'
                | b'|'
                | b'~'
        )
}

struct Reader<'a> {
    bytes: &'a [u8],
    at: usize,
}

impl Reader<'_> {
    fn peek(&self) -> Option<u8> {
        self.bytes.get(self.at).copied()
    }

    fn done(&self) -> bool {
        self.at == self.bytes.len()
    }

    fn expect(&mut self, byte: u8) -> Option<()> {
        (self.peek() == Some(byte)).then(|| self.at += 1)
    }

    fn whitespace(&mut self) {
        while matches!(self.peek(), Some(b' ' | b'\t')) {
            self.at += 1;
        }
    }

    /// `1*tchar`.
    fn token(&mut self) -> Option<String> {
        let start = self.at;
        while self.peek().is_some_and(is_tchar) {
            self.at += 1;
        }
        (self.at > start).then(|| {
            String::from_utf8(self.bytes[start..self.at].to_vec()).expect("tchars are ASCII")
        })
    }

    /// `DQUOTE *( qdtext / quoted-pair ) DQUOTE`, unquoted, refusing what is
    /// not ASCII.
    fn quoted(&mut self) -> Option<String> {
        self.expect(b'"')?;
        let mut value = String::new();
        loop {
            let byte = self.peek()?;
            self.at += 1;
            match byte {
                b'"' => return Some(value),
                b'\\' => {
                    let escaped = self.peek().filter(|byte| visible_or_blank(*byte))?;
                    self.at += 1;
                    value.push(char::from(escaped));
                }
                byte if visible_or_blank(byte) => value.push(char::from(byte)),
                _ => return None,
            }
        }
    }
}

/// HTAB, SP or a visible ASCII character.
fn visible_or_blank(byte: u8) -> bool {
    matches!(byte, b'\t' | b' ' | 0x21..=0x7E)
}