postgres_types_extra/
pg_circle.rs1use bytes::{Buf, BufMut};
2use postgres_types::{FromSql, IsNull, ToSql, Type, accepts, to_sql_checked};
3use std::{error::Error, fmt};
4
5use super::pg_point::PgPoint;
6
7#[derive(Debug, Clone)]
8pub struct PgCircle {
9 pub center: PgPoint,
10 pub radius: f64,
11}
12
13impl fmt::Display for PgCircle {
14 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
15 write!(f, "<{},{}>", self.center, self.radius)
16 }
17}
18
19impl FromSql<'_> for PgCircle {
20 fn from_sql(ty: &Type, mut raw: &[u8]) -> Result<Self, Box<dyn Error + Sync + Send>> {
21 if ty.name() != "circle" {
22 return Err("Unexpected type".into());
23 }
24 let x = raw.get_f64();
25 let y = raw.get_f64();
26 let radius = raw.get_f64();
27 Ok(PgCircle {
28 center: PgPoint { x, y },
29 radius,
30 })
31 }
32
33 accepts!(CIRCLE);
34}
35
36impl ToSql for PgCircle {
37 fn to_sql(
38 &self,
39 ty: &Type,
40 out: &mut bytes::BytesMut,
41 ) -> Result<IsNull, Box<dyn Error + Sync + Send>>
42 where
43 Self: Sized,
44 {
45 if ty.name() != "circle" {
46 return Err("Unexpected type".into());
47 }
48
49 out.put_f64(self.center.x);
50 out.put_f64(self.center.y);
51 out.put_f64(self.radius);
52
53 Ok(IsNull::No)
54 }
55
56 accepts!(CIRCLE);
57
58 to_sql_checked!();
59}