s2rst 0.3.2

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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
// 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
//   - Go:   golang/geo
//   - Java: google/s2-geometry-library-java

//! The [`Shape`] trait and supporting types for representing geometry in an
//! [`ShapeIndex`](super::shape_index).
//!
//! All geometry is represented as a collection of edges that optionally
//! define an interior. An `S2Shape` can represent a set of points, a set
//! of polylines, or a set of polygons — but all edges must have the same
//! *dimension* (0, 1, or 2).
//!
//! Corresponds to C++ `s2shape.h`, Go `s2/shape.go`.

use crate::s2::Point;

// ─── Dimension ──────────────────────────────────────────────────────────

/// The geometric dimension of a shape.
///
/// Every [`Shape`] has a fixed dimension that determines the type of
/// geometry it represents:
///
/// - [`Point`](Dimension::Point) (0): a collection of points.
/// - [`Polyline`](Dimension::Polyline) (1): a collection of open polylines.
/// - [`Polygon`](Dimension::Polygon) (2): a collection of closed polygons
///   with interior.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(u8)]
pub enum Dimension {
    /// Point geometry (0-dimensional).
    Point = 0,
    /// Polyline geometry (1-dimensional).
    Polyline = 1,
    /// Polygon geometry (2-dimensional).
    Polygon = 2,
}

impl Dimension {
    /// Returns the dimension as a `usize`, suitable for use as an array index.
    pub const fn as_usize(self) -> usize {
        self as usize
    }
}

impl std::fmt::Display for Dimension {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Dimension::Point => write!(f, "0"),
            Dimension::Polyline => write!(f, "1"),
            Dimension::Polygon => write!(f, "2"),
        }
    }
}

impl From<Dimension> for u8 {
    fn from(d: Dimension) -> u8 {
        d as u8
    }
}

impl From<Dimension> for i8 {
    fn from(d: Dimension) -> i8 {
        d as i8
    }
}

impl From<Dimension> for i32 {
    fn from(d: Dimension) -> i32 {
        d as i32
    }
}

impl From<Dimension> for usize {
    fn from(d: Dimension) -> usize {
        d as usize
    }
}

impl TryFrom<u8> for Dimension {
    type Error = &'static str;
    fn try_from(v: u8) -> Result<Self, Self::Error> {
        match v {
            0 => Ok(Dimension::Point),
            1 => Ok(Dimension::Polyline),
            2 => Ok(Dimension::Polygon),
            _ => Err("dimension must be 0, 1, or 2"),
        }
    }
}

impl TryFrom<i8> for Dimension {
    type Error = &'static str;
    fn try_from(v: i8) -> Result<Self, Self::Error> {
        match v {
            0 => Ok(Dimension::Point),
            1 => Ok(Dimension::Polyline),
            2 => Ok(Dimension::Polygon),
            _ => Err("dimension must be 0, 1, or 2"),
        }
    }
}

impl TryFrom<i32> for Dimension {
    type Error = &'static str;
    fn try_from(v: i32) -> Result<Self, Self::Error> {
        match v {
            0 => Ok(Dimension::Point),
            1 => Ok(Dimension::Polyline),
            2 => Ok(Dimension::Polygon),
            _ => Err("dimension must be 0, 1, or 2"),
        }
    }
}

// ─── Supporting types ───────────────────────────────────────────────────

/// A geodesic edge between two points on the sphere.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Edge {
    /// The first vertex of the edge.
    pub v0: Point,
    /// The second vertex of the edge.
    pub v1: Point,
}

impl Edge {
    /// Creates a new edge from two points.
    pub fn new(v0: Point, v1: Point) -> Self {
        Edge { v0, v1 }
    }

    /// Returns the reversed edge (v1 → v0).
    pub fn reversed(self) -> Edge {
        Edge {
            v0: self.v1,
            v1: self.v0,
        }
    }

    /// Reports whether this edge is degenerate (v0 == v1).
    pub fn is_degenerate(self) -> bool {
        self.v0 == self.v1
    }

    /// Lexicographic comparison: first by v0, then by v1.
    #[expect(
        clippy::should_implement_trait,
        reason = "named constructor avoids ambiguity with std traits"
    )]
    pub fn cmp(&self, other: &Edge) -> std::cmp::Ordering {
        let c = self.v0.cmp_point(other.v0);
        if c != std::cmp::Ordering::Equal {
            return c;
        }
        self.v1.cmp_point(other.v1)
    }
}

// ─── ShapeId ────────────────────────────────────────────────────────────

/// Index of a shape within a [`ShapeIndex`](super::shape_index::ShapeIndex).
///
/// Wraps an `i32`. Negative values (typically `-1`) serve as sentinel
/// "no shape" markers — prefer using `Option<ShapeId>` at API boundaries
/// where possible.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ShapeId(pub i32);

impl ShapeId {
    /// Creates a new `ShapeId`.
    pub const fn new(v: i32) -> Self {
        ShapeId(v)
    }

    /// Returns the raw `i32` value.
    pub const fn as_i32(self) -> i32 {
        self.0
    }

    /// Returns the value as a `usize` for array indexing.
    ///
    /// # Panics
    ///
    /// Panics if the value is negative.
    #[expect(clippy::cast_sign_loss, reason = "guarded by assert")]
    pub const fn as_usize(self) -> usize {
        assert!(self.0 >= 0, "ShapeId must be non-negative for indexing");
        self.0 as usize
    }
}

impl std::ops::Add<i32> for ShapeId {
    type Output = ShapeId;
    fn add(self, rhs: i32) -> ShapeId {
        ShapeId(self.0 + rhs)
    }
}

impl std::ops::Sub<i32> for ShapeId {
    type Output = ShapeId;
    fn sub(self, rhs: i32) -> ShapeId {
        ShapeId(self.0 - rhs)
    }
}

impl std::ops::AddAssign<i32> for ShapeId {
    fn add_assign(&mut self, rhs: i32) {
        self.0 += rhs;
    }
}

impl PartialEq<i32> for ShapeId {
    fn eq(&self, other: &i32) -> bool {
        self.0 == *other
    }
}

impl PartialOrd<i32> for ShapeId {
    fn partial_cmp(&self, other: &i32) -> Option<std::cmp::Ordering> {
        self.0.partial_cmp(other)
    }
}

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

impl From<i32> for ShapeId {
    fn from(v: i32) -> Self {
        ShapeId(v)
    }
}

impl From<ShapeId> for i32 {
    fn from(id: ShapeId) -> i32 {
        id.0
    }
}

// ─── ShapeEdgeId ────────────────────────────────────────────────────────

/// A unique identifier for an edge within a [`ShapeIndex`](super::shape_index::ShapeIndex).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ShapeEdgeId {
    /// The shape's index within the `ShapeIndex`.
    pub shape_id: ShapeId,
    /// The edge's index within the shape.
    pub edge_id: i32,
}

impl ShapeEdgeId {
    /// Creates a new `ShapeEdgeId`.
    pub fn new(shape_id: impl Into<ShapeId>, edge_id: i32) -> Self {
        ShapeEdgeId {
            shape_id: shape_id.into(),
            edge_id,
        }
    }
}

impl std::fmt::Display for ShapeEdgeId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:{}", self.shape_id, self.edge_id)
    }
}

/// Combines a [`ShapeEdgeId`] with its corresponding [`Edge`].
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ShapeEdge {
    /// The shape and edge identifiers.
    pub id: ShapeEdgeId,
    /// The edge geometry.
    pub edge: Edge,
}

impl ShapeEdge {
    /// Creates a new `ShapeEdge`.
    pub fn new(id: ShapeEdgeId, edge: Edge) -> Self {
        ShapeEdge { id, edge }
    }
}

/// A contiguous range of edge IDs within a shape.
///
/// Edges within a chain are connected: the `v1` of edge *i* equals the
/// `v0` of edge *i+1*. For dimension-2 shapes (polygons), chains form
/// closed loops; for dimension-1 shapes (polylines), they form open paths.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Chain {
    /// The first edge ID in this chain.
    pub start: usize,
    /// The number of edges in this chain.
    pub length: usize,
}

impl Chain {
    /// Creates a new chain.
    pub fn new(start: usize, length: usize) -> Self {
        Chain { start, length }
    }
}

/// The position of an edge within a particular chain.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ChainPosition {
    /// The index of the chain containing this edge.
    pub chain_id: usize,
    /// The offset of the edge within the chain.
    pub offset: usize,
}

impl ChainPosition {
    /// Creates a new `ChainPosition`.
    pub fn new(chain_id: usize, offset: usize) -> Self {
        ChainPosition { chain_id, offset }
    }
}

/// An arbitrary reference point with a boolean indicating whether the
/// shape's interior contains the point.
///
/// For shapes that have an interior (dimension 2), `contained` reports
/// whether `point` is inside the shape. For other shapes, `contained`
/// is false.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ReferencePoint {
    /// The reference point.
    pub point: Point,
    /// Whether the shape's interior contains the reference point.
    pub contained: bool,
}

impl ReferencePoint {
    /// Creates a new `ReferencePoint`.
    pub fn new(point: Point, contained: bool) -> Self {
        ReferencePoint { point, contained }
    }
}

impl Default for ReferencePoint {
    fn default() -> Self {
        ReferencePoint {
            point: Point::origin(),
            contained: false,
        }
    }
}

// ─── Shape trait ────────────────────────────────────────────────────────

/// The fundamental abstraction for geometry in the S2 library.
///
/// All geometry is represented as a collection of edges. Edges are
/// organized into chains — connected sequences where the endpoint of
/// one edge is the start of the next.
///
/// The *dimension* determines the type of geometry:
/// - **0**: A set of points (each edge is degenerate: v0 == v1).
/// - **1**: A set of polylines (open paths).
/// - **2**: A set of polygons (closed loops with interior).
///
/// Shapes are immutable once added to a [`ShapeIndex`](super::shape_index::ShapeIndex). The trait
/// requires `Send + Sync` for safe sharing across threads.
pub trait Shape: Send + Sync + std::fmt::Debug {
    /// Returns the number of edges in this shape.
    fn num_edges(&self) -> usize;

    /// Returns the edge with the given index.
    fn edge(&self, id: usize) -> Edge;

    /// Returns an arbitrary reference point and whether it is contained
    /// by the shape's interior. Only meaningful for dimension-2 shapes.
    fn reference_point(&self) -> ReferencePoint;

    /// Returns the number of edge chains.
    fn num_chains(&self) -> usize;

    /// Returns the chain with the given index.
    fn chain(&self, chain_id: usize) -> Chain;

    /// Returns the edge at the given offset within the specified chain.
    fn chain_edge(&self, chain_id: usize, offset: usize) -> Edge;

    /// Returns the chain and offset for the given edge ID.
    fn chain_position(&self, edge_id: usize) -> ChainPosition;

    /// Returns the dimension of this shape's geometry.
    fn dimension(&self) -> Dimension;

    /// Reports whether this shape contains no geometry.
    fn is_empty(&self) -> bool {
        self.num_edges() == 0 && (self.dimension() < Dimension::Polygon || self.num_chains() == 0)
    }

    /// Reports whether this shape contains the entire sphere.
    /// Only possible for dimension-2 shapes.
    fn is_full(&self) -> bool {
        !self.is_empty()
            && self.dimension() == Dimension::Polygon
            && self.reference_point().contained
    }

    /// Reports whether this shape has an interior (dimension == 2).
    fn has_interior(&self) -> bool {
        self.dimension() == Dimension::Polygon
    }

    /// Returns the type tag for this shape type, used for serialization.
    ///
    /// Returns 0 (`kNoTypeTag`) if this shape type does not support encoding.
    /// Standard type tags match C++:
    /// - 1 = `Polygon::Shape`
    /// - 2 = `Polyline::Shape`
    /// - 3 = `PointVector`
    /// - 4 = `LaxPolyline`
    /// - 5 = `LaxPolygon`
    fn type_tag(&self) -> u32 {
        0
    }

    /// Encodes this shape's data (without the type tag) to the writer.
    ///
    /// The `hint` controls the trade-off between encoding speed and size.
    ///
    /// # Errors
    ///
    /// Returns an error if this shape type does not support encoding, or
    /// if the write fails.
    fn encode_tagged(
        &self,
        _w: &mut dyn std::io::Write,
        _hint: super::encoded_s2point_vector::CodingHint,
    ) -> std::io::Result<()> {
        Err(std::io::Error::new(
            std::io::ErrorKind::Unsupported,
            "this shape type does not support encoding",
        ))
    }
}

// ─── Utilities ──────────────────────────────────────────────────────────

/// Computes a [`ReferencePoint`] for a dimension-2 shape by finding an
/// unbalanced vertex and using [`ContainsVertexQuery`](super::contains_vertex_query::ContainsVertexQuery) to determine
/// containment.
///
/// A "matched" edge is one that can be paired with a corresponding reversed
/// edge. A "balanced" vertex is one where all edges are matched. This
/// function finds an unbalanced vertex to determine containment.
///
/// This is the Rust equivalent of Go's `referencePointForShape`.
pub fn reference_point_for_shape(shape: &dyn Shape) -> ReferencePoint {
    if shape.num_edges() == 0 {
        // A shape with no edges is full if and only if it contains at
        // least one chain (i.e., an empty loop).
        return ReferencePoint::new(Point::origin(), shape.num_chains() > 0);
    }

    // Try the first edge's starting vertex.
    let edge = shape.edge(0);
    if let Some(rp) = reference_point_at_vertex(shape, edge.v0) {
        return rp;
    }

    // Gather all edges and their reverses, then sort to find unmatched edges.
    let n = shape.num_edges();
    let mut edges: Vec<Edge> = (0..n).map(|i| shape.edge(i)).collect();
    let mut rev_edges: Vec<Edge> = edges.iter().map(|e| e.reversed()).collect();

    edges.sort_by(Edge::cmp);
    rev_edges.sort_by(Edge::cmp);

    for i in 0..n {
        if edges[i].cmp(&rev_edges[i]) == std::cmp::Ordering::Less
            && let Some(rp) = reference_point_at_vertex(shape, edges[i].v0)
        {
            return rp;
        }
        if rev_edges[i].cmp(&edges[i]) == std::cmp::Ordering::Less
            && let Some(rp) = reference_point_at_vertex(shape, rev_edges[i].v0)
        {
            return rp;
        }
    }

    // All vertices are balanced. The shape is full if it contains any
    // chain with no edges (an empty loop).
    for i in 0..shape.num_chains() {
        if shape.chain(i).length == 0 {
            return ReferencePoint::new(Point::origin(), true);
        }
    }

    ReferencePoint::new(Point::origin(), false)
}

/// Tests whether `v_test` is an unbalanced vertex and computes containment.
/// Returns `None` if the vertex is balanced (all edges are matched).
fn reference_point_at_vertex(shape: &dyn Shape, v_test: Point) -> Option<ReferencePoint> {
    use crate::s2::contains_vertex_query::ContainsVertexQuery;

    let mut query = ContainsVertexQuery::new(v_test);
    let n = shape.num_edges();
    for i in 0..n {
        let edge = shape.edge(i);
        if edge.v0 == v_test {
            query.add_edge(edge.v1, 1);
        }
        if edge.v1 == v_test {
            query.add_edge(edge.v0, -1);
        }
    }
    let sign = query.contains_vertex();
    if sign == 0 {
        return None; // vertex is balanced
    }
    Some(ReferencePoint::new(v_test, sign > 0))
}

// ─── Tests ──────────────────────────────────────────────────────────────

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

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

    #[test]
    fn edge_is_send_sync() {
        is_send_sync::<Edge>();
    }

    #[test]
    fn shape_edge_id_is_send_sync() {
        is_send_sync::<ShapeEdgeId>();
    }

    #[test]
    fn chain_is_send_sync() {
        is_send_sync::<Chain>();
    }

    #[test]
    fn chain_position_is_send_sync() {
        is_send_sync::<ChainPosition>();
    }

    #[test]
    fn reference_point_is_send_sync() {
        is_send_sync::<ReferencePoint>();
    }

    #[test]
    fn test_edge_reversed() {
        let a = Point(Vector {
            x: 1.0,
            y: 0.0,
            z: 0.0,
        });
        let b = Point(Vector {
            x: 0.0,
            y: 1.0,
            z: 0.0,
        });
        let e = Edge::new(a, b);
        let r = e.reversed();
        assert_eq!(r.v0, b);
        assert_eq!(r.v1, a);
    }

    #[test]
    fn test_edge_is_degenerate() {
        let a = Point(Vector {
            x: 1.0,
            y: 0.0,
            z: 0.0,
        });
        let b = Point(Vector {
            x: 0.0,
            y: 1.0,
            z: 0.0,
        });
        assert!(!Edge::new(a, b).is_degenerate());
        assert!(Edge::new(a, a).is_degenerate());
    }

    #[test]
    fn test_shape_edge_id_display() {
        let id = ShapeEdgeId::new(3, 7);
        assert_eq!(format!("{id}"), "3:7");
    }

    #[test]
    fn test_shape_edge_id_ordering() {
        let a = ShapeEdgeId::new(1, 5);
        let b = ShapeEdgeId::new(1, 6);
        let c = ShapeEdgeId::new(2, 0);
        assert!(a < b);
        assert!(b < c);
    }

    #[test]
    fn test_chain_new() {
        let c = Chain::new(10, 5);
        assert_eq!(c.start, 10);
        assert_eq!(c.length, 5);
    }

    #[test]
    fn test_chain_position_new() {
        let cp = ChainPosition::new(2, 3);
        assert_eq!(cp.chain_id, 2);
        assert_eq!(cp.offset, 3);
    }

    #[test]
    fn test_reference_point_default() {
        let rp = ReferencePoint::default();
        assert!(!rp.contained);
    }

    /// A trivial point-vector shape for testing the trait.
    #[derive(Debug)]
    struct TestShape {
        points: Vec<Point>,
    }

    impl Shape for TestShape {
        fn num_edges(&self) -> usize {
            self.points.len()
        }
        fn edge(&self, id: usize) -> Edge {
            Edge::new(self.points[id], self.points[id])
        }
        fn reference_point(&self) -> ReferencePoint {
            ReferencePoint::default()
        }
        fn num_chains(&self) -> usize {
            self.points.len()
        }
        fn chain(&self, chain_id: usize) -> Chain {
            Chain::new(chain_id, 1)
        }
        fn chain_edge(&self, chain_id: usize, _offset: usize) -> Edge {
            self.edge(chain_id)
        }
        fn chain_position(&self, edge_id: usize) -> ChainPosition {
            ChainPosition::new(edge_id, 0)
        }
        fn dimension(&self) -> Dimension {
            Dimension::Point
        }
    }

    #[test]
    fn test_shape_trait() {
        let shape = TestShape {
            points: vec![
                Point(Vector {
                    x: 1.0,
                    y: 0.0,
                    z: 0.0,
                }),
                Point(Vector {
                    x: 0.0,
                    y: 1.0,
                    z: 0.0,
                }),
            ],
        };
        assert_eq!(shape.num_edges(), 2);
        assert_eq!(shape.dimension(), Dimension::Point);
        assert!(!shape.is_empty());
        assert!(!shape.is_full());
        assert!(!shape.has_interior());
    }

    #[test]
    fn test_shape_empty() {
        let shape = TestShape { points: vec![] };
        assert!(shape.is_empty());
        assert!(!shape.is_full());
    }

    #[test]
    fn test_dyn_shape_is_object_safe() {
        let shape: Box<dyn Shape> = Box::new(TestShape {
            points: vec![Point(Vector {
                x: 1.0,
                y: 0.0,
                z: 0.0,
            })],
        });
        assert_eq!(shape.num_edges(), 1);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_serde_roundtrip() {
        let p0 = Point::from_coords(1.0, 0.0, 0.0);
        let p1 = Point::from_coords(0.0, 1.0, 0.0);

        let edge = Edge::new(p0, p1);
        let json = serde_json::to_string(&edge).unwrap();
        let back: Edge = serde_json::from_str(&json).unwrap();
        assert_eq!(edge, back);

        let seid = ShapeEdgeId::new(3, 7);
        let json = serde_json::to_string(&seid).unwrap();
        let back: ShapeEdgeId = serde_json::from_str(&json).unwrap();
        assert_eq!(seid, back);

        let se = ShapeEdge::new(seid, edge);
        let json = serde_json::to_string(&se).unwrap();
        let back: ShapeEdge = serde_json::from_str(&json).unwrap();
        assert_eq!(se, back);

        let chain = Chain {
            start: 0,
            length: 5,
        };
        let json = serde_json::to_string(&chain).unwrap();
        let back: Chain = serde_json::from_str(&json).unwrap();
        assert_eq!(chain, back);

        let cp = ChainPosition::new(2, 3);
        let json = serde_json::to_string(&cp).unwrap();
        let back: ChainPosition = serde_json::from_str(&json).unwrap();
        assert_eq!(cp, back);

        let rp = ReferencePoint::new(p0, true);
        let json = serde_json::to_string(&rp).unwrap();
        let back: ReferencePoint = serde_json::from_str(&json).unwrap();
        assert_eq!(rp, back);
    }
}

#[cfg(test)]
#[path = "shape_tests.rs"]
mod shape_tests;