sql_values/postgres/
bytea.rs1use alloc::vec::Vec;
5use core::fmt;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
17pub enum ByteaError {
18 #[error("invalid input syntax for type bytea")]
20 InvalidInputSyntax,
21 #[error("invalid hexadecimal digit: \"{0}\"")]
23 InvalidHexDigit(char),
24 #[error("invalid hexadecimal data: odd number of digits")]
26 OddHexDigits,
27}
28
29#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
46pub struct PgBytea(Vec<u8>);
47
48impl PgBytea {
49 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 pub fn as_bytes(&self) -> &[u8] {
64 &self.0
65 }
66
67 pub fn into_bytes(self) -> Vec<u8> {
69 self.0
70 }
71
72 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
91struct 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
104fn 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
125fn 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
134fn 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}