1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
use bytes::{BufMut, BytesMut};
use crate::error::{Error, Result};
use crate::types::{FromSql, Oid, ToSql};
/// PostgreSQL CUBE type -- an n-dimensional point or box.
///
/// CUBE is a PostgreSQL extension type for multi-dimensional geometric data.
/// It represents either a point (all dimensions equal) or a box (two corners).
///
/// Binary wire format:
/// - `ndim` (u32): number of dimensions
/// - `flags` (u32): bit 0 = is_point
/// - coordinates: `ndim` f64 values for points, `ndim * 2` for boxes
///
/// Uses TEXT OID as carrier since CUBE is an extension type.
#[derive(Debug, Clone, PartialEq)]
pub struct PgCube {
/// For a point: `[x, y, z, ...]` (ndim values).
/// For a box: `[x1, y1, z1, ..., x2, y2, z2, ...]` (ndim * 2 values).
pub coordinates: Vec<f64>,
/// True if this represents a point, false if a box.
pub is_point: bool,
}
const CUBE_IS_POINT: u32 = 1;
impl PgCube {
/// Create a point with the given coordinates.
pub fn point(coordinates: Vec<f64>) -> Self {
PgCube {
coordinates,
is_point: true,
}
}
/// Create a box with the given coordinates and number of dimensions.
///
/// `coordinates` must have exactly `ndim * 2` values:
/// the first `ndim` are the lower-left corner, the last `ndim` are the upper-right.
pub fn cube(coordinates: Vec<f64>, ndim: usize) -> Self {
debug_assert_eq!(
coordinates.len(),
ndim * 2,
"box coordinates must be ndim * 2"
);
PgCube {
coordinates,
is_point: false,
}
}
/// Number of dimensions.
pub fn ndim(&self) -> usize {
if self.is_point {
self.coordinates.len()
} else if self.coordinates.is_empty() {
0
} else {
self.coordinates.len() / 2
}
}
}
impl ToSql for PgCube {
fn oid(&self) -> Oid {
Oid::TEXT
}
fn to_sql(&self, buf: &mut BytesMut) -> Result<()> {
let ndim = self.ndim() as u32;
let flags = if self.is_point { CUBE_IS_POINT } else { 0 };
buf.put_u32(ndim);
buf.put_u32(flags);
for &coord in &self.coordinates {
buf.put_f64(coord);
}
Ok(())
}
}
impl FromSql for PgCube {
fn oid() -> Oid {
Oid::TEXT
}
fn from_sql(buf: &[u8]) -> Result<Self> {
if buf.len() < 8 {
return Err(Error::Decode(format!(
"cube: expected at least 8 bytes, got {}",
buf.len()
)));
}
let ndim = u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize;
let flags = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]);
let is_point = (flags & CUBE_IS_POINT) != 0;
let num_coords = if is_point { ndim } else { ndim * 2 };
let expected_len = 8 + num_coords * 8;
if buf.len() < expected_len {
return Err(Error::Decode(format!(
"cube: expected {} bytes for {ndim}D {}, got {}",
expected_len,
if is_point { "point" } else { "box" },
buf.len()
)));
}
let mut coordinates = Vec::with_capacity(num_coords);
let mut offset = 8;
for _ in 0..num_coords {
let val = f64::from_be_bytes([
buf[offset],
buf[offset + 1],
buf[offset + 2],
buf[offset + 3],
buf[offset + 4],
buf[offset + 5],
buf[offset + 6],
buf[offset + 7],
]);
coordinates.push(val);
offset += 8;
}
Ok(PgCube {
coordinates,
is_point,
})
}
}
impl std::fmt::Display for PgCube {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.is_point {
write!(f, "(")?;
for (i, coord) in self.coordinates.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{coord}")?;
}
write!(f, ")")
} else {
let ndim = self.ndim();
let (lower, upper) = self.coordinates.split_at(ndim);
write!(f, "(")?;
for (i, coord) in lower.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{coord}")?;
}
write!(f, "),(")?;
for (i, coord) in upper.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{coord}")?;
}
write!(f, ")")
}
}
}