|
| 1 | +use crate::decode::Decode; |
| 2 | +use crate::encode::{Encode, IsNull}; |
| 3 | +use crate::error::BoxDynError; |
| 4 | +use crate::types::Type; |
| 5 | +use crate::{PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueFormat, PgValueRef, Postgres}; |
| 6 | +use sqlx_core::bytes::Buf; |
| 7 | +use std::str::FromStr; |
| 8 | + |
| 9 | +const ERROR: &str = "error decoding BOX"; |
| 10 | + |
| 11 | +/// ## Postgres Geometric Box type |
| 12 | +/// |
| 13 | +/// Description: Rectangular box |
| 14 | +/// Representation: `((upper_right_x,upper_right_y),(lower_left_x,lower_left_y))` |
| 15 | +/// |
| 16 | +/// Boxes are represented by pairs of points that are opposite corners of the box. Values of type box are specified using any of the following syntaxes: |
| 17 | +/// |
| 18 | +/// ```text |
| 19 | +/// ( ( upper_right_x , upper_right_y ) , ( lower_left_x , lower_left_y ) ) |
| 20 | +/// ( upper_right_x , upper_right_y ) , ( lower_left_x , lower_left_y ) |
| 21 | +/// upper_right_x , upper_right_y , lower_left_x , lower_left_y |
| 22 | +/// ``` |
| 23 | +/// where `(upper_right_x,upper_right_y) and (lower_left_x,lower_left_y)` are any two opposite corners of the box. |
| 24 | +/// Any two opposite corners can be supplied on input, but the values will be reordered as needed to store the upper right and lower left corners, in that order. |
| 25 | +/// |
| 26 | +/// See https://www.postgresql.org/docs/16/datatype-geometric.html#DATATYPE-GEOMETRIC-BOXES |
| 27 | +#[derive(Debug, Clone, PartialEq)] |
| 28 | +pub struct PgBox { |
| 29 | + pub upper_right_x: f64, |
| 30 | + pub upper_right_y: f64, |
| 31 | + pub lower_left_x: f64, |
| 32 | + pub lower_left_y: f64, |
| 33 | +} |
| 34 | + |
| 35 | +impl Type<Postgres> for PgBox { |
| 36 | + fn type_info() -> PgTypeInfo { |
| 37 | + PgTypeInfo::with_name("box") |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +impl PgHasArrayType for PgBox { |
| 42 | + fn array_type_info() -> PgTypeInfo { |
| 43 | + PgTypeInfo::with_name("_box") |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +impl<'r> Decode<'r, Postgres> for PgBox { |
| 48 | + fn decode(value: PgValueRef<'r>) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> { |
| 49 | + match value.format() { |
| 50 | + PgValueFormat::Text => Ok(PgBox::from_str(value.as_str()?)?), |
| 51 | + PgValueFormat::Binary => Ok(PgBox::from_bytes(value.as_bytes()?)?), |
| 52 | + } |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +impl<'q> Encode<'q, Postgres> for PgBox { |
| 57 | + fn produces(&self) -> Option<PgTypeInfo> { |
| 58 | + Some(PgTypeInfo::with_name("box")) |
| 59 | + } |
| 60 | + |
| 61 | + fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> { |
| 62 | + self.serialize(buf)?; |
| 63 | + Ok(IsNull::No) |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +impl FromStr for PgBox { |
| 68 | + type Err = BoxDynError; |
| 69 | + |
| 70 | + fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 71 | + let sanitised = s.replace(['(', ')', '[', ']', ' '], ""); |
| 72 | + let mut parts = sanitised.split(','); |
| 73 | + |
| 74 | + let upper_right_x = parts |
| 75 | + .next() |
| 76 | + .and_then(|s| s.parse::<f64>().ok()) |
| 77 | + .ok_or_else(|| format!("{}: could not get upper_right_x from {}", ERROR, s))?; |
| 78 | + |
| 79 | + let upper_right_y = parts |
| 80 | + .next() |
| 81 | + .and_then(|s| s.parse::<f64>().ok()) |
| 82 | + .ok_or_else(|| format!("{}: could not get upper_right_y from {}", ERROR, s))?; |
| 83 | + |
| 84 | + let lower_left_x = parts |
| 85 | + .next() |
| 86 | + .and_then(|s| s.parse::<f64>().ok()) |
| 87 | + .ok_or_else(|| format!("{}: could not get lower_left_x from {}", ERROR, s))?; |
| 88 | + |
| 89 | + let lower_left_y = parts |
| 90 | + .next() |
| 91 | + .and_then(|s| s.parse::<f64>().ok()) |
| 92 | + .ok_or_else(|| format!("{}: could not get lower_left_y from {}", ERROR, s))?; |
| 93 | + |
| 94 | + if parts.next().is_some() { |
| 95 | + return Err(format!("{}: too many numbers inputted in {}", ERROR, s).into()); |
| 96 | + } |
| 97 | + |
| 98 | + Ok(PgBox { |
| 99 | + upper_right_x, |
| 100 | + upper_right_y, |
| 101 | + lower_left_x, |
| 102 | + lower_left_y, |
| 103 | + }) |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +impl PgBox { |
| 108 | + fn from_bytes(mut bytes: &[u8]) -> Result<PgBox, BoxDynError> { |
| 109 | + let upper_right_x = bytes.get_f64(); |
| 110 | + let upper_right_y = bytes.get_f64(); |
| 111 | + let lower_left_x = bytes.get_f64(); |
| 112 | + let lower_left_y = bytes.get_f64(); |
| 113 | + |
| 114 | + Ok(PgBox { |
| 115 | + upper_right_x, |
| 116 | + upper_right_y, |
| 117 | + lower_left_x, |
| 118 | + lower_left_y, |
| 119 | + }) |
| 120 | + } |
| 121 | + |
| 122 | + fn serialize(&self, buff: &mut PgArgumentBuffer) -> Result<(), String> { |
| 123 | + let min_x = &self.upper_right_x.min(self.lower_left_x); |
| 124 | + let min_y = &self.upper_right_y.min(self.lower_left_y); |
| 125 | + let max_x = &self.upper_right_x.max(self.lower_left_x); |
| 126 | + let max_y = &self.upper_right_y.max(self.lower_left_y); |
| 127 | + |
| 128 | + buff.extend_from_slice(&max_x.to_be_bytes()); |
| 129 | + buff.extend_from_slice(&max_y.to_be_bytes()); |
| 130 | + buff.extend_from_slice(&min_x.to_be_bytes()); |
| 131 | + buff.extend_from_slice(&min_y.to_be_bytes()); |
| 132 | + |
| 133 | + Ok(()) |
| 134 | + } |
| 135 | + |
| 136 | + #[cfg(test)] |
| 137 | + fn serialize_to_vec(&self) -> Vec<u8> { |
| 138 | + let mut buff = PgArgumentBuffer::default(); |
| 139 | + self.serialize(&mut buff).unwrap(); |
| 140 | + buff.to_vec() |
| 141 | + } |
| 142 | +} |
| 143 | + |
| 144 | +#[cfg(test)] |
| 145 | +mod box_tests { |
| 146 | + |
| 147 | + use std::str::FromStr; |
| 148 | + |
| 149 | + use super::PgBox; |
| 150 | + |
| 151 | + const BOX_BYTES: &[u8] = &[ |
| 152 | + 64, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 192, 0, 0, 0, |
| 153 | + 0, 0, 0, 0, |
| 154 | + ]; |
| 155 | + |
| 156 | + #[test] |
| 157 | + fn can_deserialise_box_type_bytes_in_order() { |
| 158 | + let pg_box = PgBox::from_bytes(BOX_BYTES).unwrap(); |
| 159 | + assert_eq!( |
| 160 | + pg_box, |
| 161 | + PgBox { |
| 162 | + upper_right_x: 2., |
| 163 | + upper_right_y: 2., |
| 164 | + lower_left_x: -2., |
| 165 | + lower_left_y: -2. |
| 166 | + } |
| 167 | + ) |
| 168 | + } |
| 169 | + |
| 170 | + #[test] |
| 171 | + fn can_deserialise_box_type_str_first_syntax() { |
| 172 | + let pg_box = PgBox::from_str("[( 1, 2), (3, 4 )]").unwrap(); |
| 173 | + assert_eq!( |
| 174 | + pg_box, |
| 175 | + PgBox { |
| 176 | + upper_right_x: 1., |
| 177 | + upper_right_y: 2., |
| 178 | + lower_left_x: 3., |
| 179 | + lower_left_y: 4. |
| 180 | + } |
| 181 | + ); |
| 182 | + } |
| 183 | + #[test] |
| 184 | + fn can_deserialise_box_type_str_second_syntax() { |
| 185 | + let pg_box = PgBox::from_str("(( 1, 2), (3, 4 ))").unwrap(); |
| 186 | + assert_eq!( |
| 187 | + pg_box, |
| 188 | + PgBox { |
| 189 | + upper_right_x: 1., |
| 190 | + upper_right_y: 2., |
| 191 | + lower_left_x: 3., |
| 192 | + lower_left_y: 4. |
| 193 | + } |
| 194 | + ); |
| 195 | + } |
| 196 | + |
| 197 | + #[test] |
| 198 | + fn can_deserialise_box_type_str_third_syntax() { |
| 199 | + let pg_box = PgBox::from_str("(1, 2), (3, 4 )").unwrap(); |
| 200 | + assert_eq!( |
| 201 | + pg_box, |
| 202 | + PgBox { |
| 203 | + upper_right_x: 1., |
| 204 | + upper_right_y: 2., |
| 205 | + lower_left_x: 3., |
| 206 | + lower_left_y: 4. |
| 207 | + } |
| 208 | + ); |
| 209 | + } |
| 210 | + |
| 211 | + #[test] |
| 212 | + fn can_deserialise_box_type_str_fourth_syntax() { |
| 213 | + let pg_box = PgBox::from_str("1, 2, 3, 4").unwrap(); |
| 214 | + assert_eq!( |
| 215 | + pg_box, |
| 216 | + PgBox { |
| 217 | + upper_right_x: 1., |
| 218 | + upper_right_y: 2., |
| 219 | + lower_left_x: 3., |
| 220 | + lower_left_y: 4. |
| 221 | + } |
| 222 | + ); |
| 223 | + } |
| 224 | + |
| 225 | + #[test] |
| 226 | + fn cannot_deserialise_too_many_numbers() { |
| 227 | + let input_str = "1, 2, 3, 4, 5"; |
| 228 | + let pg_box = PgBox::from_str(input_str); |
| 229 | + assert!(pg_box.is_err()); |
| 230 | + if let Err(err) = pg_box { |
| 231 | + assert_eq!( |
| 232 | + err.to_string(), |
| 233 | + format!("error decoding BOX: too many numbers inputted in {input_str}") |
| 234 | + ) |
| 235 | + } |
| 236 | + } |
| 237 | + |
| 238 | + #[test] |
| 239 | + fn cannot_deserialise_too_few_numbers() { |
| 240 | + let input_str = "1, 2, 3 "; |
| 241 | + let pg_box = PgBox::from_str(input_str); |
| 242 | + assert!(pg_box.is_err()); |
| 243 | + if let Err(err) = pg_box { |
| 244 | + assert_eq!( |
| 245 | + err.to_string(), |
| 246 | + format!("error decoding BOX: could not get lower_left_y from {input_str}") |
| 247 | + ) |
| 248 | + } |
| 249 | + } |
| 250 | + |
| 251 | + #[test] |
| 252 | + fn cannot_deserialise_invalid_numbers() { |
| 253 | + let input_str = "1, 2, 3, FOUR"; |
| 254 | + let pg_box = PgBox::from_str(input_str); |
| 255 | + assert!(pg_box.is_err()); |
| 256 | + if let Err(err) = pg_box { |
| 257 | + assert_eq!( |
| 258 | + err.to_string(), |
| 259 | + format!("error decoding BOX: could not get lower_left_y from {input_str}") |
| 260 | + ) |
| 261 | + } |
| 262 | + } |
| 263 | + |
| 264 | + #[test] |
| 265 | + fn can_deserialise_box_type_str_float() { |
| 266 | + let pg_box = PgBox::from_str("(1.1, 2.2), (3.3, 4.4)").unwrap(); |
| 267 | + assert_eq!( |
| 268 | + pg_box, |
| 269 | + PgBox { |
| 270 | + upper_right_x: 1.1, |
| 271 | + upper_right_y: 2.2, |
| 272 | + lower_left_x: 3.3, |
| 273 | + lower_left_y: 4.4 |
| 274 | + } |
| 275 | + ); |
| 276 | + } |
| 277 | + |
| 278 | + #[test] |
| 279 | + fn can_serialise_box_type_in_order() { |
| 280 | + let pg_box = PgBox { |
| 281 | + upper_right_x: 2., |
| 282 | + lower_left_x: -2., |
| 283 | + upper_right_y: -2., |
| 284 | + lower_left_y: 2., |
| 285 | + }; |
| 286 | + assert_eq!(pg_box.serialize_to_vec(), BOX_BYTES,) |
| 287 | + } |
| 288 | + |
| 289 | + #[test] |
| 290 | + fn can_serialise_box_type_out_of_order() { |
| 291 | + let pg_box = PgBox { |
| 292 | + upper_right_x: -2., |
| 293 | + lower_left_x: 2., |
| 294 | + upper_right_y: 2., |
| 295 | + lower_left_y: -2., |
| 296 | + }; |
| 297 | + assert_eq!(pg_box.serialize_to_vec(), BOX_BYTES,) |
| 298 | + } |
| 299 | + |
| 300 | + #[test] |
| 301 | + fn can_order_box() { |
| 302 | + let pg_box = PgBox { |
| 303 | + upper_right_x: -2., |
| 304 | + lower_left_x: 2., |
| 305 | + upper_right_y: 2., |
| 306 | + lower_left_y: -2., |
| 307 | + }; |
| 308 | + let bytes = pg_box.serialize_to_vec(); |
| 309 | + |
| 310 | + let pg_box = PgBox::from_bytes(&bytes).unwrap(); |
| 311 | + assert_eq!( |
| 312 | + pg_box, |
| 313 | + PgBox { |
| 314 | + upper_right_x: 2., |
| 315 | + upper_right_y: 2., |
| 316 | + lower_left_x: -2., |
| 317 | + lower_left_y: -2. |
| 318 | + } |
| 319 | + ) |
| 320 | + } |
| 321 | +} |
0 commit comments