sqlx_postgres/types/geometry/
circle.rs1use crate::decode::Decode;
2use crate::encode::{Encode, IsNull};
3use crate::error::BoxDynError;
4use crate::types::Type;
5use crate::{PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueFormat, PgValueRef, Postgres};
6use sqlx_core::bytes::Buf;
7use sqlx_core::Error;
8use std::str::FromStr;
9
10const ERROR: &str = "error decoding CIRCLE";
11
12#[derive(Debug, Clone, PartialEq)]
30pub struct PgCircle {
31 pub x: f64,
32 pub y: f64,
33 pub radius: f64,
34}
35
36impl Type<Postgres> for PgCircle {
37 fn type_info() -> PgTypeInfo {
38 PgTypeInfo::with_name("circle")
39 }
40}
41
42impl PgHasArrayType for PgCircle {
43 fn array_type_info() -> PgTypeInfo {
44 PgTypeInfo::with_name("_circle")
45 }
46}
47
48impl<'r> Decode<'r, Postgres> for PgCircle {
49 fn decode(value: PgValueRef<'r>) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
50 match value.format() {
51 PgValueFormat::Text => Ok(PgCircle::from_str(value.as_str()?)?),
52 PgValueFormat::Binary => Ok(PgCircle::from_bytes(value.as_bytes()?)?),
53 }
54 }
55}
56
57impl<'q> Encode<'q, Postgres> for PgCircle {
58 fn produces(&self) -> Option<PgTypeInfo> {
59 Some(PgTypeInfo::with_name("circle"))
60 }
61
62 fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> {
63 self.serialize(buf)?;
64 Ok(IsNull::No)
65 }
66}
67
68impl FromStr for PgCircle {
69 type Err = BoxDynError;
70
71 fn from_str(s: &str) -> Result<Self, Self::Err> {
72 let sanitised = s.replace(['<', '>', '(', ')', ' '], "");
73 let mut parts = sanitised.split(',');
74
75 let x = parts
76 .next()
77 .and_then(|s| s.trim().parse::<f64>().ok())
78 .ok_or_else(|| format!("{}: could not get x from {}", ERROR, s))?;
79
80 let y = parts
81 .next()
82 .and_then(|s| s.trim().parse::<f64>().ok())
83 .ok_or_else(|| format!("{}: could not get y from {}", ERROR, s))?;
84
85 let radius = parts
86 .next()
87 .and_then(|s| s.trim().parse::<f64>().ok())
88 .ok_or_else(|| format!("{}: could not get radius from {}", ERROR, s))?;
89
90 if parts.next().is_some() {
91 return Err(format!("{}: too many numbers inputted in {}", ERROR, s).into());
92 }
93
94 if radius < 0. {
95 return Err(format!("{}: cannot have negative radius: {}", ERROR, s).into());
96 }
97
98 Ok(PgCircle { x, y, radius })
99 }
100}
101
102impl PgCircle {
103 fn from_bytes(mut bytes: &[u8]) -> Result<PgCircle, Error> {
104 let x = bytes.get_f64();
105 let y = bytes.get_f64();
106 let r = bytes.get_f64();
107 Ok(PgCircle { x, y, radius: r })
108 }
109
110 fn serialize(&self, buff: &mut PgArgumentBuffer) -> Result<(), Error> {
111 buff.extend_from_slice(&self.x.to_be_bytes());
112 buff.extend_from_slice(&self.y.to_be_bytes());
113 buff.extend_from_slice(&self.radius.to_be_bytes());
114 Ok(())
115 }
116
117 #[cfg(test)]
118 fn serialize_to_vec(&self) -> Vec<u8> {
119 let mut buff = PgArgumentBuffer::default();
120 self.serialize(&mut buff).unwrap();
121 buff.to_vec()
122 }
123}
124
125#[cfg(test)]
126mod circle_tests {
127
128 use std::str::FromStr;
129
130 use super::PgCircle;
131
132 const CIRCLE_BYTES: &[u8] = &[
133 63, 241, 153, 153, 153, 153, 153, 154, 64, 1, 153, 153, 153, 153, 153, 154, 64, 10, 102,
134 102, 102, 102, 102, 102,
135 ];
136
137 #[test]
138 fn can_deserialise_circle_type_bytes() {
139 let circle = PgCircle::from_bytes(CIRCLE_BYTES).unwrap();
140 assert_eq!(
141 circle,
142 PgCircle {
143 x: 1.1,
144 y: 2.2,
145 radius: 3.3
146 }
147 )
148 }
149
150 #[test]
151 fn can_deserialise_circle_type_str() {
152 let circle = PgCircle::from_str("<(1, 2), 3 >").unwrap();
153 assert_eq!(
154 circle,
155 PgCircle {
156 x: 1.0,
157 y: 2.0,
158 radius: 3.0
159 }
160 );
161 }
162
163 #[test]
164 fn can_deserialise_circle_type_str_second_syntax() {
165 let circle = PgCircle::from_str("((1, 2), 3 )").unwrap();
166 assert_eq!(
167 circle,
168 PgCircle {
169 x: 1.0,
170 y: 2.0,
171 radius: 3.0
172 }
173 );
174 }
175
176 #[test]
177 fn can_deserialise_circle_type_str_third_syntax() {
178 let circle = PgCircle::from_str("(1, 2), 3 ").unwrap();
179 assert_eq!(
180 circle,
181 PgCircle {
182 x: 1.0,
183 y: 2.0,
184 radius: 3.0
185 }
186 );
187 }
188
189 #[test]
190 fn can_deserialise_circle_type_str_fourth_syntax() {
191 let circle = PgCircle::from_str("1, 2, 3 ").unwrap();
192 assert_eq!(
193 circle,
194 PgCircle {
195 x: 1.0,
196 y: 2.0,
197 radius: 3.0
198 }
199 );
200 }
201
202 #[test]
203 fn cannot_deserialise_circle_invalid_numbers() {
204 let input_str = "1, 2, Three";
205 let circle = PgCircle::from_str(input_str);
206 assert!(circle.is_err());
207 if let Err(err) = circle {
208 assert_eq!(
209 err.to_string(),
210 format!("error decoding CIRCLE: could not get radius from {input_str}")
211 )
212 }
213 }
214
215 #[test]
216 fn cannot_deserialise_circle_negative_radius() {
217 let input_str = "1, 2, -3";
218 let circle = PgCircle::from_str(input_str);
219 assert!(circle.is_err());
220 if let Err(err) = circle {
221 assert_eq!(
222 err.to_string(),
223 format!("error decoding CIRCLE: cannot have negative radius: {input_str}")
224 )
225 }
226 }
227
228 #[test]
229 fn can_deserialise_circle_type_str_float() {
230 let circle = PgCircle::from_str("<(1.1, 2.2), 3.3>").unwrap();
231 assert_eq!(
232 circle,
233 PgCircle {
234 x: 1.1,
235 y: 2.2,
236 radius: 3.3
237 }
238 );
239 }
240
241 #[test]
242 fn can_serialise_circle_type() {
243 let circle = PgCircle {
244 x: 1.1,
245 y: 2.2,
246 radius: 3.3,
247 };
248 assert_eq!(circle.serialize_to_vec(), CIRCLE_BYTES,)
249 }
250}