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<'_> {}
99impl Fields<'_> {
100    /// Copy the unread field descriptions out of the connection's buffer.
101    /// One allocation; the result outlives every later mutable call.
102    pub fn into_owned(self) -> OwnedFields {
103        OwnedFields {
104            data: self.cursor.0.into(),
105            remaining: self.remaining,
106        }
107    }
108}
109/// Owned RowDescription. `fields()` iterates it exactly like the borrowed form.
110#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct OwnedFields {
112    data: Box<[u8]>,
113    remaining: u16,
114}
115impl OwnedFields {
116    pub fn fields(&self) -> Fields<'_> {
117        Fields {
118            cursor: Cursor(&self.data),
119            remaining: self.remaining,
120        }
121    }
122    pub fn len(&self) -> usize {
123        self.remaining as usize
124    }
125    pub fn is_empty(&self) -> bool {
126        self.remaining == 0
127    }
128}
129
130/// Borrowed, already validated PostgreSQL row. Iteration never allocates.
131#[derive(Debug, Clone, Copy)]
132pub struct Row<'a> {
133    cursor: Cursor<'a>,
134    remaining: u16,
135}
136impl<'a> Row<'a> {
137    pub(crate) fn parse(body: &'a [u8]) -> Result<Self> {
138        let mut cursor = Cursor(body);
139        let remaining = cursor.u16()?;
140        let row = Self { cursor, remaining };
141        let mut check = row;
142        for value in &mut check {
143            value?;
144        }
145        check.cursor.end()?;
146        Ok(row)
147    }
148}
149impl<'a> Iterator for Row<'a> {
150    type Item = Result<Option<&'a [u8]>>;
151    fn next(&mut self) -> Option<Self::Item> {
152        if self.remaining == 0 {
153            return None;
154        }
155        self.remaining -= 1;
156        Some((|| {
157            let n = self.cursor.i32()?;
158            match n {
159                -1 => Ok(None),
160                0.. => Ok(Some(self.cursor.take(n as usize)?)),
161                _ => Err(Error::Protocol("invalid field length")),
162            }
163        })())
164    }
165    fn size_hint(&self) -> (usize, Option<usize>) {
166        (self.remaining as usize, Some(self.remaining as usize))
167    }
168}
169impl ExactSizeIterator for Row<'_> {}
170impl Row<'_> {
171    /// Copy the unread values out of the connection's buffer in one allocation,
172    /// so the row can be retained past the next mutable call on the connection.
173    pub fn into_owned(self) -> OwnedRow {
174        OwnedRow {
175            data: self.cursor.0.into(),
176            remaining: self.remaining,
177        }
178    }
179}
180/// Owned, already validated DataRow. `row()` lends the same borrowed iterator,
181/// so one host decoder serves both forms; `get` indexes a column directly.
182#[derive(Debug, Clone, PartialEq, Eq)]
183pub struct OwnedRow {
184    data: Box<[u8]>,
185    remaining: u16,
186}
187impl OwnedRow {
188    pub fn row(&self) -> Row<'_> {
189        Row {
190            cursor: Cursor(&self.data),
191            remaining: self.remaining,
192        }
193    }
194    /// `None` past the last column; `Some(None)` is SQL NULL.
195    pub fn get(&self, index: usize) -> Option<Option<&[u8]>> {
196        self.row().nth(index)?.ok()
197    }
198    pub fn len(&self) -> usize {
199        self.remaining as usize
200    }
201    pub fn is_empty(&self) -> bool {
202        self.remaining == 0
203    }
204}
205
206/// ErrorResponse and NoticeResponse retain every field, including future fields.
207#[derive(Clone, Copy, Debug)]
208pub struct ServerError<'a>(pub(crate) &'a [u8]);
209
210/// Owned terminal server diagnostic. Clones share one copy of all wire fields.
211/// Only connection failure allocates; ordinary statement errors remain borrowed.
212#[derive(Clone, PartialEq, Eq)]
213pub struct ConnectionFailure(std::sync::Arc<[u8]>);
214impl ConnectionFailure {
215    pub(crate) fn new(error: ServerError<'_>) -> Self {
216        Self(error.0.into())
217    }
218    pub fn server_error(&self) -> ServerError<'_> {
219        ServerError(&self.0)
220    }
221}
222impl std::fmt::Display for ConnectionFailure {
223    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
224        let error = self.server_error();
225        write!(f, "{}: {}", error.code(), error.message())
226    }
227}
228impl std::fmt::Debug for ConnectionFailure {
229    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
230        f.debug_map().entries(self.server_error().fields()).finish()
231    }
232}
233/// Owned ErrorResponse/NoticeResponse with every field, including future ones.
234#[derive(Clone, PartialEq, Eq)]
235pub struct OwnedServerError(Box<[u8]>);
236impl OwnedServerError {
237    pub fn server_error(&self) -> ServerError<'_> {
238        ServerError(&self.0)
239    }
240}
241impl std::fmt::Display for OwnedServerError {
242    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
243        let error = self.server_error();
244        write!(f, "{}: {}", error.code(), error.message())
245    }
246}
247impl std::fmt::Debug for OwnedServerError {
248    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
249        f.debug_map().entries(self.server_error().fields()).finish()
250    }
251}
252impl<'a> ServerError<'a> {
253    /// Copy every field out of the connection's buffer in one allocation.
254    pub fn into_owned(self) -> OwnedServerError {
255        OwnedServerError(self.0.into())
256    }
257    pub(crate) fn parse(body: &'a [u8]) -> Result<Self> {
258        let mut c = Cursor(body);
259        while c.u8()? != 0 {
260            c.cstr()?;
261        }
262        c.end()?;
263        Ok(Self(body))
264    }
265    pub fn fields(self) -> impl Iterator<Item = (u8, &'a str)> {
266        let mut c = Cursor(self.0);
267        std::iter::from_fn(move || {
268            let tag = c.u8().ok()?;
269            if tag == 0 {
270                None
271            } else {
272                Some((tag, c.cstr().ok()?))
273            }
274        })
275    }
276    pub fn get(self, tag: u8) -> Option<&'a str> {
277        self.fields().find(|(t, _)| *t == tag).map(|(_, v)| v)
278    }
279    pub fn code(self) -> &'a str {
280        self.get(b'C').unwrap_or("")
281    }
282    pub fn message(self) -> &'a str {
283        self.get(b'M').unwrap_or("")
284    }
285    pub fn severity(self) -> Option<&'a str> {
286        self.get(b'S')
287    }
288    pub fn detail(self) -> Option<&'a str> {
289        self.get(b'D')
290    }
291    pub fn hint(self) -> Option<&'a str> {
292        self.get(b'H')
293    }
294    pub fn internal_position(self) -> Option<&'a str> {
295        self.get(b'p')
296    }
297    pub fn internal_query(self) -> Option<&'a str> {
298        self.get(b'q')
299    }
300    pub fn context(self) -> Option<&'a str> {
301        self.get(b'W')
302    }
303    pub fn schema(self) -> Option<&'a str> {
304        self.get(b's')
305    }
306    pub fn table(self) -> Option<&'a str> {
307        self.get(b't')
308    }
309    pub fn column(self) -> Option<&'a str> {
310        self.get(b'c')
311    }
312    pub fn data_type(self) -> Option<&'a str> {
313        self.get(b'd')
314    }
315    pub fn constraint(self) -> Option<&'a str> {
316        self.get(b'n')
317    }
318    pub fn file(self) -> Option<&'a str> {
319        self.get(b'F')
320    }
321    pub fn line(self) -> Option<&'a str> {
322        self.get(b'L')
323    }
324    pub fn routine(self) -> Option<&'a str> {
325        self.get(b'R')
326    }
327    pub fn position(self) -> Option<&'a str> {
328        self.get(b'P')
329    }
330}