use alloc::vec::Vec;
use core::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
pub enum ByteaError {
#[error("invalid input syntax for type bytea")]
InvalidInputSyntax,
#[error("invalid hexadecimal digit: \"{0}\"")]
InvalidHexDigit(char),
#[error("invalid hexadecimal data: odd number of digits")]
OddHexDigits,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PgBytea(Vec<u8>);
impl PgBytea {
pub fn parse(text: &str) -> Result<Self, ByteaError> {
match text.strip_prefix(r"\x") {
Some(digits) => read_hex(digits),
None => read_escape(text.as_bytes()),
}
.map(Self)
}
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
pub fn into_bytes(self) -> Vec<u8> {
self.0
}
pub fn escaped(&self) -> impl fmt::Display + '_ {
Escaped(&self.0)
}
}
impl From<Vec<u8>> for PgBytea {
fn from(bytes: Vec<u8>) -> Self {
Self(bytes)
}
}
impl fmt::Display for PgBytea {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(r"\x")?;
self.0.iter().try_for_each(|byte| write!(f, "{byte:02x}"))
}
}
struct Escaped<'a>(&'a [u8]);
impl fmt::Display for Escaped<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.iter().try_for_each(|&byte| match byte {
b'\\' => f.write_str(r"\\"),
b' '..=b'~' => write!(f, "{}", char::from(byte)),
_ => write!(f, "\\{byte:03o}"),
})
}
}
fn read_hex(digits: &str) -> Result<Vec<u8>, ByteaError> {
let bytes = digits.as_bytes();
let mut decoded = Vec::with_capacity(bytes.len() / 2);
let mut at = 0;
while at < bytes.len() {
if matches!(bytes[at], b' ' | b'\t' | b'\n' | b'\r') {
at += 1;
continue;
}
let high = hex_value(digits, at)?;
if at + 1 == bytes.len() {
return Err(ByteaError::OddHexDigits);
}
let low = hex_value(digits, at + 1)?;
decoded.push((high << 4) | low);
at += 2;
}
Ok(decoded)
}
fn hex_value(digits: &str, at: usize) -> Result<u8, ByteaError> {
char::from(digits.as_bytes()[at])
.to_digit(16)
.and_then(|value| u8::try_from(value).ok())
.ok_or_else(|| ByteaError::InvalidHexDigit(digits[at..].chars().next().unwrap_or_default()))
}
fn read_escape(text: &[u8]) -> Result<Vec<u8>, ByteaError> {
let mut decoded = Vec::with_capacity(text.len());
let mut rest = text;
loop {
rest = match rest {
[] => return Ok(decoded),
[
b'\\',
high @ b'0'..=b'3',
middle @ b'0'..=b'7',
low @ b'0'..=b'7',
tail @ ..,
] => {
decoded.push(((high - b'0') << 6) | ((middle - b'0') << 3) | (low - b'0'));
tail
}
[b'\\', b'\\', tail @ ..] => {
decoded.push(b'\\');
tail
}
[b'\\', ..] => return Err(ByteaError::InvalidInputSyntax),
[byte, tail @ ..] => {
decoded.push(*byte);
tail
}
};
}
}