Skip to main content

turnloop_postgres/
wire.rs

1use crate::{Error, Result};
2
3#[derive(Clone, Copy, Debug)]
4pub(crate) struct Cursor<'a>(pub &'a [u8]);
5impl<'a> Cursor<'a> {
6    pub fn take(&mut self, n: usize) -> Result<&'a [u8]> {
7        if n > self.0.len() {
8            return Err(Error::Protocol("truncated message"));
9        }
10        let (v, rest) = self.0.split_at(n);
11        self.0 = rest;
12        Ok(v)
13    }
14    pub fn u8(&mut self) -> Result<u8> {
15        Ok(self.take(1)?[0])
16    }
17    pub fn i16(&mut self) -> Result<i16> {
18        Ok(i16::from_be_bytes(self.take(2)?.try_into().unwrap()))
19    }
20    pub fn u16(&mut self) -> Result<u16> {
21        Ok(u16::from_be_bytes(self.take(2)?.try_into().unwrap()))
22    }
23    pub fn i32(&mut self) -> Result<i32> {
24        Ok(i32::from_be_bytes(self.take(4)?.try_into().unwrap()))
25    }
26    pub fn u32(&mut self) -> Result<u32> {
27        Ok(u32::from_be_bytes(self.take(4)?.try_into().unwrap()))
28    }
29    pub fn cstr(&mut self) -> Result<&'a str> {
30        let n = self
31            .0
32            .iter()
33            .position(|b| *b == 0)
34            .ok_or(Error::Protocol("missing terminator"))?;
35        let s = self.take(n + 1)?;
36        std::str::from_utf8(&s[..n]).map_err(|_| Error::Protocol("invalid UTF-8"))
37    }
38    pub fn end(self) -> Result<()> {
39        if self.0.is_empty() {
40            Ok(())
41        } else {
42            Err(Error::Protocol("trailing message bytes"))
43        }
44    }
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub struct Field<'a> {
49    pub name: &'a str,
50    pub table_id: u32,
51    pub column_id: i16,
52    pub data_type_id: u32,
53    pub data_type_size: i16,
54    pub data_type_modifier: i32,
55    pub format: i16,
56}
57#[derive(Debug, Clone, Copy)]
58pub struct Fields<'a> {
59    cursor: Cursor<'a>,
60    remaining: u16,
61}
62impl<'a> Fields<'a> {
63    pub(crate) fn parse(body: &'a [u8]) -> Result<Self> {
64        let mut cursor = Cursor(body);
65        let remaining = cursor.u16()?;
66        let fields = Self { cursor, remaining };
67        let mut check = fields;
68        for field in &mut check {
69            field?;
70        }
71        check.cursor.end()?;
72        Ok(fields)
73    }
74}
75impl<'a> Iterator for Fields<'a> {
76    type Item = Result<Field<'a>>;
77    fn next(&mut self) -> Option<Self::Item> {
78        if self.remaining == 0 {
79            return None;
80        }
81        self.remaining -= 1;
82        Some((|| {
83            Ok(Field {
84                name: self.cursor.cstr()?,
85                table_id: self.cursor.u32()?,
86                column_id: self.cursor.i16()?,
87                data_type_id: self.cursor.u32()?,
88                data_type_size: self.cursor.i16()?,
89                data_type_modifier: self.cursor.i32()?,
90                format: self.cursor.i16()?,
91            })
92        })())
93    }
94    fn size_hint(&self) -> (usize, Option<usize>) {
95        (self.remaining as usize, Some(self.remaining as usize))
96    }
97}
98impl ExactSizeIterator for Fields<'_> {}
99
100/// Borrowed, already validated PostgreSQL row. Iteration never allocates.
101#[derive(Debug, Clone, Copy)]
102pub struct Row<'a> {
103    cursor: Cursor<'a>,
104    remaining: u16,
105}
106impl<'a> Row<'a> {
107    pub(crate) fn parse(body: &'a [u8]) -> Result<Self> {
108        let mut cursor = Cursor(body);
109        let remaining = cursor.u16()?;
110        let row = Self { cursor, remaining };
111        let mut check = row;
112        for value in &mut check {
113            value?;
114        }
115        check.cursor.end()?;
116        Ok(row)
117    }
118}
119impl<'a> Iterator for Row<'a> {
120    type Item = Result<Option<&'a [u8]>>;
121    fn next(&mut self) -> Option<Self::Item> {
122        if self.remaining == 0 {
123            return None;
124        }
125        self.remaining -= 1;
126        Some((|| {
127            let n = self.cursor.i32()?;
128            match n {
129                -1 => Ok(None),
130                0.. => Ok(Some(self.cursor.take(n as usize)?)),
131                _ => Err(Error::Protocol("invalid field length")),
132            }
133        })())
134    }
135    fn size_hint(&self) -> (usize, Option<usize>) {
136        (self.remaining as usize, Some(self.remaining as usize))
137    }
138}
139impl ExactSizeIterator for Row<'_> {}
140
141/// ErrorResponse and NoticeResponse retain every field, including future fields.
142#[derive(Clone, Copy, Debug)]
143pub struct ServerError<'a>(pub(crate) &'a [u8]);
144
145/// Owned terminal server diagnostic. Clones share one copy of all wire fields.
146/// Only connection failure allocates; ordinary statement errors remain borrowed.
147#[derive(Clone, PartialEq, Eq)]
148pub struct ConnectionFailure(std::sync::Arc<[u8]>);
149impl ConnectionFailure {
150    pub(crate) fn new(error: ServerError<'_>) -> Self {
151        Self(error.0.into())
152    }
153    pub fn server_error(&self) -> ServerError<'_> {
154        ServerError(&self.0)
155    }
156}
157impl std::fmt::Display for ConnectionFailure {
158    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
159        let error = self.server_error();
160        write!(f, "{}: {}", error.code(), error.message())
161    }
162}
163impl std::fmt::Debug for ConnectionFailure {
164    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165        f.debug_map().entries(self.server_error().fields()).finish()
166    }
167}
168impl<'a> ServerError<'a> {
169    pub(crate) fn parse(body: &'a [u8]) -> Result<Self> {
170        let mut c = Cursor(body);
171        while c.u8()? != 0 {
172            c.cstr()?;
173        }
174        c.end()?;
175        Ok(Self(body))
176    }
177    pub fn fields(self) -> impl Iterator<Item = (u8, &'a str)> {
178        let mut c = Cursor(self.0);
179        std::iter::from_fn(move || {
180            let tag = c.u8().ok()?;
181            if tag == 0 {
182                None
183            } else {
184                Some((tag, c.cstr().ok()?))
185            }
186        })
187    }
188    pub fn get(self, tag: u8) -> Option<&'a str> {
189        self.fields().find(|(t, _)| *t == tag).map(|(_, v)| v)
190    }
191    pub fn code(self) -> &'a str {
192        self.get(b'C').unwrap_or("")
193    }
194    pub fn message(self) -> &'a str {
195        self.get(b'M').unwrap_or("")
196    }
197    pub fn severity(self) -> Option<&'a str> {
198        self.get(b'S')
199    }
200    pub fn detail(self) -> Option<&'a str> {
201        self.get(b'D')
202    }
203    pub fn hint(self) -> Option<&'a str> {
204        self.get(b'H')
205    }
206    pub fn internal_position(self) -> Option<&'a str> {
207        self.get(b'p')
208    }
209    pub fn internal_query(self) -> Option<&'a str> {
210        self.get(b'q')
211    }
212    pub fn context(self) -> Option<&'a str> {
213        self.get(b'W')
214    }
215    pub fn schema(self) -> Option<&'a str> {
216        self.get(b's')
217    }
218    pub fn table(self) -> Option<&'a str> {
219        self.get(b't')
220    }
221    pub fn column(self) -> Option<&'a str> {
222        self.get(b'c')
223    }
224    pub fn data_type(self) -> Option<&'a str> {
225        self.get(b'd')
226    }
227    pub fn constraint(self) -> Option<&'a str> {
228        self.get(b'n')
229    }
230    pub fn file(self) -> Option<&'a str> {
231        self.get(b'F')
232    }
233    pub fn line(self) -> Option<&'a str> {
234        self.get(b'L')
235    }
236    pub fn routine(self) -> Option<&'a str> {
237        self.get(b'R')
238    }
239    pub fn position(self) -> Option<&'a str> {
240        self.get(b'P')
241    }
242}