zero_postgres/conversion/
bytes.rs1use crate::error::{Error, Result};
4use crate::protocol::types::{Oid, oid};
5
6use super::{FromWireValue, ToWireValue};
7
8impl<'a> FromWireValue<'a> for &'a [u8] {
9 fn from_text(oid: Oid, bytes: &'a [u8]) -> Result<Self> {
10 if oid != oid::BYTEA {
11 return Err(Error::Decode(format!("cannot decode oid {} as bytes", oid)));
12 }
13 Ok(bytes)
16 }
17
18 fn from_binary(oid: Oid, bytes: &'a [u8]) -> Result<Self> {
19 if oid != oid::BYTEA {
20 return Err(Error::Decode(format!("cannot decode oid {} as bytes", oid)));
21 }
22 Ok(bytes)
23 }
24}
25
26impl FromWireValue<'_> for Vec<u8> {
27 fn from_text(oid: Oid, bytes: &[u8]) -> Result<Self> {
28 if oid != oid::BYTEA {
29 return Err(Error::Decode(format!(
30 "cannot decode oid {} as Vec<u8>",
31 oid
32 )));
33 }
34 if bytes.starts_with(b"\\x") {
36 decode_hex(&bytes[2..])
37 } else {
38 Ok(bytes.to_vec())
40 }
41 }
42
43 fn from_binary(oid: Oid, bytes: &[u8]) -> Result<Self> {
44 if oid != oid::BYTEA {
45 return Err(Error::Decode(format!(
46 "cannot decode oid {} as Vec<u8>",
47 oid
48 )));
49 }
50 Ok(bytes.to_vec())
51 }
52}
53
54impl ToWireValue for [u8] {
55 fn natural_oid(&self) -> Oid {
56 oid::BYTEA
57 }
58
59 fn encode(&self, target_oid: Oid, buf: &mut Vec<u8>) -> Result<()> {
60 match target_oid {
61 oid::BYTEA => {
62 buf.extend_from_slice(&(self.len() as i32).to_be_bytes());
63 buf.extend_from_slice(self);
64 Ok(())
65 }
66 _ => Err(Error::type_mismatch(self.natural_oid(), target_oid)),
67 }
68 }
69}
70
71impl ToWireValue for Vec<u8> {
72 fn natural_oid(&self) -> Oid {
73 oid::BYTEA
74 }
75
76 fn encode(&self, target_oid: Oid, buf: &mut Vec<u8>) -> Result<()> {
77 self.as_slice().encode(target_oid, buf)
78 }
79}
80
81fn decode_hex(hex: &[u8]) -> Result<Vec<u8>> {
83 if !hex.len().is_multiple_of(2) {
84 return Err(Error::Decode("invalid hex length".into()));
85 }
86
87 let mut result = Vec::with_capacity(hex.len() >> 1);
88 for chunk in hex.chunks(2) {
89 let high = hex_digit(chunk[0])?;
90 let low = hex_digit(chunk[1])?;
91 result.push((high << 4) | low);
92 }
93 Ok(result)
94}
95
96fn hex_digit(b: u8) -> Result<u8> {
97 match b {
98 b'0'..=b'9' => Ok(b - b'0'),
99 b'a'..=b'f' => Ok(b - b'a' + 10),
100 b'A'..=b'F' => Ok(b - b'A' + 10),
101 _ => Err(Error::Decode(format!("invalid hex digit: {}", b as char))),
102 }
103}
104
105#[cfg(test)]
106mod tests {
107 use super::*;
108
109 #[test]
110 fn test_bytea_hex() {
111 assert_eq!(
112 Vec::<u8>::from_text(oid::BYTEA, b"\\xDEADBEEF").unwrap(),
113 vec![0xDE, 0xAD, 0xBE, 0xEF]
114 );
115 }
116}