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]);
144impl<'a> ServerError<'a> {
145    pub(crate) fn parse(body: &'a [u8]) -> Result<Self> {
146        let mut c = Cursor(body);
147        while c.u8()? != 0 {
148            c.cstr()?;
149        }
150        c.end()?;
151        Ok(Self(body))
152    }
153    pub fn fields(self) -> impl Iterator<Item = (u8, &'a str)> {
154        let mut c = Cursor(self.0);
155        std::iter::from_fn(move || {
156            let tag = c.u8().ok()?;
157            if tag == 0 {
158                None
159            } else {
160                Some((tag, c.cstr().ok()?))
161            }
162        })
163    }
164    pub fn get(self, tag: u8) -> Option<&'a str> {
165        self.fields().find(|(t, _)| *t == tag).map(|(_, v)| v)
166    }
167    pub fn code(self) -> &'a str {
168        self.get(b'C').unwrap_or("")
169    }
170    pub fn message(self) -> &'a str {
171        self.get(b'M').unwrap_or("")
172    }
173    pub fn severity(self) -> Option<&'a str> {
174        self.get(b'S')
175    }
176    pub fn detail(self) -> Option<&'a str> {
177        self.get(b'D')
178    }
179    pub fn hint(self) -> Option<&'a str> {
180        self.get(b'H')
181    }
182    pub fn internal_position(self) -> Option<&'a str> {
183        self.get(b'p')
184    }
185    pub fn internal_query(self) -> Option<&'a str> {
186        self.get(b'q')
187    }
188    pub fn context(self) -> Option<&'a str> {
189        self.get(b'W')
190    }
191    pub fn schema(self) -> Option<&'a str> {
192        self.get(b's')
193    }
194    pub fn table(self) -> Option<&'a str> {
195        self.get(b't')
196    }
197    pub fn column(self) -> Option<&'a str> {
198        self.get(b'c')
199    }
200    pub fn data_type(self) -> Option<&'a str> {
201        self.get(b'd')
202    }
203    pub fn constraint(self) -> Option<&'a str> {
204        self.get(b'n')
205    }
206    pub fn file(self) -> Option<&'a str> {
207        self.get(b'F')
208    }
209    pub fn line(self) -> Option<&'a str> {
210        self.get(b'L')
211    }
212    pub fn routine(self) -> Option<&'a str> {
213        self.get(b'R')
214    }
215    pub fn position(self) -> Option<&'a str> {
216        self.get(b'P')
217    }
218}