Skip to main content

knipsa/
lib.rs

1#![doc = include_str!("lib.md")]
2#![forbid(unsafe_code)]
3#![deny(missing_docs)]
4#![doc(test(attr(deny(warnings))))]
5
6mod boolean;
7mod complexity;
8mod dispatch;
9mod error;
10mod fast;
11mod fast_dispatch;
12#[cfg(feature = "geo-types")]
13pub mod geo_types;
14mod geometry;
15mod offset;
16mod request;
17mod standard_dispatch;
18mod topology;
19mod triangulation;
20
21pub use complexity::{ComplexityLimits, ComplexityResource};
22pub use error::{Error, PathValidationError};
23pub use geometry::{
24    Orientation, Path64, PathD, Paths64, PathsD, Point64, PointD, PointLocation, Rect64, RectD,
25    clip_to_rect_d, clip_to_rect64, normalize_path_d, normalize_path64, orientation,
26    point_in_polygon, reverse_path_d, reverse_path64, signed_area2, simplify_paths_d,
27    simplify_paths64, translate_path_d, translate_path64, trim_collinear_d, trim_collinear64,
28    validate_path_d, validate_path64, validate_paths_d, validate_paths_d_located, validate_paths64,
29    validate_paths64_located,
30};
31pub use offset::{
32    EndType, JoinType, OffsetOptions, offset_path_d, offset_path64, offset_paths_d, offset_paths64,
33};
34pub use request::{
35    BooleanOutput, BooleanRequest, ClipType, FillRule, boolean_op, boolean_op_d, difference,
36    difference_d, difference_path, difference_path_d, intersection, intersection_d,
37    intersection_path, intersection_path_d, union, union_d, union_path, union_path_d, xor, xor_d,
38    xor_path, xor_path_d,
39};
40pub use topology::{Polygon64, PolygonD, build_polygons_d, build_polygons64};
41pub use triangulation::{
42    Triangle64, TriangleD, triangulate_d, triangulate_path_d, triangulate_path64, triangulate64,
43};
44
45/// Describes whether a path's final point connects back to its first point.
46///
47/// Polygon operations use [`PathKind::Closed`]. Offset operations use
48/// [`PathKind::Open`] for stroked polylines and [`PathKind::Closed`] for
49/// filled polygons. A repeated closing point is accepted and removed by the
50/// normalization helpers; it is not required by the API.
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
53#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
54pub enum PathKind {
55    /// A path whose edges wrap from the final point to the first.
56    Closed,
57    /// A path whose final point is not connected back to its first.
58    Open,
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn public_contract_is_constructible() {
67        assert_eq!(PathKind::Closed, PathKind::Closed);
68        let request = BooleanRequest {
69            limits: crate::ComplexityLimits::DEFAULT,
70            open_subjects: &[],
71            closed_subjects: &[],
72            clips: &[],
73            clip_type: ClipType::Xor,
74            fill_rule: FillRule::Positive,
75        };
76        assert!(boolean_op(request).is_ok());
77    }
78
79    #[test]
80    fn errors_are_displayable() {
81        let errors = [
82            Error::InvalidPath { kind: PathKind::Closed, minimum_vertices: 3, actual_vertices: 2 },
83            Error::NonFiniteCoordinate { point_index: 4 },
84            Error::ArithmeticOverflow,
85            Error::NonIntegralResult,
86            Error::TopologyFailure,
87            Error::InvalidOffset,
88            Error::TriangulationFailure,
89            Error::IntersectingPaths,
90            Error::LimitExceeded { resource: ComplexityResource::Vertices, limit: 4, required: 5 },
91        ];
92        for error in errors {
93            assert!(!error.to_string().is_empty());
94        }
95    }
96}
97
98#[cfg(all(test, feature = "serde"))]
99mod serde_tests {
100    use super::*;
101    use serde::{Serialize, de::DeserializeOwned};
102
103    fn round_trip<T>(value: &T) -> T
104    where
105        T: Serialize + DeserializeOwned,
106    {
107        serde_json::from_str(&serde_json::to_string(value).unwrap()).unwrap()
108    }
109
110    #[test]
111    fn public_value_types_round_trip_through_serde() {
112        let path = vec![PointD::new(1.25, -2.5), PointD::new(3.75, 4.5)];
113        assert_eq!(round_trip(&path), path);
114        assert_eq!(round_trip(&Point64::new(i64::MIN, i64::MAX)), Point64::new(i64::MIN, i64::MAX));
115        assert_eq!(round_trip(&Rect64::new(5, 6, 1, 2)), Rect64::new(5, 6, 1, 2));
116        assert_eq!(round_trip(&RectD::new(5.0, 6.0, 1.0, 2.0)), RectD::new(5.0, 6.0, 1.0, 2.0));
117        assert_eq!(round_trip(&Orientation::CounterClockwise), Orientation::CounterClockwise);
118        assert_eq!(round_trip(&PointLocation::Boundary), PointLocation::Boundary);
119        assert_eq!(round_trip(&PathKind::Open), PathKind::Open);
120        assert_eq!(round_trip(&ClipType::Difference), ClipType::Difference);
121        assert_eq!(round_trip(&FillRule::Negative), FillRule::Negative);
122        assert_eq!(round_trip(&JoinType::Miter), JoinType::Miter);
123        assert_eq!(round_trip(&EndType::Round), EndType::Round);
124        assert_eq!(round_trip(&OffsetOptions::default()), OffsetOptions::default());
125        assert_eq!(round_trip(&ComplexityLimits::DEFAULT), ComplexityLimits::DEFAULT);
126        let polygon = PolygonD {
127            outer: vec![PointD::new(0.0, 0.0), PointD::new(4.0, 0.0), PointD::new(0.0, 4.0)],
128            holes: Vec::new(),
129        };
130        assert_eq!(round_trip(&polygon), polygon);
131        let polygon64 = Polygon64 {
132            outer: vec![Point64::new(0, 0), Point64::new(4, 0), Point64::new(0, 4)],
133            holes: Vec::new(),
134        };
135        assert_eq!(round_trip(&polygon64), polygon64);
136        let boolean_output = BooleanOutput {
137            closed: vec![vec![Point64::new(0, 0), Point64::new(1, 0), Point64::new(0, 1)]],
138            open: vec![vec![Point64::new(0, 0), Point64::new(1, 1)]],
139        };
140        assert_eq!(round_trip(&boolean_output), boolean_output);
141
142        let limit_error =
143            Error::LimitExceeded { resource: ComplexityResource::Vertices, limit: 4, required: 5 };
144        assert_eq!(round_trip(&limit_error), limit_error);
145        assert_eq!(round_trip(&Error::TopologyFailure), Error::TopologyFailure);
146
147        let located = validate_paths_d_located(
148            &[vec![PointD::new(0.0, 0.0), PointD::new(f64::NAN, 0.0)]],
149            PathKind::Open,
150        )
151        .unwrap_err();
152        assert_eq!(round_trip(&located), located);
153    }
154
155    #[test]
156    fn public_enum_wire_names_are_snake_case() {
157        assert_eq!(
158            serde_json::to_string(&Orientation::CounterClockwise).unwrap(),
159            "\"counter_clockwise\""
160        );
161        assert_eq!(serde_json::to_string(&FillRule::EvenOdd).unwrap(), "\"even_odd\"");
162        assert_eq!(
163            serde_json::to_string(&ComplexityResource::EdgePairs).unwrap(),
164            "\"edge_pairs\""
165        );
166    }
167}