Skip to main content

sql_values/postgres/
bytea.rs

1//! PostgreSQL 18's `bytea`, read as `byteain` reads its hex and escape formats and printed as
2//! `byteaout` prints it under either setting of `bytea_output`.
3
4use alloc::vec::Vec;
5use core::fmt;
6
7/// Why `byteain` refuses a text, one variant per message it raises.
8///
9/// ```
10/// use sql_values::postgres::{ByteaError, PgBytea};
11///
12/// assert_eq!(PgBytea::parse(r"\x0"), Err(ByteaError::OddHexDigits));
13/// assert_eq!(PgBytea::parse(r"\x0g"), Err(ByteaError::InvalidHexDigit('g')));
14/// assert_eq!(PgBytea::parse(r"\9"), Err(ByteaError::InvalidInputSyntax));
15/// ```
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
17pub enum ByteaError {
18    /// A backslash of the escape format not followed by `\` or three octal digits up to `\377`.
19    #[error("invalid input syntax for type bytea")]
20    InvalidInputSyntax,
21    /// The first character of the hex format that is no digit and no whitespace between pairs.
22    #[error("invalid hexadecimal digit: \"{0}\"")]
23    InvalidHexDigit(char),
24    /// Hex digits that end on half a byte.
25    #[error("invalid hexadecimal data: odd number of digits")]
26    OddHexDigits,
27}
28
29/// A PostgreSQL `bytea`, ordered as `byteacmp` orders it and printed as `byteaout` prints it
30/// under the default `bytea_output` of `hex`.
31///
32/// ```
33/// use sql_values::postgres::PgBytea;
34///
35/// let bytea = |text| PgBytea::parse(text).unwrap();
36/// assert_eq!(bytea(r"\x de AD "), bytea(r"\336\255"));
37/// assert_eq!(bytea(r"a\\b").as_bytes(), b"a\\b");
38/// assert_eq!(bytea("hi").to_string(), r"\x6869");
39/// assert_eq!(PgBytea::from(b"hi".to_vec()), bytea(r"\x6869"));
40/// assert_eq!(bytea(r"\150\151").into_bytes(), b"hi");
41/// assert_eq!(bytea(r"\x00415c").escaped().to_string(), r"\000A\\");
42/// assert!(bytea(r"\x00") < bytea(r"\x0000"));
43/// assert!(bytea(r"\x0000") < bytea(r"\x01"));
44/// ```
45#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
46pub struct PgBytea(Vec<u8>);
47
48impl PgBytea {
49    /// Read `text` as `byteain` reads it, hex after a leading `\x`, else the escape format.
50    ///
51    /// # Errors
52    ///
53    /// The [`ByteaError`] whose message PostgreSQL raises for `text`.
54    pub fn parse(text: &str) -> Result<Self, ByteaError> {
55        match text.strip_prefix(r"\x") {
56            Some(digits) => read_hex(digits),
57            None => read_escape(text.as_bytes()),
58        }
59        .map(Self)
60    }
61
62    /// The bytes.
63    pub fn as_bytes(&self) -> &[u8] {
64        &self.0
65    }
66
67    /// The bytes, owned.
68    pub fn into_bytes(self) -> Vec<u8> {
69        self.0
70    }
71
72    /// The value as `byteaout` prints it under `bytea_output` `escape`.
73    pub fn escaped(&self) -> impl fmt::Display + '_ {
74        Escaped(&self.0)
75    }
76}
77
78impl From<Vec<u8>> for PgBytea {
79    fn from(bytes: Vec<u8>) -> Self {
80        Self(bytes)
81    }
82}
83
84impl fmt::Display for PgBytea {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        f.write_str(r"\x")?;
87        self.0.iter().try_for_each(|byte| write!(f, "{byte:02x}"))
88    }
89}
90
91/// [`PgBytea::escaped`]'s printing.
92struct Escaped<'a>(&'a [u8]);
93
94impl fmt::Display for Escaped<'_> {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        self.0.iter().try_for_each(|&byte| match byte {
97            b'\\' => f.write_str(r"\\"),
98            b' '..=b'~' => write!(f, "{}", char::from(byte)),
99            _ => write!(f, "\\{byte:03o}"),
100        })
101    }
102}
103
104/// `hex_decode_safe` over the digits after `\x`.
105fn read_hex(digits: &str) -> Result<Vec<u8>, ByteaError> {
106    let bytes = digits.as_bytes();
107    let mut decoded = Vec::with_capacity(bytes.len() / 2);
108    let mut at = 0;
109    while at < bytes.len() {
110        if matches!(bytes[at], b' ' | b'\t' | b'\n' | b'\r') {
111            at += 1;
112            continue;
113        }
114        let high = hex_value(digits, at)?;
115        if at + 1 == bytes.len() {
116            return Err(ByteaError::OddHexDigits);
117        }
118        let low = hex_value(digits, at + 1)?;
119        decoded.push((high << 4) | low);
120        at += 2;
121    }
122    Ok(decoded)
123}
124
125/// The value of the hex digit at byte `at` of `digits`, which every caller reaches over ASCII
126/// alone, so `at` starts a character.
127fn hex_value(digits: &str, at: usize) -> Result<u8, ByteaError> {
128    char::from(digits.as_bytes()[at])
129        .to_digit(16)
130        .and_then(|value| u8::try_from(value).ok())
131        .ok_or_else(|| ByteaError::InvalidHexDigit(digits[at..].chars().next().unwrap_or_default()))
132}
133
134/// `byteain`'s escape format.
135fn read_escape(text: &[u8]) -> Result<Vec<u8>, ByteaError> {
136    let mut decoded = Vec::with_capacity(text.len());
137    let mut rest = text;
138    loop {
139        rest = match rest {
140            [] => return Ok(decoded),
141            [
142                b'\\',
143                high @ b'0'..=b'3',
144                middle @ b'0'..=b'7',
145                low @ b'0'..=b'7',
146                tail @ ..,
147            ] => {
148                decoded.push(((high - b'0') << 6) | ((middle - b'0') << 3) | (low - b'0'));
149                tail
150            }
151            [b'\\', b'\\', tail @ ..] => {
152                decoded.push(b'\\');
153                tail
154            }
155            [b'\\', ..] => return Err(ByteaError::InvalidInputSyntax),
156            [byte, tail @ ..] => {
157                decoded.push(*byte);
158                tail
159            }
160        };
161    }
162}