postgres_types_extra/
pg_box.rs

1use bytes::{Buf, BufMut, BytesMut};
2use postgres_types::{FromSql, IsNull, ToSql, Type, accepts, to_sql_checked};
3use std::{error::Error, fmt};
4
5use crate::pg_point::PgPoint;
6
7#[derive(Debug)]
8pub struct PgBox {
9    pub high: PgPoint,
10    pub low: PgPoint,
11}
12
13impl fmt::Display for PgBox {
14    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
15        write!(
16            f,
17            "({},{}),({},{})",
18            self.high.x, self.high.y, self.low.x, self.low.y
19        )
20    }
21}
22
23impl FromSql<'_> for PgBox {
24    fn from_sql(ty: &Type, mut raw: &[u8]) -> Result<Self, Box<dyn Error + Sync + Send>> {
25        if ty.name() != "box" {
26            return Err("Unexpected type".into());
27        }
28        let high_x = raw.get_f64();
29        let high_y = raw.get_f64();
30        let low_x = raw.get_f64();
31        let low_y = raw.get_f64();
32        Ok(PgBox {
33            high: PgPoint {
34                x: high_x,
35                y: high_y,
36            },
37            low: PgPoint { x: low_x, y: low_y },
38        })
39    }
40
41    accepts!(BOX);
42}
43
44impl ToSql for PgBox {
45    fn to_sql(
46        &self,
47        ty: &Type,
48        out: &mut BytesMut,
49    ) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
50        if ty.name() != "box" {
51            return Err("Unexpected type".into());
52        }
53
54        // Write 4 f64 values in network (big-endian) order
55        out.put_f64(self.high.x);
56        out.put_f64(self.high.y);
57        out.put_f64(self.low.x);
58        out.put_f64(self.low.y);
59
60        Ok(IsNull::No)
61    }
62
63    accepts!(BOX);
64
65    to_sql_checked!();
66}