s2rst 0.4.0

A Rust port of Google's S2 spherical geometry library — points, regions, shapes, and a hierarchical cell index on the sphere.
Documentation
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2026 Torgeir Børresen <tb@starkad.no>
// Rust port of Google's S2 Geometry library — a derivative work, modified from
// the upstream Apache-2.0 source(s) below (Copyright Google Inc.). See LICENSE.
//   - C++:  google/s2geometry
//   - Java: google/s2-geometry-library-java

//! A 2D point / vector in ℝ².
//!
//! Corresponds to C++ `R2Point` / `Vector2_d`.

use std::fmt;
use std::ops::{Add, Div, Index, Mul, Neg, Sub};

/// Selects a coordinate axis of a 2D point.
///
/// # Examples
///
/// ```
/// use s2rst::r2::{Axis, Point};
///
/// let p = Point::new(3.0, 4.0);
/// assert_eq!(p[Axis::X], 3.0);
/// assert_eq!(p[Axis::Y], 4.0);
/// ```
#[must_use]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Axis {
    /// The x coordinate.
    #[default]
    X,
    /// The y coordinate.
    Y,
}

/// A point (or vector) in 2D Euclidean space.
///
/// This type is `Copy` and intended to be passed by value.
///
/// # Examples
///
/// ```
/// use s2rst::r2::Point;
///
/// let a = Point::new(3.0, 4.0);
/// let b = Point::new(1.0, 2.0);
///
/// // Arithmetic
/// assert_eq!(a + b, Point::new(4.0, 6.0));
/// assert_eq!(a - b, Point::new(2.0, 2.0));
///
/// // Dot and cross products
/// assert_eq!(a.dot(b), 11.0);   // 3*1 + 4*2
/// assert_eq!(a.cross(b), 2.0);  // 3*2 - 4*1
///
/// // Norm and normalization
/// assert_eq!(a.norm(), 5.0);
/// let n = a.normalize();
/// assert!((n.norm() - 1.0).abs() < 1e-15);
/// ```
#[must_use]
#[derive(Clone, Copy, Debug, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Point {
    /// The x-coordinate.
    pub x: f64,
    /// The y-coordinate.
    pub y: f64,
}

impl Point {
    /// Creates a new point.
    #[inline]
    pub fn new(x: f64, y: f64) -> Self {
        Point { x, y }
    }

    /// Returns the dot product of `self` and `other`.
    #[inline]
    pub fn dot(self, other: Point) -> f64 {
        self.x * other.x + self.y * other.y
    }

    /// Returns the cross product (z-component of the 3D cross product).
    #[inline]
    pub fn cross(self, other: Point) -> f64 {
        self.x * other.y - self.y * other.x
    }

    /// Returns a counterclockwise orthogonal vector with the same norm.
    #[inline]
    pub fn ortho(self) -> Point {
        Point {
            x: -self.y,
            y: self.x,
        }
    }

    /// Returns the squared Euclidean norm.
    #[inline]
    pub fn norm2(self) -> f64 {
        self.x * self.x + self.y * self.y
    }

    /// Returns the Euclidean norm.
    #[inline]
    pub fn norm(self) -> f64 {
        self.x.hypot(self.y)
    }

    /// Returns a unit vector in the same direction, or zero if the vector
    /// is zero-length.
    #[inline]
    pub fn normalize(self) -> Point {
        if self.x == 0.0 && self.y == 0.0 {
            return self;
        }
        self * (1.0 / self.norm())
    }

    /// Returns the angle from `self` to `other` in the counterclockwise
    /// direction, in radians. Range: \[-π, π\].
    #[inline]
    pub fn angle(self, other: Point) -> f64 {
        f64::atan2(self.cross(other), self.dot(other))
    }

    /// Returns the component-wise absolute value.
    #[inline]
    pub fn abs(self) -> Point {
        Point {
            x: self.x.abs(),
            y: self.y.abs(),
        }
    }
}

// --- Arithmetic operator impls ---

impl Add for Point {
    type Output = Point;
    #[inline]
    fn add(self, rhs: Point) -> Point {
        Point {
            x: self.x + rhs.x,
            y: self.y + rhs.y,
        }
    }
}

impl Sub for Point {
    type Output = Point;
    #[inline]
    fn sub(self, rhs: Point) -> Point {
        Point {
            x: self.x - rhs.x,
            y: self.y - rhs.y,
        }
    }
}

impl Mul<f64> for Point {
    type Output = Point;
    #[inline]
    fn mul(self, rhs: f64) -> Point {
        Point {
            x: self.x * rhs,
            y: self.y * rhs,
        }
    }
}

impl Mul<Point> for f64 {
    type Output = Point;
    #[inline]
    fn mul(self, rhs: Point) -> Point {
        rhs * self
    }
}

impl Div<f64> for Point {
    type Output = Point;
    #[inline]
    fn div(self, rhs: f64) -> Point {
        Point {
            x: self.x / rhs,
            y: self.y / rhs,
        }
    }
}

impl Neg for Point {
    type Output = Point;
    #[inline]
    fn neg(self) -> Point {
        Point {
            x: -self.x,
            y: -self.y,
        }
    }
}

impl Index<Axis> for Point {
    type Output = f64;
    #[inline]
    fn index(&self, axis: Axis) -> &f64 {
        match axis {
            Axis::X => &self.x,
            Axis::Y => &self.y,
        }
    }
}

impl From<(f64, f64)> for Point {
    fn from((x, y): (f64, f64)) -> Self {
        Point { x, y }
    }
}

impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "({}, {})", self.x, self.y)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn is_send_sync<T: Sized + Send + Sync + Unpin>() {}

    #[test]
    fn point_is_send_sync() {
        is_send_sync::<Point>();
    }

    fn approx_eq(a: f64, b: f64) -> bool {
        (a - b).abs() < 1e-14
    }

    fn points_approx_eq(a: Point, b: Point) -> bool {
        approx_eq(a.x, b.x) && approx_eq(a.y, b.y)
    }

    #[test]
    fn test_ortho() {
        let cases = [
            (Point::new(0.0, 0.0), Point::new(0.0, 0.0)),
            (Point::new(0.0, 1.0), Point::new(-1.0, 0.0)),
            (Point::new(1.0, 1.0), Point::new(-1.0, 1.0)),
            (Point::new(-4.0, 7.0), Point::new(-7.0, -4.0)),
        ];
        for (p, want) in &cases {
            assert!(
                points_approx_eq(p.ortho(), *want),
                "{p}.ortho() = {:?}, want {want:?}",
                p.ortho()
            );
        }
    }

    #[test]
    fn test_dot() {
        assert!(approx_eq(
            Point::new(0.0, 0.0).dot(Point::new(0.0, 0.0)),
            0.0
        ));
        assert!(approx_eq(
            Point::new(1.0, 1.0).dot(Point::new(4.0, 3.0)),
            7.0
        ));
        assert!(approx_eq(
            Point::new(-4.0, 7.0).dot(Point::new(1.0, 5.0)),
            31.0
        ));
    }

    #[test]
    fn test_cross() {
        assert!(approx_eq(
            Point::new(1.0, 1.0).cross(Point::new(-1.0, -1.0)),
            0.0
        ));
        assert!(approx_eq(
            Point::new(1.0, 1.0).cross(Point::new(4.0, 3.0)),
            -1.0
        ));
        assert!(approx_eq(
            Point::new(1.0, 5.0).cross(Point::new(-2.0, 3.0)),
            13.0
        ));
    }

    #[test]
    fn test_norm() {
        assert!(approx_eq(Point::new(0.0, 0.0).norm(), 0.0));
        assert!(approx_eq(Point::new(0.0, 1.0).norm(), 1.0));
        assert!(approx_eq(Point::new(3.0, 4.0).norm(), 5.0));
        assert!(approx_eq(Point::new(3.0, -4.0).norm(), 5.0));
        assert!(approx_eq(Point::new(2.0, 2.0).norm(), 2.0 * f64::sqrt(2.0)));
    }

    #[test]
    fn test_normalize() {
        assert_eq!(Point::new(0.0, 0.0).normalize(), Point::new(0.0, 0.0));
        assert!(points_approx_eq(
            Point::new(3.0, 4.0).normalize(),
            Point::new(0.6, 0.8)
        ));
        assert!(points_approx_eq(
            Point::new(3.0, -4.0).normalize(),
            Point::new(0.6, -0.8)
        ));
    }

    #[test]
    fn test_arithmetic() {
        let a = Point::new(1.0, 2.0);
        let b = Point::new(3.0, 4.0);
        assert_eq!(a + b, Point::new(4.0, 6.0));
        assert_eq!(a - b, Point::new(-2.0, -2.0));
        assert_eq!(a * 3.0, Point::new(3.0, 6.0));
        assert_eq!(3.0 * a, Point::new(3.0, 6.0));
        assert_eq!(a / 2.0, Point::new(0.5, 1.0));
        assert_eq!(-a, Point::new(-1.0, -2.0));
    }

    #[test]
    fn test_index() {
        let p = Point::new(1.0, 2.0);
        assert_eq!(p[Axis::X], 1.0);
        assert_eq!(p[Axis::Y], 2.0);
    }
}

#[cfg(test)]
mod quickcheck_tests {
    use super::*;
    use quickcheck_macros::quickcheck;

    fn clamp_finite(v: f64) -> f64 {
        if v.is_finite() {
            v.clamp(-1e10, 1e10)
        } else {
            0.0
        }
    }

    fn pt(x: f64, y: f64) -> Point {
        Point::new(clamp_finite(x), clamp_finite(y))
    }

    #[quickcheck]
    fn prop_dot_commutative(ax: f64, ay: f64, bx: f64, by: f64) -> bool {
        let a = pt(ax, ay);
        let b = pt(bx, by);
        (a.dot(b) - b.dot(a)).abs() < 1e-10
    }

    #[quickcheck]
    fn prop_ortho_is_orthogonal(x: f64, y: f64) -> bool {
        let p = pt(x, y);
        p.dot(p.ortho()).abs() < 1e-10
    }

    #[quickcheck]
    fn prop_normalize_unit(x: f64, y: f64) -> bool {
        let p = pt(x, y);
        let n = p.normalize();
        if p.norm2() == 0.0 {
            n == Point::default()
        } else {
            (n.norm() - 1.0).abs() < 1e-14
        }
    }

    #[quickcheck]
    fn prop_add_commutative(ax: f64, ay: f64, bx: f64, by: f64) -> bool {
        let a = pt(ax, ay);
        let b = pt(bx, by);
        (a + b) == (b + a)
    }

    #[quickcheck]
    fn prop_cross_antisymmetric(ax: f64, ay: f64, bx: f64, by: f64) -> bool {
        let a = pt(ax, ay);
        let b = pt(bx, by);
        let tol = 1e-6 * a.norm() * b.norm();
        (a.cross(b) + b.cross(a)).abs() <= tol + 1e-30
    }

    #[quickcheck]
    fn prop_norm2_equals_dot_self(x: f64, y: f64) -> bool {
        let p = pt(x, y);
        (p.norm2() - p.dot(p)).abs() < 1e-10
    }

    #[cfg(feature = "serde")]
    #[quickcheck]
    fn prop_serde_roundtrip(x: i32, y: i32) -> bool {
        let p = Point::new(f64::from(x), f64::from(y));
        let json = serde_json::to_string(&p).unwrap();
        let back: Point = serde_json::from_str(&json).unwrap();
        back == p
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_serde_axis_roundtrip() {
        for a in [Axis::X, Axis::Y] {
            let json = serde_json::to_string(&a).unwrap();
            let back: Axis = serde_json::from_str(&json).unwrap();
            assert_eq!(a, back);
        }
    }
}