Skip to main content

knipsa_ffi/
lib.rs

1#![doc = include_str!("lib.md")]
2#![deny(unsafe_op_in_unsafe_fn)]
3#![deny(missing_docs)]
4#![doc(test(attr(deny(warnings))))]
5
6use std::{
7    ffi::c_char,
8    panic::{AssertUnwindSafe, catch_unwind},
9    ptr, slice,
10};
11
12#[cfg(test)]
13use std::cell::Cell;
14
15use knipsa::{
16    BooleanRequest, ClipType, ComplexityLimits, EndType, Error, FillRule, JoinType, OffsetOptions,
17    Path64, PathD, PathKind, Point64, PointD, PointLocation, Rect64, RectD, boolean_op,
18    boolean_op_d, clip_to_rect_d, clip_to_rect64, offset_paths_d, point_in_polygon,
19    simplify_paths_d, simplify_paths64, triangulate_d, triangulate64, validate_paths_d,
20    validate_paths64,
21};
22
23/// A fixed-layout integer point for FFI callers.
24#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
25#[repr(C)]
26pub struct KnipsaPoint64 {
27    /// Horizontal coordinate.
28    pub x: i64,
29    /// Vertical coordinate.
30    pub y: i64,
31}
32
33impl From<KnipsaPoint64> for Point64 {
34    fn from(point: KnipsaPoint64) -> Self {
35        Self::new(point.x, point.y)
36    }
37}
38
39/// A fixed-layout floating-point point for FFI callers.
40#[derive(Clone, Copy, Debug, Default, PartialEq)]
41#[repr(C)]
42pub struct KnipsaPointD {
43    /// Horizontal coordinate.
44    pub x: f64,
45    /// Vertical coordinate.
46    pub y: f64,
47}
48
49impl From<KnipsaPointD> for PointD {
50    fn from(point: KnipsaPointD) -> Self {
51        Self::new(point.x, point.y)
52    }
53}
54
55/// An axis-aligned integer clipping rectangle.
56#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
57#[repr(C)]
58pub struct KnipsaRect64 {
59    /// Lower horizontal bound.
60    pub min_x: i64,
61    /// Lower vertical bound.
62    pub min_y: i64,
63    /// Upper horizontal bound.
64    pub max_x: i64,
65    /// Upper vertical bound.
66    pub max_y: i64,
67}
68
69impl From<KnipsaRect64> for Rect64 {
70    fn from(rectangle: KnipsaRect64) -> Self {
71        Self::new(rectangle.min_x, rectangle.min_y, rectangle.max_x, rectangle.max_y)
72    }
73}
74
75/// An axis-aligned floating-point clipping rectangle.
76#[derive(Clone, Copy, Debug, Default, PartialEq)]
77#[repr(C)]
78pub struct KnipsaRectD {
79    /// Lower horizontal bound.
80    pub min_x: f64,
81    /// Lower vertical bound.
82    pub min_y: f64,
83    /// Upper horizontal bound.
84    pub max_x: f64,
85    /// Upper vertical bound.
86    pub max_y: f64,
87}
88
89impl From<KnipsaRectD> for RectD {
90    fn from(rectangle: KnipsaRectD) -> Self {
91        Self::new(rectangle.min_x, rectangle.min_y, rectangle.max_x, rectangle.max_y)
92    }
93}
94
95/// A borrowed integer point slice.
96///
97/// A null `points` pointer is valid only when `point_count` is zero. The
98/// pointer must remain readable for the duration of the call that receives
99/// this descriptor; ownership stays with the caller.
100#[derive(Clone, Copy, Debug)]
101#[repr(C)]
102pub struct KnipsaPath64 {
103    /// Pointer to the first point.
104    pub points: *const KnipsaPoint64,
105    /// Number of points at `points`.
106    pub point_count: usize,
107}
108
109/// A borrowed floating-point point slice.
110///
111/// A null `points` pointer is valid only when `point_count` is zero. The
112/// pointer must remain readable for the duration of the call that receives
113/// this descriptor; ownership stays with the caller.
114#[derive(Clone, Copy, Debug)]
115#[repr(C)]
116pub struct KnipsaPathD {
117    /// Pointer to the first point.
118    pub points: *const KnipsaPointD,
119    /// Number of points at `points`.
120    pub point_count: usize,
121}
122
123/// An owned integer result returned by a Rust operation.
124///
125/// Release both the descriptor array and its point arrays with
126/// [`knipsa_free_paths64`]. A zero-path result has `paths == NULL` and
127/// `path_count == 0`. Treat the returned descriptors and points as read-only.
128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
129#[repr(C)]
130pub struct KnipsaPaths64 {
131    /// Pointer to the returned path descriptors.
132    pub paths: *mut KnipsaPath64,
133    /// Number of descriptors at `paths`.
134    pub path_count: usize,
135}
136
137impl Default for KnipsaPaths64 {
138    fn default() -> Self {
139        Self { paths: std::ptr::null_mut(), path_count: 0 }
140    }
141}
142
143/// An owned floating-point result returned by a Rust operation.
144///
145/// Release both the descriptor array and its point arrays with
146/// [`knipsa_free_paths_d`]. A zero-path result has `paths == NULL` and
147/// `path_count == 0`. Treat the returned descriptors and points as read-only.
148#[derive(Clone, Copy, Debug, PartialEq)]
149#[repr(C)]
150pub struct KnipsaPathsD {
151    /// Pointer to the returned path descriptors.
152    pub paths: *mut KnipsaPathD,
153    /// Number of descriptors at `paths`.
154    pub path_count: usize,
155}
156
157impl Default for KnipsaPathsD {
158    fn default() -> Self {
159        Self { paths: std::ptr::null_mut(), path_count: 0 }
160    }
161}
162
163/// Options shared by the integer and floating-point offset entry points.
164///
165/// The enum fields use the numeric values documented by the C header so that
166/// unknown values can be rejected without constructing an invalid Rust enum at
167/// the ABI boundary. Use [`Default::default`] for round polygon offsets, then
168/// change the fields that matter to the caller.
169#[derive(Clone, Copy, Debug, PartialEq)]
170#[repr(C)]
171pub struct KnipsaOffsetOptions {
172    /// Corner style: `0` square, `1` bevel, `2` round, or `3` miter.
173    pub join_type: u8,
174    /// Endpoint style: `0` polygon, `1` joined, `2` butt, `3` square, or `4`
175    /// round.
176    pub end_type: u8,
177    /// Non-zero keeps collinear vertices in output rings.
178    pub preserve_collinear: u8,
179    /// Reserved padding; set this to zero.
180    pub reserved: u8,
181    /// Maximum miter length divided by the absolute offset distance.
182    pub miter_limit: f64,
183    /// Maximum round-join deviation in input units; zero selects the default.
184    pub arc_tolerance: f64,
185}
186
187impl KnipsaOffsetOptions {
188    /// Creates the default round-join polygon options.
189    #[must_use]
190    pub const fn new() -> Self {
191        Self {
192            join_type: 2,
193            end_type: 0,
194            preserve_collinear: 0,
195            reserved: 0,
196            miter_limit: 2.0,
197            arc_tolerance: 0.0,
198        }
199    }
200}
201
202impl Default for KnipsaOffsetOptions {
203    fn default() -> Self {
204        Self::new()
205    }
206}
207
208/// The corner style accepted by offset operations.
209///
210/// The numeric values are part of the C ABI and mirror the generated header.
211#[derive(Clone, Copy, Debug, PartialEq, Eq)]
212#[repr(C)]
213pub enum KnipsaJoinType {
214    /// A square corner.
215    Square = 0,
216    /// A bevelled corner.
217    Bevel = 1,
218    /// A circular corner.
219    Round = 2,
220    /// A mitered corner.
221    Miter = 3,
222}
223
224/// The endpoint style accepted by offset operations.
225///
226/// `Polygon` is for closed rings; all other values describe open polylines.
227#[derive(Clone, Copy, Debug, PartialEq, Eq)]
228#[repr(C)]
229pub enum KnipsaEndType {
230    /// Treat paths as closed polygons.
231    Polygon = 0,
232    /// Join the two sides of an open path.
233    Joined = 1,
234    /// Butt cap.
235    Butt = 2,
236    /// Square cap.
237    Square = 3,
238    /// Round cap.
239    Round = 4,
240}
241
242/// Whether an FFI path is closed or open.
243#[derive(Clone, Copy, Debug, PartialEq, Eq)]
244#[repr(C)]
245pub enum KnipsaPathKind {
246    /// The final point connects back to the first.
247    Closed = 0,
248    /// The final point does not connect back to the first.
249    Open = 1,
250}
251
252impl From<KnipsaPathKind> for PathKind {
253    fn from(kind: KnipsaPathKind) -> Self {
254        match kind {
255            KnipsaPathKind::Closed => Self::Closed,
256            KnipsaPathKind::Open => Self::Open,
257        }
258    }
259}
260
261/// Boolean operation values used by the C ABI.
262#[derive(Clone, Copy, Debug, PartialEq, Eq)]
263#[repr(C)]
264pub enum KnipsaClipType {
265    /// Keep the region present in both inputs.
266    Intersection = 1,
267    /// Keep the region present in either input.
268    Union = 2,
269    /// Keep subject regions outside clip regions.
270    Difference = 3,
271    /// Keep regions present in exactly one input.
272    Xor = 4,
273}
274
275/// Fill-rule values used by the C ABI.
276#[derive(Clone, Copy, Debug, PartialEq, Eq)]
277#[repr(C)]
278pub enum KnipsaFillRule {
279    /// Alternate filled state at every crossing.
280    EvenOdd = 0,
281    /// Fill where the winding number is non-zero.
282    NonZero = 1,
283    /// Fill only positively wound regions.
284    Positive = 2,
285    /// Fill only negatively wound regions.
286    Negative = 3,
287}
288
289/// Stable status codes returned by exported functions.
290///
291/// Functions return a status instead of allowing a Rust panic or exception to
292/// cross the ABI boundary. The output descriptor is reset before operations
293/// that produce an owned result.
294#[derive(Clone, Copy, Debug, PartialEq, Eq)]
295#[repr(C)]
296pub enum KnipsaStatus {
297    /// The call succeeded.
298    Ok = 0,
299    /// A required pointer was null.
300    NullPointer = 1,
301    /// A path did not satisfy the requested shape contract.
302    InvalidPath = 2,
303    /// A checked integer computation overflowed.
304    ArithmeticOverflow = 3,
305    /// An exact result could not be represented by the integer API.
306    NonIntegralResult = 4,
307    /// The arrangement could not be closed into output rings.
308    TopologyFailure = 5,
309    /// An operation or fill-rule value was not recognized.
310    InvalidArgument = 6,
311    /// A Rust panic was contained at the ABI boundary.
312    InternalError = 7,
313    /// Input paths intersect where a triangulation requires disjoint rings.
314    IntersectingPaths = 8,
315    /// A floating-point coordinate is NaN or infinite.
316    NonFiniteCoordinate = 9,
317    /// Offset parameters are not geometrically meaningful.
318    InvalidOffset = 10,
319    /// The input topology could not be triangulated.
320    TriangulationFailure = 11,
321}
322
323/// Point classification returned by `knipsa_point_in_polygon64`.
324#[derive(Clone, Copy, Debug, PartialEq, Eq)]
325#[repr(C)]
326pub enum KnipsaLocation {
327    /// The point is outside the path.
328    Outside = 0,
329    /// The point is inside the path.
330    Inside = 1,
331    /// The point lies on the path boundary.
332    Boundary = 2,
333}
334
335const VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes();
336const STATUS_OK: &[u8] = b"ok\0";
337const STATUS_NULL: &[u8] = b"required pointer is null\0";
338const STATUS_PATH: &[u8] = b"invalid path\0";
339const STATUS_OVERFLOW: &[u8] = b"checked arithmetic overflow\0";
340const STATUS_NON_INTEGRAL: &[u8] = b"result contains a non-integral coordinate\0";
341const STATUS_TOPOLOGY: &[u8] = b"polygon arrangement did not close\0";
342const STATUS_ARGUMENT: &[u8] = b"invalid operation or fill rule\0";
343const STATUS_INTERNAL: &[u8] = b"internal error\0";
344const STATUS_INTERSECTING: &[u8] = b"input paths intersect\0";
345const STATUS_NON_FINITE: &[u8] = b"coordinate is not finite\0";
346const STATUS_INVALID_OFFSET: &[u8] = b"invalid offset parameters\0";
347const STATUS_TRIANGULATION: &[u8] = b"triangulation failed\0";
348const STATUS_UNKNOWN: &[u8] = b"unknown status\0";
349
350#[cfg(test)]
351thread_local! {
352    static FORCE_BOOLEAN_PANIC: Cell<bool> = const { Cell::new(false) };
353}
354
355#[cfg(test)]
356fn test_panic_if_requested() {
357    assert!(!FORCE_BOOLEAN_PANIC.with(Cell::get), "test panic at the ABI boundary");
358}
359
360/// Returns the knipsa FFI version as a static NUL-terminated string.
361///
362/// The returned pointer is owned by the library and must not be freed.
363#[unsafe(no_mangle)]
364pub extern "C" fn knipsa_version() -> *const c_char {
365    VERSION.as_ptr().cast()
366}
367
368/// Returns a static NUL-terminated description for a status code.
369///
370/// The returned pointer is owned by the library and must not be freed.
371#[unsafe(no_mangle)]
372pub extern "C" fn knipsa_status_message(status: u8) -> *const c_char {
373    match status {
374        0 => STATUS_OK.as_ptr().cast(),
375        1 => STATUS_NULL.as_ptr().cast(),
376        2 => STATUS_PATH.as_ptr().cast(),
377        3 => STATUS_OVERFLOW.as_ptr().cast(),
378        4 => STATUS_NON_INTEGRAL.as_ptr().cast(),
379        5 => STATUS_TOPOLOGY.as_ptr().cast(),
380        6 => STATUS_ARGUMENT.as_ptr().cast(),
381        7 => STATUS_INTERNAL.as_ptr().cast(),
382        8 => STATUS_INTERSECTING.as_ptr().cast(),
383        9 => STATUS_NON_FINITE.as_ptr().cast(),
384        10 => STATUS_INVALID_OFFSET.as_ptr().cast(),
385        11 => STATUS_TRIANGULATION.as_ptr().cast(),
386        _ => STATUS_UNKNOWN.as_ptr().cast(),
387    }
388}
389
390/// Validates a borrowed array of paths.
391///
392/// A null `paths` pointer is accepted when `path_count` is zero. Each path's
393/// point pointer follows the same rule. Inputs remain owned by the caller.
394///
395/// # Safety
396///
397/// When either count is non-zero, the corresponding pointer and every
398/// non-empty point pointer must refer to readable memory for the duration of
399/// the call.
400#[unsafe(no_mangle)]
401pub unsafe extern "C" fn knipsa_validate_paths64(
402    paths: *const KnipsaPath64,
403    path_count: usize,
404    kind: u8,
405) -> KnipsaStatus {
406    let Some(kind) = path_kind_from_u8(kind) else {
407        return KnipsaStatus::InvalidArgument;
408    };
409    let paths = match copy_paths64(paths, path_count) {
410        Ok(paths) => paths,
411        Err(status) => return status,
412    };
413    match validate_paths64(&paths, kind) {
414        Ok(()) => KnipsaStatus::Ok,
415        Err(error) => status_from_error(&error),
416    }
417}
418
419/// Validates a borrowed array of floating-point paths.
420///
421/// A null `paths` pointer is accepted when `path_count` is zero. Coordinates
422/// must be finite. The `kind` argument accepts `KNIPSA_PATH_CLOSED` or
423/// `KNIPSA_PATH_OPEN`.
424///
425/// # Safety
426///
427/// When either count is non-zero, the corresponding pointer and every
428/// non-empty point pointer must refer to readable memory for the duration of
429/// the call.
430#[unsafe(no_mangle)]
431pub unsafe extern "C" fn knipsa_validate_paths_d(
432    paths: *const KnipsaPathD,
433    path_count: usize,
434    kind: u8,
435) -> KnipsaStatus {
436    let Some(kind) = path_kind_from_u8(kind) else {
437        return KnipsaStatus::InvalidArgument;
438    };
439    let paths = match copy_paths_d(paths, path_count) {
440        Ok(paths) => paths,
441        Err(status) => return status,
442    };
443    match validate_paths_d(&paths, kind) {
444        Ok(()) => KnipsaStatus::Ok,
445        Err(error) => status_from_error(&error),
446    }
447}
448
449/// Executes an integer boolean operation and allocates the result for the
450/// caller. The operation and fill-rule arguments use the values from
451/// `KnipsaClipType` and `KnipsaFillRule`.
452///
453/// On success, release `result` with [`knipsa_free_paths64`]. The input arrays
454/// remain owned by the caller. A null input array is valid when its count is
455/// zero.
456///
457/// # Safety
458///
459/// `result` must point to an empty, zero-initialized `KnipsaPaths64` storage
460/// slot, or to a slot whose previous result has been released. Non-empty input
461/// arrays and their point buffers must be readable for the duration of the
462/// call. Passing a live result without releasing it first returns
463/// [`KnipsaStatus::InvalidArgument`] and leaves that result untouched.
464#[unsafe(no_mangle)]
465pub unsafe extern "C" fn knipsa_boolean64(
466    subjects: *const KnipsaPath64,
467    subject_count: usize,
468    clips: *const KnipsaPath64,
469    clip_count: usize,
470    clip_type: u8,
471    fill_rule: u8,
472    result: *mut KnipsaPaths64,
473) -> KnipsaStatus {
474    if result.is_null() {
475        return KnipsaStatus::NullPointer;
476    }
477    if !result_is_empty64(result) {
478        return KnipsaStatus::InvalidArgument;
479    }
480    // SAFETY: `result` was checked for null and is writable for this call.
481    unsafe {
482        *result = KnipsaPaths64::default();
483    }
484    let Some(clip_type) = clip_type_from_u8(clip_type) else {
485        return KnipsaStatus::InvalidArgument;
486    };
487    let Some(fill_rule) = fill_rule_from_u8(fill_rule) else {
488        return KnipsaStatus::InvalidArgument;
489    };
490
491    let operation = catch_unwind(AssertUnwindSafe(|| {
492        #[cfg(test)]
493        test_panic_if_requested();
494        check_ffi_boolean_complexity(
495            subjects,
496            subject_count,
497            clips,
498            clip_count,
499            ComplexityLimits::DEFAULT,
500            |path| path.point_count,
501        )?;
502        let subjects = copy_paths64(subjects, subject_count)?;
503        let clips = copy_paths64(clips, clip_count)?;
504        boolean_op(BooleanRequest {
505            closed_subjects: &subjects,
506            open_subjects: &[],
507            clips: &clips,
508            clip_type,
509            fill_rule,
510            limits: ComplexityLimits::DEFAULT,
511        })
512        .map_err(|error| status_from_error(&error))
513    }));
514    match operation {
515        Ok(Ok(paths)) => {
516            write_paths64(paths.closed, result);
517            KnipsaStatus::Ok
518        }
519        Ok(Err(status)) => status,
520        Err(_) => KnipsaStatus::InternalError,
521    }
522}
523
524/// Executes a floating-point boolean operation and allocates the result for
525/// the caller. Coordinates are accepted as IEEE-754 `double` values and are
526/// checked for finiteness by the Rust API.
527///
528/// On success, release `result` with [`knipsa_free_paths_d`]. The input arrays
529/// remain owned by the caller. A null input array is valid when its count is
530/// zero.
531///
532/// # Safety
533///
534/// `result` must point to an empty, zero-initialized `KnipsaPathsD` storage
535/// slot, or to a slot whose previous result has been released. Non-empty input
536/// arrays and their point buffers must be readable for the duration of the
537/// call. Passing a live result without releasing it first returns
538/// [`KnipsaStatus::InvalidArgument`] and leaves that result untouched.
539#[unsafe(no_mangle)]
540pub unsafe extern "C" fn knipsa_boolean_d(
541    subjects: *const KnipsaPathD,
542    subject_count: usize,
543    clips: *const KnipsaPathD,
544    clip_count: usize,
545    clip_type: u8,
546    fill_rule: u8,
547    result: *mut KnipsaPathsD,
548) -> KnipsaStatus {
549    if result.is_null() {
550        return KnipsaStatus::NullPointer;
551    }
552    if !result_is_empty_d(result) {
553        return KnipsaStatus::InvalidArgument;
554    }
555    // SAFETY: `result` was checked for null and is writable for this call.
556    unsafe {
557        *result = KnipsaPathsD::default();
558    }
559    let Some(clip_type) = clip_type_from_u8(clip_type) else {
560        return KnipsaStatus::InvalidArgument;
561    };
562    let Some(fill_rule) = fill_rule_from_u8(fill_rule) else {
563        return KnipsaStatus::InvalidArgument;
564    };
565
566    let operation = catch_unwind(AssertUnwindSafe(|| {
567        #[cfg(test)]
568        test_panic_if_requested();
569        check_ffi_boolean_complexity(
570            subjects,
571            subject_count,
572            clips,
573            clip_count,
574            ComplexityLimits::DEFAULT,
575            |path| path.point_count,
576        )?;
577        let subjects = copy_paths_d(subjects, subject_count)?;
578        let clips = copy_paths_d(clips, clip_count)?;
579        boolean_op_d(BooleanRequest {
580            closed_subjects: &subjects,
581            open_subjects: &[],
582            clips: &clips,
583            clip_type,
584            fill_rule,
585            limits: ComplexityLimits::DEFAULT,
586        })
587        .map_err(|error| status_from_error(&error))
588    }));
589    match operation {
590        Ok(Ok(paths)) => {
591            write_paths_d(paths.closed, result);
592            KnipsaStatus::Ok
593        }
594        Ok(Err(status)) => status,
595        Err(_) => KnipsaStatus::InternalError,
596    }
597}
598
599/// Simplifies integer paths with a union using the selected fill rule.
600///
601/// On success, release `result` with [`knipsa_free_paths64`].
602///
603/// # Safety
604///
605/// `result` must point to an initialized empty result slot. When
606/// `path_count` is non-zero, `paths` and every non-empty point buffer must be
607/// readable for the duration of the call.
608#[unsafe(no_mangle)]
609pub unsafe extern "C" fn knipsa_simplify64(
610    paths: *const KnipsaPath64,
611    path_count: usize,
612    fill_rule: u8,
613    result: *mut KnipsaPaths64,
614) -> KnipsaStatus {
615    if result.is_null() {
616        return KnipsaStatus::NullPointer;
617    }
618    if !result_is_empty64(result) {
619        return KnipsaStatus::InvalidArgument;
620    }
621    // SAFETY: `result` was checked for null and is writable for this call.
622    unsafe {
623        *result = KnipsaPaths64::default();
624    }
625    let Some(fill_rule) = fill_rule_from_u8(fill_rule) else {
626        return KnipsaStatus::InvalidArgument;
627    };
628    let operation = catch_unwind(AssertUnwindSafe(|| {
629        #[cfg(test)]
630        test_panic_if_requested();
631        check_ffi_complexity(paths, path_count, ComplexityLimits::DEFAULT, |path| {
632            path.point_count
633        })?;
634        let paths = copy_paths64(paths, path_count)?;
635        simplify_paths64(&paths, fill_rule).map_err(|error| status_from_error(&error))
636    }));
637    match operation {
638        Ok(Ok(paths)) => {
639            write_paths64(paths, result);
640            KnipsaStatus::Ok
641        }
642        Ok(Err(status)) => status,
643        Err(_) => KnipsaStatus::InternalError,
644    }
645}
646
647/// Simplifies floating-point paths with a union using the selected fill rule.
648///
649/// On success, release `result` with [`knipsa_free_paths_d`].
650///
651/// # Safety
652///
653/// `result` must point to an initialized empty result slot. When
654/// `path_count` is non-zero, `paths` and every non-empty point buffer must be
655/// readable for the duration of the call.
656#[unsafe(no_mangle)]
657pub unsafe extern "C" fn knipsa_simplify_d(
658    paths: *const KnipsaPathD,
659    path_count: usize,
660    fill_rule: u8,
661    result: *mut KnipsaPathsD,
662) -> KnipsaStatus {
663    if result.is_null() {
664        return KnipsaStatus::NullPointer;
665    }
666    if !result_is_empty_d(result) {
667        return KnipsaStatus::InvalidArgument;
668    }
669    // SAFETY: `result` was checked for null and is writable for this call.
670    unsafe {
671        *result = KnipsaPathsD::default();
672    }
673    let Some(fill_rule) = fill_rule_from_u8(fill_rule) else {
674        return KnipsaStatus::InvalidArgument;
675    };
676    let operation = catch_unwind(AssertUnwindSafe(|| {
677        #[cfg(test)]
678        test_panic_if_requested();
679        check_ffi_complexity(paths, path_count, ComplexityLimits::DEFAULT, |path| {
680            path.point_count
681        })?;
682        let paths = copy_paths_d(paths, path_count)?;
683        simplify_paths_d(&paths, fill_rule).map_err(|error| status_from_error(&error))
684    }));
685    match operation {
686        Ok(Ok(paths)) => {
687            write_paths_d(paths, result);
688            KnipsaStatus::Ok
689        }
690        Ok(Err(status)) => status,
691        Err(_) => KnipsaStatus::InternalError,
692    }
693}
694
695/// Clips integer paths to an axis-aligned rectangle.
696///
697/// On success, release `result` with [`knipsa_free_paths64`].
698///
699/// # Safety
700///
701/// `result` must point to an initialized empty result slot. When
702/// `path_count` is non-zero, `paths` and every non-empty point buffer must be
703/// readable for the duration of the call.
704#[unsafe(no_mangle)]
705pub unsafe extern "C" fn knipsa_clip_to_rect64(
706    paths: *const KnipsaPath64,
707    path_count: usize,
708    rectangle: KnipsaRect64,
709    fill_rule: u8,
710    result: *mut KnipsaPaths64,
711) -> KnipsaStatus {
712    if result.is_null() {
713        return KnipsaStatus::NullPointer;
714    }
715    if !result_is_empty64(result) {
716        return KnipsaStatus::InvalidArgument;
717    }
718    // SAFETY: `result` was checked for null and is writable for this call.
719    unsafe {
720        *result = KnipsaPaths64::default();
721    }
722    let Some(fill_rule) = fill_rule_from_u8(fill_rule) else {
723        return KnipsaStatus::InvalidArgument;
724    };
725    let operation = catch_unwind(AssertUnwindSafe(|| {
726        #[cfg(test)]
727        test_panic_if_requested();
728        let paths = copy_paths64(paths, path_count)?;
729        clip_to_rect64(&paths, rectangle.into(), fill_rule)
730            .map_err(|error| status_from_error(&error))
731    }));
732    match operation {
733        Ok(Ok(paths)) => {
734            write_paths64(paths, result);
735            KnipsaStatus::Ok
736        }
737        Ok(Err(status)) => status,
738        Err(_) => KnipsaStatus::InternalError,
739    }
740}
741
742/// Clips floating-point paths to an axis-aligned rectangle.
743///
744/// On success, release `result` with [`knipsa_free_paths_d`].
745///
746/// # Safety
747///
748/// `result` must point to an initialized empty result slot. When
749/// `path_count` is non-zero, `paths` and every non-empty point buffer must be
750/// readable for the duration of the call.
751#[unsafe(no_mangle)]
752pub unsafe extern "C" fn knipsa_clip_to_rect_d(
753    paths: *const KnipsaPathD,
754    path_count: usize,
755    rectangle: KnipsaRectD,
756    fill_rule: u8,
757    result: *mut KnipsaPathsD,
758) -> KnipsaStatus {
759    if result.is_null() {
760        return KnipsaStatus::NullPointer;
761    }
762    if !result_is_empty_d(result) {
763        return KnipsaStatus::InvalidArgument;
764    }
765    // SAFETY: `result` was checked for null and is writable for this call.
766    unsafe {
767        *result = KnipsaPathsD::default();
768    }
769    let Some(fill_rule) = fill_rule_from_u8(fill_rule) else {
770        return KnipsaStatus::InvalidArgument;
771    };
772    let operation = catch_unwind(AssertUnwindSafe(|| {
773        #[cfg(test)]
774        test_panic_if_requested();
775        let paths = copy_paths_d(paths, path_count)?;
776        clip_to_rect_d(&paths, rectangle.into(), fill_rule)
777            .map_err(|error| status_from_error(&error))
778    }));
779    match operation {
780        Ok(Ok(paths)) => {
781            write_paths_d(paths, result);
782            KnipsaStatus::Ok
783        }
784        Ok(Err(status)) => status,
785        Err(_) => KnipsaStatus::InternalError,
786    }
787}
788
789/// Offsets integer-coordinate paths and returns the floating-point outline.
790/// Integer input coordinates are converted exactly when they fit in the
791/// exact `f64` integer range; joins and round caps are not rounded to integers
792/// by this entry point.
793///
794/// On success, release `result` with [`knipsa_free_paths_d`]. The offset style
795/// and tolerances are supplied through [`KnipsaOffsetOptions`].
796///
797/// # Safety
798///
799/// `options` must point to a readable [`KnipsaOffsetOptions`] value. `result`
800/// must point to an empty, zero-initialized `KnipsaPathsD` storage slot, or to
801/// a slot whose previous result has been released. Non-empty input arrays and
802/// their point buffers must be readable for the duration of the call. Passing
803/// a live result without releasing it first returns
804/// [`KnipsaStatus::InvalidArgument`] and leaves that result untouched.
805#[unsafe(no_mangle)]
806pub unsafe extern "C" fn knipsa_offset64(
807    paths: *const KnipsaPath64,
808    path_count: usize,
809    delta: f64,
810    options: *const KnipsaOffsetOptions,
811    result: *mut KnipsaPathsD,
812) -> KnipsaStatus {
813    if result.is_null() {
814        return KnipsaStatus::NullPointer;
815    }
816    if !result_is_empty_d(result) {
817        return KnipsaStatus::InvalidArgument;
818    }
819    // SAFETY: `result` was checked for null and is writable for this call.
820    unsafe {
821        *result = KnipsaPathsD::default();
822    }
823    let options = match copy_offset_options(options) {
824        Ok(options) => options,
825        Err(status) => return status,
826    };
827    let operation = catch_unwind(AssertUnwindSafe(|| {
828        #[cfg(test)]
829        test_panic_if_requested();
830        check_ffi_complexity(paths, path_count, ComplexityLimits::DEFAULT, |path| {
831            path.point_count
832        })?;
833        let paths = copy_paths64(paths, path_count)?;
834        let paths = paths64_to_d(&paths)?;
835        offset_paths_d(&paths, delta, options).map_err(|error| status_from_error(&error))
836    }));
837    match operation {
838        Ok(Ok(paths)) => {
839            write_paths_d(paths, result);
840            KnipsaStatus::Ok
841        }
842        Ok(Err(status)) => status,
843        Err(_) => KnipsaStatus::InternalError,
844    }
845}
846
847/// Offsets floating-point paths and returns floating-point polygon outlines.
848///
849/// On success, release `result` with [`knipsa_free_paths_d`]. The offset style
850/// and tolerances are supplied through [`KnipsaOffsetOptions`].
851///
852/// # Safety
853///
854/// `options` must point to a readable [`KnipsaOffsetOptions`] value. `result`
855/// must point to an empty, zero-initialized `KnipsaPathsD` storage slot, or to
856/// a slot whose previous result has been released. Non-empty input arrays and
857/// their point buffers must be readable for the duration of the call. Passing
858/// a live result without releasing it first returns
859/// [`KnipsaStatus::InvalidArgument`] and leaves that result untouched.
860#[unsafe(no_mangle)]
861pub unsafe extern "C" fn knipsa_offset_d(
862    paths: *const KnipsaPathD,
863    path_count: usize,
864    delta: f64,
865    options: *const KnipsaOffsetOptions,
866    result: *mut KnipsaPathsD,
867) -> KnipsaStatus {
868    if result.is_null() {
869        return KnipsaStatus::NullPointer;
870    }
871    if !result_is_empty_d(result) {
872        return KnipsaStatus::InvalidArgument;
873    }
874    // SAFETY: `result` was checked for null and is writable for this call.
875    unsafe {
876        *result = KnipsaPathsD::default();
877    }
878    let options = match copy_offset_options(options) {
879        Ok(options) => options,
880        Err(status) => return status,
881    };
882    let operation = catch_unwind(AssertUnwindSafe(|| {
883        #[cfg(test)]
884        test_panic_if_requested();
885        check_ffi_complexity(paths, path_count, ComplexityLimits::DEFAULT, |path| {
886            path.point_count
887        })?;
888        let paths = copy_paths_d(paths, path_count)?;
889        offset_paths_d(&paths, delta, options).map_err(|error| status_from_error(&error))
890    }));
891    match operation {
892        Ok(Ok(paths)) => {
893            write_paths_d(paths, result);
894            KnipsaStatus::Ok
895        }
896        Ok(Err(status)) => status,
897        Err(_) => KnipsaStatus::InternalError,
898    }
899}
900
901/// Triangulates integer-coordinate rings. Each returned triangle is exposed
902/// as a three-point path in `KnipsaPaths64`.
903///
904/// On success, release `result` with [`knipsa_free_paths64`].
905///
906/// # Safety
907///
908/// `result` must point to an empty, zero-initialized `KnipsaPaths64` storage
909/// slot, or to a slot whose previous result has been released. Non-empty input
910/// arrays and their point buffers must be readable for the duration of the
911/// call. Passing a live result without releasing it first returns
912/// [`KnipsaStatus::InvalidArgument`] and leaves that result untouched.
913#[unsafe(no_mangle)]
914pub unsafe extern "C" fn knipsa_triangulate64(
915    paths: *const KnipsaPath64,
916    path_count: usize,
917    fill_rule: u8,
918    result: *mut KnipsaPaths64,
919) -> KnipsaStatus {
920    if result.is_null() {
921        return KnipsaStatus::NullPointer;
922    }
923    if !result_is_empty64(result) {
924        return KnipsaStatus::InvalidArgument;
925    }
926    // SAFETY: `result` was checked for null and is writable for this call.
927    unsafe {
928        *result = KnipsaPaths64::default();
929    }
930    let Some(fill_rule) = fill_rule_from_u8(fill_rule) else {
931        return KnipsaStatus::InvalidArgument;
932    };
933    let operation = catch_unwind(AssertUnwindSafe(|| {
934        #[cfg(test)]
935        test_panic_if_requested();
936        check_ffi_complexity(paths, path_count, ComplexityLimits::DEFAULT, |path| {
937            path.point_count
938        })?;
939        let paths = copy_paths64(paths, path_count)?;
940        triangulate64(&paths, fill_rule, ComplexityLimits::DEFAULT)
941            .map(|triangles| {
942                triangles.into_iter().map(|triangle| triangle.into_iter().collect()).collect()
943            })
944            .map_err(|error| status_from_error(&error))
945    }));
946    match operation {
947        Ok(Ok(paths)) => {
948            write_paths64(paths, result);
949            KnipsaStatus::Ok
950        }
951        Ok(Err(status)) => status,
952        Err(_) => KnipsaStatus::InternalError,
953    }
954}
955
956/// Triangulates floating-point rings. Each returned triangle is exposed as a
957/// three-point path in `KnipsaPathsD`.
958///
959/// On success, release `result` with [`knipsa_free_paths_d`].
960///
961/// # Safety
962///
963/// `result` must point to an empty, zero-initialized `KnipsaPathsD` storage
964/// slot, or to a slot whose previous result has been released. Non-empty input
965/// arrays and their point buffers must be readable for the duration of the
966/// call. Passing a live result without releasing it first returns
967/// [`KnipsaStatus::InvalidArgument`] and leaves that result untouched.
968#[unsafe(no_mangle)]
969pub unsafe extern "C" fn knipsa_triangulate_d(
970    paths: *const KnipsaPathD,
971    path_count: usize,
972    fill_rule: u8,
973    result: *mut KnipsaPathsD,
974) -> KnipsaStatus {
975    if result.is_null() {
976        return KnipsaStatus::NullPointer;
977    }
978    if !result_is_empty_d(result) {
979        return KnipsaStatus::InvalidArgument;
980    }
981    // SAFETY: `result` was checked for null and is writable for this call.
982    unsafe {
983        *result = KnipsaPathsD::default();
984    }
985    let Some(fill_rule) = fill_rule_from_u8(fill_rule) else {
986        return KnipsaStatus::InvalidArgument;
987    };
988    let operation = catch_unwind(AssertUnwindSafe(|| {
989        #[cfg(test)]
990        test_panic_if_requested();
991        check_ffi_complexity(paths, path_count, ComplexityLimits::DEFAULT, |path| {
992            path.point_count
993        })?;
994        let paths = copy_paths_d(paths, path_count)?;
995        triangulate_d(&paths, fill_rule, ComplexityLimits::DEFAULT)
996            .map(|triangles| {
997                triangles.into_iter().map(|triangle| triangle.into_iter().collect()).collect()
998            })
999            .map_err(|error| status_from_error(&error))
1000    }));
1001    match operation {
1002        Ok(Ok(paths)) => {
1003            write_paths_d(paths, result);
1004            KnipsaStatus::Ok
1005        }
1006        Ok(Err(status)) => status,
1007        Err(_) => KnipsaStatus::InternalError,
1008    }
1009}
1010
1011/// Releases a result returned by [`knipsa_boolean64`] or
1012/// [`knipsa_triangulate64`]. It is safe to pass a null pointer or to call this
1013/// function again after it zeroes the result.
1014///
1015/// The pointer must be a valid pointer to a result descriptor previously
1016/// initialized by this library or a zeroed descriptor.
1017///
1018/// # Safety
1019///
1020/// A non-null `result` must point to writable storage initialized by this
1021/// library or to a zeroed descriptor. Its allocation metadata must not have
1022/// been modified by the caller.
1023#[unsafe(no_mangle)]
1024pub unsafe extern "C" fn knipsa_free_paths64(result: *mut KnipsaPaths64) {
1025    if result.is_null() {
1026        return;
1027    }
1028    // SAFETY: The pointer is supplied by the caller and is checked above.
1029    let owned = unsafe { *result };
1030    if owned.paths.is_null() {
1031        // SAFETY: `result` is non-null and points to the caller's result slot.
1032        unsafe {
1033            *result = KnipsaPaths64::default();
1034        }
1035        return;
1036    }
1037    // SAFETY: `owned.paths` and each point allocation were produced by
1038    // `write_paths64`, with exactly these lengths.
1039    unsafe {
1040        let descriptors = slice::from_raw_parts_mut(owned.paths, owned.path_count);
1041        for path in descriptors {
1042            if !path.points.is_null() {
1043                let points =
1044                    ptr::slice_from_raw_parts_mut(path.points.cast_mut(), path.point_count);
1045                drop(Box::from_raw(points));
1046            }
1047            *path = KnipsaPath64 { points: ptr::null(), point_count: 0 };
1048        }
1049        let descriptor_slice = ptr::slice_from_raw_parts_mut(owned.paths, owned.path_count);
1050        drop(Box::from_raw(descriptor_slice));
1051        *result = KnipsaPaths64::default();
1052    }
1053}
1054
1055/// Releases a result returned by [`knipsa_boolean_d`], [`knipsa_offset64`],
1056/// [`knipsa_offset_d`], or [`knipsa_triangulate_d`]. It is safe to pass a null
1057/// pointer or to call this function again after it zeroes the result.
1058///
1059/// The pointer must be a valid pointer to a result descriptor previously
1060/// initialized by this library or a zeroed descriptor.
1061///
1062/// # Safety
1063///
1064/// A non-null `result` must point to writable storage initialized by this
1065/// library or to a zeroed descriptor. Its allocation metadata must not have
1066/// been modified by the caller.
1067#[unsafe(no_mangle)]
1068pub unsafe extern "C" fn knipsa_free_paths_d(result: *mut KnipsaPathsD) {
1069    if result.is_null() {
1070        return;
1071    }
1072    // SAFETY: The pointer is supplied by the caller and is checked above.
1073    let owned = unsafe { *result };
1074    if owned.paths.is_null() {
1075        // SAFETY: `result` is non-null and points to the caller's result slot.
1076        unsafe {
1077            *result = KnipsaPathsD::default();
1078        }
1079        return;
1080    }
1081    // SAFETY: `owned.paths` and each point allocation were produced by
1082    // `write_paths_d`, with exactly these lengths.
1083    unsafe {
1084        let descriptors = slice::from_raw_parts_mut(owned.paths, owned.path_count);
1085        for path in descriptors {
1086            if !path.points.is_null() {
1087                let points =
1088                    ptr::slice_from_raw_parts_mut(path.points.cast_mut(), path.point_count);
1089                drop(Box::from_raw(points));
1090            }
1091            *path = KnipsaPathD { points: ptr::null(), point_count: 0 };
1092        }
1093        let descriptor_slice = ptr::slice_from_raw_parts_mut(owned.paths, owned.path_count);
1094        drop(Box::from_raw(descriptor_slice));
1095        *result = KnipsaPathsD::default();
1096    }
1097}
1098
1099/// Classifies one point against a borrowed closed path using the even-odd rule.
1100///
1101/// # Safety
1102///
1103/// `location` must point to writable `KnipsaLocation` storage. If
1104/// `path.point_count` is non-zero, `path.points` must point to readable
1105/// `KnipsaPoint64` values for the duration of the call.
1106#[unsafe(no_mangle)]
1107pub unsafe extern "C" fn knipsa_point_in_polygon64(
1108    path: KnipsaPath64,
1109    point: KnipsaPoint64,
1110    location: *mut KnipsaLocation,
1111) -> KnipsaStatus {
1112    if location.is_null() {
1113        return KnipsaStatus::NullPointer;
1114    }
1115    let points = if path.point_count == 0 {
1116        &[]
1117    } else if path.points.is_null() {
1118        return KnipsaStatus::NullPointer;
1119    } else {
1120        // SAFETY: The path descriptor has a non-null point pointer and the
1121        // caller owns the borrowed memory for this call.
1122        unsafe { slice::from_raw_parts(path.points, path.point_count) }
1123    };
1124    let rust_points: Vec<Point64> = points.iter().copied().map(Into::into).collect();
1125    match point_in_polygon(point.into(), &rust_points) {
1126        Ok(result) => {
1127            // SAFETY: The null pointer was rejected above and the caller owns
1128            // the writable output location for the duration of this call.
1129            unsafe {
1130                *location = result.into();
1131            }
1132            KnipsaStatus::Ok
1133        }
1134        Err(error) => status_from_error(&error),
1135    }
1136}
1137
1138fn status_from_error(error: &Error) -> KnipsaStatus {
1139    match error {
1140        Error::InvalidPath { .. } => KnipsaStatus::InvalidPath,
1141        Error::NonFiniteCoordinate { .. } => KnipsaStatus::NonFiniteCoordinate,
1142        Error::ArithmeticOverflow => KnipsaStatus::ArithmeticOverflow,
1143        Error::NonIntegralResult => KnipsaStatus::NonIntegralResult,
1144        Error::TopologyFailure => KnipsaStatus::TopologyFailure,
1145        Error::InvalidOffset => KnipsaStatus::InvalidOffset,
1146        Error::TriangulationFailure => KnipsaStatus::TriangulationFailure,
1147        Error::IntersectingPaths => KnipsaStatus::IntersectingPaths,
1148        Error::LimitExceeded { .. } => KnipsaStatus::InvalidArgument,
1149    }
1150}
1151
1152fn path_kind_from_u8(value: u8) -> Option<PathKind> {
1153    match value {
1154        0 => Some(PathKind::Closed),
1155        1 => Some(PathKind::Open),
1156        _ => None,
1157    }
1158}
1159
1160fn copy_offset_options(options: *const KnipsaOffsetOptions) -> Result<OffsetOptions, KnipsaStatus> {
1161    if options.is_null() {
1162        return Err(KnipsaStatus::NullPointer);
1163    }
1164    // SAFETY: The public functions require a readable options descriptor and
1165    // reject a null pointer above.
1166    let options = unsafe { &*options };
1167    if options.reserved != 0 {
1168        return Err(KnipsaStatus::InvalidArgument);
1169    }
1170    offset_options_from_u8(
1171        options.join_type,
1172        options.end_type,
1173        options.miter_limit,
1174        options.arc_tolerance,
1175        options.preserve_collinear,
1176    )
1177    .ok_or(KnipsaStatus::InvalidArgument)
1178}
1179
1180fn offset_options_from_u8(
1181    join_type: u8,
1182    end_type: u8,
1183    miter_limit: f64,
1184    arc_tolerance: f64,
1185    preserve_collinear: u8,
1186) -> Option<OffsetOptions> {
1187    let join_type = match join_type {
1188        0 => JoinType::Square,
1189        1 => JoinType::Bevel,
1190        2 => JoinType::Round,
1191        3 => JoinType::Miter,
1192        _ => return None,
1193    };
1194    let end_type = match end_type {
1195        0 => EndType::Polygon,
1196        1 => EndType::Joined,
1197        2 => EndType::Butt,
1198        3 => EndType::Square,
1199        4 => EndType::Round,
1200        _ => return None,
1201    };
1202    Some(OffsetOptions {
1203        join_type,
1204        end_type,
1205        miter_limit,
1206        arc_tolerance,
1207        preserve_collinear: preserve_collinear != 0,
1208        limits: ComplexityLimits::DEFAULT,
1209    })
1210}
1211
1212#[allow(clippy::cast_precision_loss)]
1213fn paths64_to_d(paths: &[Path64]) -> Result<Vec<PathD>, KnipsaStatus> {
1214    paths
1215        .iter()
1216        .map(|path| {
1217            path.iter()
1218                .map(|point| {
1219                    if point.x.unsigned_abs() > (1_u64 << 53)
1220                        || point.y.unsigned_abs() > (1_u64 << 53)
1221                    {
1222                        return Err(KnipsaStatus::ArithmeticOverflow);
1223                    }
1224                    Ok(PointD::new(point.x as f64, point.y as f64))
1225                })
1226                .collect()
1227        })
1228        .collect()
1229}
1230
1231fn clip_type_from_u8(value: u8) -> Option<ClipType> {
1232    match value {
1233        1 => Some(ClipType::Intersection),
1234        2 => Some(ClipType::Union),
1235        3 => Some(ClipType::Difference),
1236        4 => Some(ClipType::Xor),
1237        _ => None,
1238    }
1239}
1240
1241fn fill_rule_from_u8(value: u8) -> Option<FillRule> {
1242    match value {
1243        0 => Some(FillRule::EvenOdd),
1244        1 => Some(FillRule::NonZero),
1245        2 => Some(FillRule::Positive),
1246        3 => Some(FillRule::Negative),
1247        _ => None,
1248    }
1249}
1250
1251fn result_is_empty64(result: *const KnipsaPaths64) -> bool {
1252    // SAFETY: Public callers check this pointer for null before calling the
1253    // helper, and the descriptor points to caller-owned writable storage.
1254    let result = unsafe { &*result };
1255    result.paths.is_null() && result.path_count == 0
1256}
1257
1258fn result_is_empty_d(result: *const KnipsaPathsD) -> bool {
1259    // SAFETY: Public callers check this pointer for null before calling the
1260    // helper, and the descriptor points to caller-owned writable storage.
1261    let result = unsafe { &*result };
1262    result.paths.is_null() && result.path_count == 0
1263}
1264
1265fn check_ffi_complexity<T>(
1266    paths: *const T,
1267    path_count: usize,
1268    limits: ComplexityLimits,
1269    point_count: impl Fn(&T) -> usize,
1270) -> Result<(), KnipsaStatus> {
1271    // SAFETY: The public ABI contract keeps the descriptor array readable for
1272    // the duration of this preflight.
1273    let descriptors = unsafe { ffi_path_descriptors(paths, path_count, limits)? };
1274    limits.check(descriptors.iter().map(point_count)).map_err(|error| status_from_error(&error))
1275}
1276
1277fn check_ffi_boolean_complexity<T>(
1278    subjects: *const T,
1279    subject_count: usize,
1280    clips: *const T,
1281    clip_count: usize,
1282    limits: ComplexityLimits,
1283    point_count: impl Fn(&T) -> usize,
1284) -> Result<(), KnipsaStatus> {
1285    // SAFETY: The public ABI contract keeps both descriptor arrays readable
1286    // for the duration of this preflight.
1287    let subjects = unsafe { ffi_path_descriptors(subjects, subject_count, limits)? };
1288    // SAFETY: Same contract as for `subjects`.
1289    let clips = unsafe { ffi_path_descriptors(clips, clip_count, limits)? };
1290    limits
1291        .check(subjects.iter().chain(clips).map(point_count))
1292        .map_err(|error| status_from_error(&error))
1293}
1294
1295unsafe fn ffi_path_descriptors<'a, T>(
1296    paths: *const T,
1297    path_count: usize,
1298    limits: ComplexityLimits,
1299) -> Result<&'a [T], KnipsaStatus> {
1300    if path_count != 0 && paths.is_null() {
1301        return Err(KnipsaStatus::NullPointer);
1302    }
1303    if path_count > limits.max_paths() {
1304        return Err(KnipsaStatus::InvalidArgument);
1305    }
1306    if path_count == 0 {
1307        return Ok(&[]);
1308    }
1309    // SAFETY: Null was rejected, the count is bounded, and the C contract
1310    // requires the descriptor array to remain readable for the call.
1311    Ok(unsafe { slice::from_raw_parts(paths, path_count) })
1312}
1313
1314fn copy_paths64(
1315    paths: *const KnipsaPath64,
1316    path_count: usize,
1317) -> Result<Vec<Path64>, KnipsaStatus> {
1318    let descriptors = if path_count == 0 {
1319        &[]
1320    } else if paths.is_null() {
1321        return Err(KnipsaStatus::NullPointer);
1322    } else {
1323        // SAFETY: A non-null pointer and element count are supplied according
1324        // to the borrowed-slice contract of this ABI.
1325        unsafe { slice::from_raw_parts(paths, path_count) }
1326    };
1327    descriptors
1328        .iter()
1329        .map(|path| {
1330            let points = if path.point_count == 0 {
1331                &[]
1332            } else if path.points.is_null() {
1333                return Err(KnipsaStatus::NullPointer);
1334            } else {
1335                // SAFETY: The descriptor contains a non-null point pointer
1336                // and the caller owns that memory for this call.
1337                unsafe { slice::from_raw_parts(path.points, path.point_count) }
1338            };
1339            Ok(points.iter().copied().map(Into::into).collect())
1340        })
1341        .collect()
1342}
1343
1344fn copy_paths_d(paths: *const KnipsaPathD, path_count: usize) -> Result<Vec<PathD>, KnipsaStatus> {
1345    let descriptors = if path_count == 0 {
1346        &[]
1347    } else if paths.is_null() {
1348        return Err(KnipsaStatus::NullPointer);
1349    } else {
1350        // SAFETY: A non-null pointer and element count are supplied according
1351        // to the borrowed-slice contract of this ABI.
1352        unsafe { slice::from_raw_parts(paths, path_count) }
1353    };
1354    descriptors
1355        .iter()
1356        .map(|path| {
1357            let points = if path.point_count == 0 {
1358                &[]
1359            } else if path.points.is_null() {
1360                return Err(KnipsaStatus::NullPointer);
1361            } else {
1362                // SAFETY: The descriptor contains a non-null point pointer
1363                // and the caller owns that memory for this call.
1364                unsafe { slice::from_raw_parts(path.points, path.point_count) }
1365            };
1366            Ok(points.iter().copied().map(Into::into).collect())
1367        })
1368        .collect()
1369}
1370
1371fn write_paths64(paths: Vec<Path64>, result: *mut KnipsaPaths64) {
1372    let descriptors: Vec<KnipsaPath64> = paths
1373        .into_iter()
1374        .map(|path| {
1375            let points: Vec<KnipsaPoint64> =
1376                path.into_iter().map(|point| KnipsaPoint64 { x: point.x, y: point.y }).collect();
1377            let point_count = points.len();
1378            let points = points.into_boxed_slice();
1379            let points = Box::into_raw(points).cast::<KnipsaPoint64>();
1380            KnipsaPath64 { points, point_count }
1381        })
1382        .collect();
1383    let descriptors = descriptors.into_boxed_slice();
1384    let path_count = descriptors.len();
1385    let paths = if descriptors.is_empty() {
1386        ptr::null_mut()
1387    } else {
1388        Box::into_raw(descriptors).cast::<KnipsaPath64>()
1389    };
1390    // SAFETY: `result` was checked by the public function before this helper
1391    // was called.
1392    unsafe {
1393        (*result).paths = paths;
1394        (*result).path_count = path_count;
1395    }
1396}
1397
1398fn write_paths_d(paths: Vec<PathD>, result: *mut KnipsaPathsD) {
1399    let descriptors: Vec<KnipsaPathD> = paths
1400        .into_iter()
1401        .map(|path| {
1402            let points: Vec<KnipsaPointD> =
1403                path.into_iter().map(|point| KnipsaPointD { x: point.x, y: point.y }).collect();
1404            let point_count = points.len();
1405            let points = points.into_boxed_slice();
1406            let points = Box::into_raw(points).cast::<KnipsaPointD>();
1407            KnipsaPathD { points, point_count }
1408        })
1409        .collect();
1410    let descriptors = descriptors.into_boxed_slice();
1411    let path_count = descriptors.len();
1412    let paths = if descriptors.is_empty() {
1413        ptr::null_mut()
1414    } else {
1415        Box::into_raw(descriptors).cast::<KnipsaPathD>()
1416    };
1417    // SAFETY: `result` was checked by the public function before this helper
1418    // was called.
1419    unsafe {
1420        (*result).paths = paths;
1421        (*result).path_count = path_count;
1422    }
1423}
1424
1425impl From<PointLocation> for KnipsaLocation {
1426    fn from(location: PointLocation) -> Self {
1427        match location {
1428            PointLocation::Outside => Self::Outside,
1429            PointLocation::Inside => Self::Inside,
1430            PointLocation::Boundary => Self::Boundary,
1431        }
1432    }
1433}
1434
1435#[cfg(test)]
1436mod tests {
1437    use super::*;
1438    use std::ffi::CStr;
1439
1440    // The unit tests construct every descriptor and keep its backing storage
1441    // alive across each call, so these wrappers centralize the matching
1442    // Rust-side safety proof while exercising the exported ABI functions.
1443    fn knipsa_validate_paths64(
1444        paths: *const KnipsaPath64,
1445        path_count: usize,
1446        kind: u8,
1447    ) -> KnipsaStatus {
1448        // SAFETY: Test callers satisfy the exported borrowed-slice contract.
1449        unsafe { super::knipsa_validate_paths64(paths, path_count, kind) }
1450    }
1451
1452    fn knipsa_validate_paths_d(
1453        paths: *const KnipsaPathD,
1454        path_count: usize,
1455        kind: u8,
1456    ) -> KnipsaStatus {
1457        // SAFETY: Test callers satisfy the exported borrowed-slice contract.
1458        unsafe { super::knipsa_validate_paths_d(paths, path_count, kind) }
1459    }
1460
1461    #[allow(clippy::too_many_arguments)]
1462    fn knipsa_boolean64(
1463        subjects: *const KnipsaPath64,
1464        subject_count: usize,
1465        clips: *const KnipsaPath64,
1466        clip_count: usize,
1467        clip_type: u8,
1468        fill_rule: u8,
1469        result: *mut KnipsaPaths64,
1470    ) -> KnipsaStatus {
1471        // SAFETY: Test callers keep inputs readable and result slots writable.
1472        unsafe {
1473            super::knipsa_boolean64(
1474                subjects,
1475                subject_count,
1476                clips,
1477                clip_count,
1478                clip_type,
1479                fill_rule,
1480                result,
1481            )
1482        }
1483    }
1484
1485    #[allow(clippy::too_many_arguments)]
1486    fn knipsa_boolean_d(
1487        subjects: *const KnipsaPathD,
1488        subject_count: usize,
1489        clips: *const KnipsaPathD,
1490        clip_count: usize,
1491        clip_type: u8,
1492        fill_rule: u8,
1493        result: *mut KnipsaPathsD,
1494    ) -> KnipsaStatus {
1495        // SAFETY: Test callers keep inputs readable and result slots writable.
1496        unsafe {
1497            super::knipsa_boolean_d(
1498                subjects,
1499                subject_count,
1500                clips,
1501                clip_count,
1502                clip_type,
1503                fill_rule,
1504                result,
1505            )
1506        }
1507    }
1508
1509    fn knipsa_simplify64(
1510        paths: *const KnipsaPath64,
1511        path_count: usize,
1512        fill_rule: u8,
1513        result: *mut KnipsaPaths64,
1514    ) -> KnipsaStatus {
1515        // SAFETY: Test callers keep inputs readable and result slots writable.
1516        unsafe { super::knipsa_simplify64(paths, path_count, fill_rule, result) }
1517    }
1518
1519    fn knipsa_simplify_d(
1520        paths: *const KnipsaPathD,
1521        path_count: usize,
1522        fill_rule: u8,
1523        result: *mut KnipsaPathsD,
1524    ) -> KnipsaStatus {
1525        // SAFETY: Test callers keep inputs readable and result slots writable.
1526        unsafe { super::knipsa_simplify_d(paths, path_count, fill_rule, result) }
1527    }
1528
1529    fn knipsa_clip_to_rect64(
1530        paths: *const KnipsaPath64,
1531        path_count: usize,
1532        rectangle: KnipsaRect64,
1533        fill_rule: u8,
1534        result: *mut KnipsaPaths64,
1535    ) -> KnipsaStatus {
1536        // SAFETY: Test callers keep inputs readable and result slots writable.
1537        unsafe { super::knipsa_clip_to_rect64(paths, path_count, rectangle, fill_rule, result) }
1538    }
1539
1540    fn knipsa_clip_to_rect_d(
1541        paths: *const KnipsaPathD,
1542        path_count: usize,
1543        rectangle: KnipsaRectD,
1544        fill_rule: u8,
1545        result: *mut KnipsaPathsD,
1546    ) -> KnipsaStatus {
1547        // SAFETY: Test callers keep inputs readable and result slots writable.
1548        unsafe { super::knipsa_clip_to_rect_d(paths, path_count, rectangle, fill_rule, result) }
1549    }
1550
1551    fn knipsa_offset64(
1552        paths: *const KnipsaPath64,
1553        path_count: usize,
1554        delta: f64,
1555        options: *const KnipsaOffsetOptions,
1556        result: *mut KnipsaPathsD,
1557    ) -> KnipsaStatus {
1558        // SAFETY: Test callers keep inputs/options readable and result slots writable.
1559        unsafe { super::knipsa_offset64(paths, path_count, delta, options, result) }
1560    }
1561
1562    fn knipsa_offset_d(
1563        paths: *const KnipsaPathD,
1564        path_count: usize,
1565        delta: f64,
1566        options: *const KnipsaOffsetOptions,
1567        result: *mut KnipsaPathsD,
1568    ) -> KnipsaStatus {
1569        // SAFETY: Test callers keep inputs/options readable and result slots writable.
1570        unsafe { super::knipsa_offset_d(paths, path_count, delta, options, result) }
1571    }
1572
1573    fn knipsa_triangulate64(
1574        paths: *const KnipsaPath64,
1575        path_count: usize,
1576        fill_rule: u8,
1577        result: *mut KnipsaPaths64,
1578    ) -> KnipsaStatus {
1579        // SAFETY: Test callers keep inputs readable and result slots writable.
1580        unsafe { super::knipsa_triangulate64(paths, path_count, fill_rule, result) }
1581    }
1582
1583    fn knipsa_triangulate_d(
1584        paths: *const KnipsaPathD,
1585        path_count: usize,
1586        fill_rule: u8,
1587        result: *mut KnipsaPathsD,
1588    ) -> KnipsaStatus {
1589        // SAFETY: Test callers keep inputs readable and result slots writable.
1590        unsafe { super::knipsa_triangulate_d(paths, path_count, fill_rule, result) }
1591    }
1592
1593    fn knipsa_free_paths64(result: *mut KnipsaPaths64) {
1594        // SAFETY: Test callers pass library-owned or zeroed result descriptors.
1595        unsafe { super::knipsa_free_paths64(result) }
1596    }
1597
1598    fn knipsa_free_paths_d(result: *mut KnipsaPathsD) {
1599        // SAFETY: Test callers pass library-owned or zeroed result descriptors.
1600        unsafe { super::knipsa_free_paths_d(result) }
1601    }
1602
1603    fn knipsa_point_in_polygon64(
1604        path: KnipsaPath64,
1605        point: KnipsaPoint64,
1606        location: *mut KnipsaLocation,
1607    ) -> KnipsaStatus {
1608        // SAFETY: Test callers keep the path readable and output writable.
1609        unsafe { super::knipsa_point_in_polygon64(path, point, location) }
1610    }
1611
1612    const TRIANGLE: [KnipsaPoint64; 3] = [
1613        KnipsaPoint64 { x: 0, y: 0 },
1614        KnipsaPoint64 { x: 10, y: 0 },
1615        KnipsaPoint64 { x: 0, y: 10 },
1616    ];
1617
1618    const TRIANGLE_D: [KnipsaPointD; 3] = [
1619        KnipsaPointD { x: 0.0, y: 0.0 },
1620        KnipsaPointD { x: 10.0, y: 0.0 },
1621        KnipsaPointD { x: 0.0, y: 10.0 },
1622    ];
1623
1624    #[test]
1625    fn exposes_version_and_status_messages() {
1626        // SAFETY: Both pointers refer to static NUL-terminated strings.
1627        unsafe {
1628            assert_eq!(CStr::from_ptr(knipsa_version()).to_str(), Ok(env!("CARGO_PKG_VERSION")));
1629            assert_eq!(
1630                CStr::from_ptr(knipsa_status_message(KnipsaStatus::Ok as u8)).to_str(),
1631                Ok("ok")
1632            );
1633            assert_eq!(
1634                CStr::from_ptr(knipsa_status_message(KnipsaStatus::NullPointer as u8)).to_str(),
1635                Ok("required pointer is null")
1636            );
1637            assert_eq!(
1638                CStr::from_ptr(knipsa_status_message(KnipsaStatus::InvalidPath as u8)).to_str(),
1639                Ok("invalid path")
1640            );
1641            assert_eq!(
1642                CStr::from_ptr(knipsa_status_message(KnipsaStatus::ArithmeticOverflow as u8))
1643                    .to_str(),
1644                Ok("checked arithmetic overflow")
1645            );
1646            assert_eq!(
1647                CStr::from_ptr(knipsa_status_message(KnipsaStatus::NonIntegralResult as u8))
1648                    .to_str(),
1649                Ok("result contains a non-integral coordinate")
1650            );
1651            assert_eq!(
1652                CStr::from_ptr(knipsa_status_message(KnipsaStatus::TopologyFailure as u8)).to_str(),
1653                Ok("polygon arrangement did not close")
1654            );
1655            assert_eq!(
1656                CStr::from_ptr(knipsa_status_message(KnipsaStatus::InvalidArgument as u8)).to_str(),
1657                Ok("invalid operation or fill rule")
1658            );
1659            assert_eq!(
1660                CStr::from_ptr(knipsa_status_message(KnipsaStatus::InternalError as u8)).to_str(),
1661                Ok("internal error")
1662            );
1663            assert_eq!(
1664                CStr::from_ptr(knipsa_status_message(KnipsaStatus::IntersectingPaths as u8))
1665                    .to_str(),
1666                Ok("input paths intersect")
1667            );
1668            assert_eq!(
1669                CStr::from_ptr(knipsa_status_message(KnipsaStatus::NonFiniteCoordinate as u8))
1670                    .to_str(),
1671                Ok("coordinate is not finite")
1672            );
1673            assert_eq!(
1674                CStr::from_ptr(knipsa_status_message(KnipsaStatus::InvalidOffset as u8)).to_str(),
1675                Ok("invalid offset parameters")
1676            );
1677            assert_eq!(
1678                CStr::from_ptr(knipsa_status_message(KnipsaStatus::TriangulationFailure as u8))
1679                    .to_str(),
1680                Ok("triangulation failed")
1681            );
1682            assert_eq!(CStr::from_ptr(knipsa_status_message(255)).to_str(), Ok("unknown status"));
1683        }
1684    }
1685
1686    #[test]
1687    fn validates_null_empty_valid_and_invalid_inputs() {
1688        assert_eq!(
1689            knipsa_validate_paths64(std::ptr::null(), 0, KnipsaPathKind::Closed as u8),
1690            KnipsaStatus::Ok
1691        );
1692        assert_eq!(
1693            knipsa_validate_paths64(std::ptr::null(), 1, KnipsaPathKind::Closed as u8),
1694            KnipsaStatus::NullPointer
1695        );
1696        let empty = KnipsaPath64 { points: std::ptr::null(), point_count: 0 };
1697        assert_eq!(
1698            knipsa_validate_paths64(std::ptr::from_ref(&empty), 1, KnipsaPathKind::Closed as u8),
1699            KnipsaStatus::Ok
1700        );
1701        let valid = KnipsaPath64 { points: TRIANGLE.as_ptr(), point_count: TRIANGLE.len() };
1702        assert_eq!(
1703            knipsa_validate_paths64(std::ptr::from_ref(&valid), 1, KnipsaPathKind::Closed as u8),
1704            KnipsaStatus::Ok
1705        );
1706        assert_eq!(
1707            knipsa_validate_paths64(std::ptr::from_ref(&valid), 1, KnipsaPathKind::Open as u8),
1708            KnipsaStatus::Ok
1709        );
1710        let invalid = KnipsaPath64 { points: TRIANGLE.as_ptr(), point_count: 1 };
1711        assert_eq!(
1712            knipsa_validate_paths64(std::ptr::from_ref(&invalid), 1, KnipsaPathKind::Closed as u8),
1713            KnipsaStatus::InvalidPath
1714        );
1715        let bad_pointer = KnipsaPath64 { points: std::ptr::null(), point_count: 1 };
1716        assert_eq!(
1717            knipsa_validate_paths64(
1718                std::ptr::from_ref(&bad_pointer),
1719                1,
1720                KnipsaPathKind::Closed as u8
1721            ),
1722            KnipsaStatus::NullPointer
1723        );
1724        assert_eq!(knipsa_validate_paths64(std::ptr::null(), 0, 99), KnipsaStatus::InvalidArgument);
1725
1726        let valid_d = KnipsaPathD { points: TRIANGLE_D.as_ptr(), point_count: TRIANGLE_D.len() };
1727        assert_eq!(
1728            knipsa_validate_paths_d(std::ptr::from_ref(&valid_d), 1, KnipsaPathKind::Closed as u8,),
1729            KnipsaStatus::Ok
1730        );
1731        let invalid_d_points = [
1732            KnipsaPointD { x: 0.0, y: 0.0 },
1733            KnipsaPointD { x: f64::NAN, y: 0.0 },
1734            KnipsaPointD { x: 0.0, y: 1.0 },
1735        ];
1736        let invalid_d =
1737            KnipsaPathD { points: invalid_d_points.as_ptr(), point_count: invalid_d_points.len() };
1738        assert_eq!(
1739            knipsa_validate_paths_d(
1740                std::ptr::from_ref(&invalid_d),
1741                1,
1742                KnipsaPathKind::Closed as u8,
1743            ),
1744            KnipsaStatus::NonFiniteCoordinate
1745        );
1746    }
1747
1748    #[test]
1749    fn covers_path_kind_result_guards_and_integer_conversion_overflow() {
1750        assert_eq!(PathKind::from(KnipsaPathKind::Closed), PathKind::Closed);
1751        assert_eq!(PathKind::from(KnipsaPathKind::Open), PathKind::Open);
1752        assert_eq!(knipsa_validate_paths_d(std::ptr::null(), 0, 99), KnipsaStatus::InvalidArgument);
1753        let bad_d_pointer = KnipsaPathD { points: std::ptr::null(), point_count: 1 };
1754        assert_eq!(
1755            knipsa_validate_paths_d(
1756                std::ptr::from_ref(&bad_d_pointer),
1757                1,
1758                KnipsaPathKind::Closed as u8,
1759            ),
1760            KnipsaStatus::NullPointer
1761        );
1762
1763        let options = KnipsaOffsetOptions::default();
1764        let mut occupied_d_path = KnipsaPathD { points: std::ptr::null(), point_count: 0 };
1765        let mut occupied_d =
1766            KnipsaPathsD { paths: std::ptr::from_mut(&mut occupied_d_path), path_count: 1 };
1767        assert_eq!(
1768            knipsa_offset64(
1769                std::ptr::null(),
1770                0,
1771                1.0,
1772                std::ptr::from_ref(&options),
1773                std::ptr::from_mut(&mut occupied_d),
1774            ),
1775            KnipsaStatus::InvalidArgument
1776        );
1777        occupied_d = KnipsaPathsD::default();
1778        let mut occupied_d_path = KnipsaPathD { points: std::ptr::null(), point_count: 0 };
1779        occupied_d.paths = std::ptr::from_mut(&mut occupied_d_path);
1780        occupied_d.path_count = 1;
1781        assert_eq!(
1782            knipsa_offset_d(
1783                std::ptr::null(),
1784                0,
1785                1.0,
1786                std::ptr::from_ref(&options),
1787                std::ptr::from_mut(&mut occupied_d),
1788            ),
1789            KnipsaStatus::InvalidArgument
1790        );
1791
1792        let mut occupied_64_path = KnipsaPath64 { points: std::ptr::null(), point_count: 0 };
1793        let mut occupied_64 =
1794            KnipsaPaths64 { paths: std::ptr::from_mut(&mut occupied_64_path), path_count: 1 };
1795        assert_eq!(
1796            knipsa_triangulate64(
1797                std::ptr::null(),
1798                0,
1799                FillRule::EvenOdd as u8,
1800                std::ptr::from_mut(&mut occupied_64),
1801            ),
1802            KnipsaStatus::InvalidArgument
1803        );
1804        let mut occupied_d_path = KnipsaPathD { points: std::ptr::null(), point_count: 0 };
1805        let mut occupied_d =
1806            KnipsaPathsD { paths: std::ptr::from_mut(&mut occupied_d_path), path_count: 1 };
1807        assert_eq!(
1808            knipsa_triangulate_d(
1809                std::ptr::null(),
1810                0,
1811                FillRule::EvenOdd as u8,
1812                std::ptr::from_mut(&mut occupied_d),
1813            ),
1814            KnipsaStatus::InvalidArgument
1815        );
1816
1817        let x_overflow = vec![Point64::new((1_i64 << 53) + 1, 0)];
1818        assert_eq!(paths64_to_d(&[x_overflow]), Err(KnipsaStatus::ArithmeticOverflow));
1819        let y_overflow = vec![Point64::new(0, (1_i64 << 53) + 1)];
1820        assert_eq!(paths64_to_d(&[y_overflow]), Err(KnipsaStatus::ArithmeticOverflow));
1821    }
1822
1823    #[test]
1824    fn classifies_points_and_rejects_bad_output_pointer() {
1825        let path = KnipsaPath64 { points: TRIANGLE.as_ptr(), point_count: TRIANGLE.len() };
1826        assert_eq!(
1827            knipsa_point_in_polygon64(path, KnipsaPoint64 { x: 1, y: 1 }, std::ptr::null_mut()),
1828            KnipsaStatus::NullPointer
1829        );
1830        let mut location = KnipsaLocation::Outside;
1831        assert_eq!(
1832            knipsa_point_in_polygon64(
1833                path,
1834                KnipsaPoint64 { x: 1, y: 1 },
1835                std::ptr::from_mut(&mut location)
1836            ),
1837            KnipsaStatus::Ok
1838        );
1839        assert_eq!(location, KnipsaLocation::Inside);
1840        assert_eq!(
1841            knipsa_point_in_polygon64(
1842                path,
1843                KnipsaPoint64 { x: 10, y: 10 },
1844                std::ptr::from_mut(&mut location)
1845            ),
1846            KnipsaStatus::Ok
1847        );
1848        assert_eq!(location, KnipsaLocation::Outside);
1849        let empty = KnipsaPath64 { points: std::ptr::null(), point_count: 0 };
1850        assert_eq!(
1851            knipsa_point_in_polygon64(
1852                empty,
1853                KnipsaPoint64 { x: 0, y: 0 },
1854                std::ptr::from_mut(&mut location)
1855            ),
1856            KnipsaStatus::Ok
1857        );
1858        assert_eq!(location, KnipsaLocation::Outside);
1859        assert_eq!(
1860            knipsa_point_in_polygon64(
1861                path,
1862                KnipsaPoint64 { x: 0, y: 0 },
1863                std::ptr::from_mut(&mut location)
1864            ),
1865            KnipsaStatus::Ok
1866        );
1867        assert_eq!(location, KnipsaLocation::Boundary);
1868        let invalid = KnipsaPath64 { points: TRIANGLE.as_ptr(), point_count: 2 };
1869        assert_eq!(
1870            knipsa_point_in_polygon64(
1871                invalid,
1872                KnipsaPoint64 { x: 0, y: 0 },
1873                std::ptr::from_mut(&mut location)
1874            ),
1875            KnipsaStatus::InvalidPath
1876        );
1877        let bad_pointer = KnipsaPath64 { points: std::ptr::null(), point_count: 1 };
1878        assert_eq!(
1879            knipsa_point_in_polygon64(
1880                bad_pointer,
1881                KnipsaPoint64 { x: 0, y: 0 },
1882                std::ptr::from_mut(&mut location)
1883            ),
1884            KnipsaStatus::NullPointer
1885        );
1886        assert_eq!(status_from_error(&Error::ArithmeticOverflow), KnipsaStatus::ArithmeticOverflow);
1887        assert_eq!(status_from_error(&Error::NonIntegralResult), KnipsaStatus::NonIntegralResult);
1888        assert_eq!(status_from_error(&Error::TopologyFailure), KnipsaStatus::TopologyFailure);
1889        assert_eq!(status_from_error(&Error::InvalidOffset), KnipsaStatus::InvalidOffset);
1890        assert_eq!(
1891            status_from_error(&Error::TriangulationFailure),
1892            KnipsaStatus::TriangulationFailure
1893        );
1894        assert_eq!(status_from_error(&Error::IntersectingPaths), KnipsaStatus::IntersectingPaths);
1895        assert_eq!(
1896            status_from_error(&Error::LimitExceeded {
1897                resource: knipsa::ComplexityResource::Paths,
1898                limit: 0,
1899                required: 1,
1900            }),
1901            KnipsaStatus::InvalidArgument
1902        );
1903    }
1904
1905    #[test]
1906    fn executes_and_releases_boolean_result() {
1907        let square = [
1908            KnipsaPoint64 { x: 0, y: 0 },
1909            KnipsaPoint64 { x: 10, y: 0 },
1910            KnipsaPoint64 { x: 10, y: 10 },
1911            KnipsaPoint64 { x: 0, y: 10 },
1912        ];
1913        let subject = KnipsaPath64 { points: square.as_ptr(), point_count: square.len() };
1914        let mut result = KnipsaPaths64::default();
1915        assert_eq!(
1916            knipsa_boolean64(
1917                std::ptr::from_ref(&subject),
1918                1,
1919                std::ptr::null(),
1920                0,
1921                ClipType::Union as u8,
1922                FillRule::NonZero as u8,
1923                std::ptr::from_mut(&mut result),
1924            ),
1925            KnipsaStatus::Ok
1926        );
1927        assert_eq!(result.path_count, 1);
1928        assert_eq!(
1929            knipsa_boolean64(
1930                std::ptr::from_ref(&subject),
1931                1,
1932                std::ptr::null(),
1933                0,
1934                ClipType::Union as u8,
1935                FillRule::NonZero as u8,
1936                std::ptr::from_mut(&mut result),
1937            ),
1938            KnipsaStatus::InvalidArgument
1939        );
1940        // SAFETY: The result belongs to this test and was returned by the
1941        // boolean function with the reported descriptor count.
1942        unsafe {
1943            let paths = slice::from_raw_parts(result.paths, result.path_count);
1944            assert_eq!(paths[0].point_count, 4);
1945            assert_eq!((*paths[0].points).x, 0);
1946        }
1947        knipsa_free_paths64(std::ptr::from_mut(&mut result));
1948        assert_eq!(result, KnipsaPaths64::default());
1949        knipsa_free_paths64(std::ptr::from_mut(&mut result));
1950        knipsa_free_paths64(std::ptr::null_mut());
1951    }
1952
1953    #[test]
1954    fn boolean_preflight_applies_one_combined_complexity_budget() {
1955        let subjects = (0..600)
1956            .map(|_| KnipsaPath64 { points: std::ptr::null(), point_count: 0 })
1957            .collect::<Vec<_>>();
1958        let clips = (0..600)
1959            .map(|_| KnipsaPath64 { points: std::ptr::null(), point_count: 0 })
1960            .collect::<Vec<_>>();
1961        let mut result = KnipsaPaths64::default();
1962        assert_eq!(
1963            knipsa_boolean64(
1964                subjects.as_ptr(),
1965                subjects.len(),
1966                clips.as_ptr(),
1967                clips.len(),
1968                ClipType::Union as u8,
1969                FillRule::EvenOdd as u8,
1970                std::ptr::from_mut(&mut result),
1971            ),
1972            KnipsaStatus::InvalidArgument
1973        );
1974        assert_eq!(result, KnipsaPaths64::default());
1975    }
1976
1977    #[test]
1978    #[allow(clippy::too_many_lines)]
1979    fn executes_and_releases_double_boolean_results() {
1980        let subject = KnipsaPathD { points: TRIANGLE_D.as_ptr(), point_count: 3 };
1981        let mut result = KnipsaPathsD::default();
1982        assert_eq!(
1983            knipsa_boolean_d(
1984                std::ptr::from_ref(&subject),
1985                1,
1986                std::ptr::null(),
1987                0,
1988                ClipType::Union as u8,
1989                FillRule::EvenOdd as u8,
1990                std::ptr::from_mut(&mut result),
1991            ),
1992            KnipsaStatus::Ok
1993        );
1994        assert_eq!(result.path_count, 1);
1995        assert_eq!(
1996            knipsa_boolean_d(
1997                std::ptr::from_ref(&subject),
1998                1,
1999                std::ptr::null(),
2000                0,
2001                ClipType::Union as u8,
2002                FillRule::EvenOdd as u8,
2003                std::ptr::from_mut(&mut result),
2004            ),
2005            KnipsaStatus::InvalidArgument
2006        );
2007        // SAFETY: The result belongs to this test and was returned by the
2008        // floating-point boolean function with the reported descriptor count.
2009        unsafe {
2010            let paths = slice::from_raw_parts(result.paths, result.path_count);
2011            assert_eq!(paths[0].point_count, 3);
2012            assert_eq!((*paths[0].points).x.to_bits(), 0.0_f64.to_bits());
2013        }
2014        knipsa_free_paths_d(std::ptr::from_mut(&mut result));
2015        assert_eq!(result, KnipsaPathsD::default());
2016        knipsa_free_paths_d(std::ptr::from_mut(&mut result));
2017        knipsa_free_paths_d(std::ptr::null_mut());
2018
2019        let subject_square = [
2020            KnipsaPointD { x: 0.0, y: 0.0 },
2021            KnipsaPointD { x: 10.0, y: 0.0 },
2022            KnipsaPointD { x: 10.0, y: 10.0 },
2023            KnipsaPointD { x: 0.0, y: 10.0 },
2024        ];
2025        let clip_square = [
2026            KnipsaPointD { x: 5.0, y: -1.0 },
2027            KnipsaPointD { x: 15.0, y: -1.0 },
2028            KnipsaPointD { x: 15.0, y: 9.0 },
2029            KnipsaPointD { x: 5.0, y: 9.0 },
2030        ];
2031        let subject_path =
2032            KnipsaPathD { points: subject_square.as_ptr(), point_count: subject_square.len() };
2033        let clip_path =
2034            KnipsaPathD { points: clip_square.as_ptr(), point_count: clip_square.len() };
2035        for clip_type in
2036            [ClipType::Intersection, ClipType::Union, ClipType::Difference, ClipType::Xor]
2037        {
2038            assert_eq!(
2039                knipsa_boolean_d(
2040                    std::ptr::from_ref(&subject_path),
2041                    1,
2042                    std::ptr::from_ref(&clip_path),
2043                    1,
2044                    clip_type as u8,
2045                    FillRule::EvenOdd as u8,
2046                    std::ptr::from_mut(&mut result),
2047                ),
2048                KnipsaStatus::Ok
2049            );
2050            assert_ne!(result.path_count, 0);
2051            knipsa_free_paths_d(std::ptr::from_mut(&mut result));
2052        }
2053
2054        // Adjacent points remain distinct to the exact kernel but collide in
2055        // the fast path's acceleration key, exercising its conservative
2056        // fallback through the public FFI build too.
2057        let sub_quantization_triangle = [
2058            KnipsaPointD { x: 0.0, y: 0.0 },
2059            KnipsaPointD { x: 0.000_000_000_1, y: 0.0 },
2060            KnipsaPointD { x: 0.0, y: 1.0 },
2061        ];
2062        let tiny_path = KnipsaPathD {
2063            points: sub_quantization_triangle.as_ptr(),
2064            point_count: sub_quantization_triangle.len(),
2065        };
2066        let subjects = [tiny_path, subject_path];
2067        assert_eq!(
2068            knipsa_boolean_d(
2069                subjects.as_ptr(),
2070                subjects.len(),
2071                std::ptr::null(),
2072                0,
2073                ClipType::Union as u8,
2074                FillRule::EvenOdd as u8,
2075                std::ptr::from_mut(&mut result),
2076            ),
2077            KnipsaStatus::Ok
2078        );
2079        knipsa_free_paths_d(std::ptr::from_mut(&mut result));
2080
2081        let subjects = [subject_path, clip_path];
2082        assert_eq!(
2083            knipsa_boolean_d(
2084                subjects.as_ptr(),
2085                subjects.len(),
2086                std::ptr::from_ref(&tiny_path),
2087                1,
2088                ClipType::Union as u8,
2089                FillRule::EvenOdd as u8,
2090                std::ptr::from_mut(&mut result),
2091            ),
2092            KnipsaStatus::Ok
2093        );
2094        knipsa_free_paths_d(std::ptr::from_mut(&mut result));
2095
2096        let large_triangle = [
2097            KnipsaPointD { x: 2_000_000.0, y: 0.0 },
2098            KnipsaPointD { x: 2_000_010.0, y: 0.0 },
2099            KnipsaPointD { x: 2_000_000.0, y: 10.0 },
2100        ];
2101        let large_path =
2102            KnipsaPathD { points: large_triangle.as_ptr(), point_count: large_triangle.len() };
2103        let subjects = [large_path, subject_path];
2104        assert_eq!(
2105            knipsa_boolean_d(
2106                subjects.as_ptr(),
2107                subjects.len(),
2108                std::ptr::null(),
2109                0,
2110                ClipType::Union as u8,
2111                FillRule::EvenOdd as u8,
2112                std::ptr::from_mut(&mut result),
2113            ),
2114            KnipsaStatus::Ok
2115        );
2116        knipsa_free_paths_d(std::ptr::from_mut(&mut result));
2117        assert_eq!(
2118            knipsa_boolean_d(
2119                std::ptr::from_ref(&large_path),
2120                1,
2121                std::ptr::from_ref(&subject_path),
2122                1,
2123                ClipType::Union as u8,
2124                FillRule::EvenOdd as u8,
2125                std::ptr::from_mut(&mut result),
2126            ),
2127            KnipsaStatus::Ok
2128        );
2129        knipsa_free_paths_d(std::ptr::from_mut(&mut result));
2130
2131        // Disjoint operand sets are only returned directly when every path in
2132        // each set is also mutually disjoint. Exercise both conservative
2133        // fallbacks through the independently instrumented FFI dependency.
2134        let far_square = [
2135            KnipsaPointD { x: 100.0, y: 100.0 },
2136            KnipsaPointD { x: 110.0, y: 100.0 },
2137            KnipsaPointD { x: 110.0, y: 110.0 },
2138            KnipsaPointD { x: 100.0, y: 110.0 },
2139        ];
2140        let far_path = KnipsaPathD { points: far_square.as_ptr(), point_count: far_square.len() };
2141        let overlapping = [subject_path, clip_path];
2142        assert_eq!(
2143            knipsa_boolean_d(
2144                overlapping.as_ptr(),
2145                overlapping.len(),
2146                std::ptr::from_ref(&far_path),
2147                1,
2148                ClipType::Union as u8,
2149                FillRule::EvenOdd as u8,
2150                std::ptr::from_mut(&mut result),
2151            ),
2152            KnipsaStatus::Ok
2153        );
2154        knipsa_free_paths_d(std::ptr::from_mut(&mut result));
2155        assert_eq!(
2156            knipsa_boolean_d(
2157                std::ptr::from_ref(&far_path),
2158                1,
2159                overlapping.as_ptr(),
2160                overlapping.len(),
2161                ClipType::Union as u8,
2162                FillRule::EvenOdd as u8,
2163                std::ptr::from_mut(&mut result),
2164            ),
2165            KnipsaStatus::Ok
2166        );
2167        knipsa_free_paths_d(std::ptr::from_mut(&mut result));
2168    }
2169
2170    #[test]
2171    #[allow(clippy::too_many_lines)]
2172    fn executes_simplification_and_rectangle_clipping() {
2173        let integer_path = KnipsaPath64 { points: TRIANGLE.as_ptr(), point_count: 3 };
2174        let mut simplified = KnipsaPaths64::default();
2175        assert_eq!(
2176            knipsa_simplify64(
2177                std::ptr::from_ref(&integer_path),
2178                1,
2179                FillRule::EvenOdd as u8,
2180                std::ptr::from_mut(&mut simplified),
2181            ),
2182            KnipsaStatus::Ok
2183        );
2184        assert_eq!(simplified.path_count, 1);
2185        knipsa_free_paths64(std::ptr::from_mut(&mut simplified));
2186
2187        assert_eq!(
2188            knipsa_clip_to_rect64(
2189                std::ptr::from_ref(&integer_path),
2190                1,
2191                KnipsaRect64 { min_x: 0, min_y: 0, max_x: 5, max_y: 5 },
2192                FillRule::EvenOdd as u8,
2193                std::ptr::from_mut(&mut simplified),
2194            ),
2195            KnipsaStatus::Ok
2196        );
2197        assert_eq!(simplified.path_count, 1);
2198        knipsa_free_paths64(std::ptr::from_mut(&mut simplified));
2199
2200        let double_path = KnipsaPathD { points: TRIANGLE_D.as_ptr(), point_count: 3 };
2201        let mut simplified_d = KnipsaPathsD::default();
2202        assert_eq!(
2203            knipsa_simplify_d(
2204                std::ptr::from_ref(&double_path),
2205                1,
2206                FillRule::EvenOdd as u8,
2207                std::ptr::from_mut(&mut simplified_d),
2208            ),
2209            KnipsaStatus::Ok
2210        );
2211        assert_eq!(simplified_d.path_count, 1);
2212        knipsa_free_paths_d(std::ptr::from_mut(&mut simplified_d));
2213
2214        assert_eq!(
2215            knipsa_clip_to_rect_d(
2216                std::ptr::from_ref(&double_path),
2217                1,
2218                KnipsaRectD { min_x: 0.0, min_y: 0.0, max_x: 5.0, max_y: 5.0 },
2219                FillRule::EvenOdd as u8,
2220                std::ptr::from_mut(&mut simplified_d),
2221            ),
2222            KnipsaStatus::Ok
2223        );
2224        assert_eq!(simplified_d.path_count, 1);
2225        knipsa_free_paths_d(std::ptr::from_mut(&mut simplified_d));
2226
2227        assert_eq!(
2228            knipsa_simplify64(std::ptr::null(), 0, 99, std::ptr::from_mut(&mut simplified),),
2229            KnipsaStatus::InvalidArgument
2230        );
2231        assert_eq!(
2232            knipsa_simplify_d(std::ptr::null(), 0, 99, std::ptr::from_mut(&mut simplified_d),),
2233            KnipsaStatus::InvalidArgument
2234        );
2235        assert_eq!(
2236            knipsa_clip_to_rect64(
2237                std::ptr::null(),
2238                0,
2239                KnipsaRect64::default(),
2240                99,
2241                std::ptr::from_mut(&mut simplified),
2242            ),
2243            KnipsaStatus::InvalidArgument
2244        );
2245        assert_eq!(
2246            knipsa_clip_to_rect_d(
2247                std::ptr::null(),
2248                0,
2249                KnipsaRectD::default(),
2250                99,
2251                std::ptr::from_mut(&mut simplified_d),
2252            ),
2253            KnipsaStatus::InvalidArgument
2254        );
2255        assert_eq!(
2256            knipsa_clip_to_rect_d(
2257                std::ptr::null(),
2258                0,
2259                KnipsaRectD { min_x: f64::NAN, ..KnipsaRectD::default() },
2260                FillRule::EvenOdd as u8,
2261                std::ptr::from_mut(&mut simplified_d),
2262            ),
2263            KnipsaStatus::NonFiniteCoordinate
2264        );
2265        assert_eq!(
2266            knipsa_simplify64(std::ptr::null(), 0, FillRule::EvenOdd as u8, std::ptr::null_mut(),),
2267            KnipsaStatus::NullPointer
2268        );
2269        assert_eq!(
2270            knipsa_simplify_d(std::ptr::null(), 0, FillRule::EvenOdd as u8, std::ptr::null_mut(),),
2271            KnipsaStatus::NullPointer
2272        );
2273        assert_eq!(
2274            knipsa_clip_to_rect64(
2275                std::ptr::null(),
2276                0,
2277                KnipsaRect64::default(),
2278                FillRule::EvenOdd as u8,
2279                std::ptr::null_mut(),
2280            ),
2281            KnipsaStatus::NullPointer
2282        );
2283        assert_eq!(
2284            knipsa_clip_to_rect_d(
2285                std::ptr::null(),
2286                0,
2287                KnipsaRectD::default(),
2288                FillRule::EvenOdd as u8,
2289                std::ptr::null_mut(),
2290            ),
2291            KnipsaStatus::NullPointer
2292        );
2293
2294        simplified.path_count = 1;
2295        assert_eq!(
2296            knipsa_simplify64(
2297                std::ptr::null(),
2298                0,
2299                FillRule::EvenOdd as u8,
2300                std::ptr::from_mut(&mut simplified),
2301            ),
2302            KnipsaStatus::InvalidArgument
2303        );
2304        assert_eq!(
2305            knipsa_clip_to_rect64(
2306                std::ptr::null(),
2307                0,
2308                KnipsaRect64::default(),
2309                FillRule::EvenOdd as u8,
2310                std::ptr::from_mut(&mut simplified),
2311            ),
2312            KnipsaStatus::InvalidArgument
2313        );
2314        simplified = KnipsaPaths64::default();
2315        simplified_d.path_count = 1;
2316        assert_eq!(
2317            knipsa_simplify_d(
2318                std::ptr::null(),
2319                0,
2320                FillRule::EvenOdd as u8,
2321                std::ptr::from_mut(&mut simplified_d),
2322            ),
2323            KnipsaStatus::InvalidArgument
2324        );
2325        assert_eq!(
2326            knipsa_clip_to_rect_d(
2327                std::ptr::null(),
2328                0,
2329                KnipsaRectD::default(),
2330                FillRule::EvenOdd as u8,
2331                std::ptr::from_mut(&mut simplified_d),
2332            ),
2333            KnipsaStatus::InvalidArgument
2334        );
2335        simplified_d = KnipsaPathsD::default();
2336
2337        let short64 = KnipsaPath64 { points: TRIANGLE.as_ptr(), point_count: 2 };
2338        let short_d = KnipsaPathD { points: TRIANGLE_D.as_ptr(), point_count: 2 };
2339        assert_eq!(
2340            knipsa_simplify64(
2341                std::ptr::from_ref(&short64),
2342                1,
2343                FillRule::EvenOdd as u8,
2344                std::ptr::from_mut(&mut simplified),
2345            ),
2346            KnipsaStatus::InvalidPath
2347        );
2348        assert_eq!(
2349            knipsa_simplify_d(
2350                std::ptr::from_ref(&short_d),
2351                1,
2352                FillRule::EvenOdd as u8,
2353                std::ptr::from_mut(&mut simplified_d),
2354            ),
2355            KnipsaStatus::InvalidPath
2356        );
2357        assert_eq!(
2358            knipsa_clip_to_rect64(
2359                std::ptr::from_ref(&short64),
2360                1,
2361                KnipsaRect64 { min_x: 0, min_y: 0, max_x: 5, max_y: 5 },
2362                FillRule::EvenOdd as u8,
2363                std::ptr::from_mut(&mut simplified),
2364            ),
2365            KnipsaStatus::InvalidPath
2366        );
2367        assert_eq!(
2368            knipsa_clip_to_rect_d(
2369                std::ptr::from_ref(&short_d),
2370                1,
2371                KnipsaRectD { min_x: 0.0, min_y: 0.0, max_x: 5.0, max_y: 5.0 },
2372                FillRule::EvenOdd as u8,
2373                std::ptr::from_mut(&mut simplified_d),
2374            ),
2375            KnipsaStatus::InvalidPath
2376        );
2377    }
2378
2379    #[test]
2380    fn executes_offsets_and_triangulation() {
2381        let square = [
2382            KnipsaPointD { x: 0.0, y: 0.0 },
2383            KnipsaPointD { x: 10.0, y: 0.0 },
2384            KnipsaPointD { x: 10.0, y: 10.0 },
2385            KnipsaPointD { x: 0.0, y: 10.0 },
2386        ];
2387        let square_path = KnipsaPathD { points: square.as_ptr(), point_count: square.len() };
2388        let mut offset = KnipsaPathsD::default();
2389        let offset_options = KnipsaOffsetOptions {
2390            join_type: KnipsaJoinType::Miter as u8,
2391            ..KnipsaOffsetOptions::default()
2392        };
2393        assert_eq!(
2394            knipsa_offset_d(
2395                std::ptr::from_ref(&square_path),
2396                1,
2397                1.0,
2398                std::ptr::from_ref(&offset_options),
2399                std::ptr::from_mut(&mut offset),
2400            ),
2401            KnipsaStatus::Ok
2402        );
2403        assert_eq!(offset.path_count, 1);
2404        // SAFETY: The output was allocated by the offset function and the
2405        // descriptor count was checked above.
2406        unsafe {
2407            assert!(slice::from_raw_parts(offset.paths, offset.path_count)[0].point_count >= 4);
2408        }
2409        knipsa_free_paths_d(std::ptr::from_mut(&mut offset));
2410
2411        let integer_path = KnipsaPath64 { points: TRIANGLE.as_ptr(), point_count: TRIANGLE.len() };
2412        let mut integer_offset = KnipsaPathsD::default();
2413        let offset_options = KnipsaOffsetOptions {
2414            join_type: KnipsaJoinType::Round as u8,
2415            ..KnipsaOffsetOptions::default()
2416        };
2417        assert_eq!(
2418            knipsa_offset64(
2419                std::ptr::from_ref(&integer_path),
2420                1,
2421                1.0,
2422                std::ptr::from_ref(&offset_options),
2423                std::ptr::from_mut(&mut integer_offset),
2424            ),
2425            KnipsaStatus::Ok
2426        );
2427        assert_eq!(integer_offset.path_count, 1);
2428        // `knipsa_offset64` returns the floating-point outline directly; a
2429        // round join must retain at least one non-integral vertex.
2430        // SAFETY: The output was allocated by the offset function and the
2431        // descriptor count was checked above.
2432        unsafe {
2433            let descriptor =
2434                &slice::from_raw_parts(integer_offset.paths, integer_offset.path_count)[0];
2435            let points = slice::from_raw_parts(descriptor.points, descriptor.point_count);
2436            assert!(
2437                points
2438                    .iter()
2439                    .any(|point| { point.x.fract().abs() > 1e-9 || point.y.fract().abs() > 1e-9 })
2440            );
2441        }
2442        knipsa_free_paths_d(std::ptr::from_mut(&mut integer_offset));
2443
2444        let mut triangles = KnipsaPaths64::default();
2445        assert_eq!(
2446            knipsa_triangulate64(
2447                std::ptr::from_ref(&integer_path),
2448                1,
2449                FillRule::NonZero as u8,
2450                std::ptr::from_mut(&mut triangles),
2451            ),
2452            KnipsaStatus::Ok
2453        );
2454        assert_eq!(triangles.path_count, 1);
2455        // SAFETY: The output was allocated by the triangulation function.
2456        unsafe {
2457            assert_eq!(
2458                slice::from_raw_parts(triangles.paths, triangles.path_count)[0].point_count,
2459                3
2460            );
2461        }
2462        knipsa_free_paths64(std::ptr::from_mut(&mut triangles));
2463
2464        let mut triangles_d = KnipsaPathsD::default();
2465        assert_eq!(
2466            knipsa_triangulate_d(
2467                std::ptr::from_ref(&square_path),
2468                1,
2469                FillRule::EvenOdd as u8,
2470                std::ptr::from_mut(&mut triangles_d),
2471            ),
2472            KnipsaStatus::Ok
2473        );
2474        assert_eq!(triangles_d.path_count, 2);
2475        knipsa_free_paths_d(std::ptr::from_mut(&mut triangles_d));
2476    }
2477
2478    #[test]
2479    #[allow(clippy::too_many_lines)]
2480    fn covers_offset_and_triangulation_error_paths() {
2481        for join_type in 0..=3 {
2482            for end_type in 0..=4 {
2483                assert!(offset_options_from_u8(join_type, end_type, 2.0, 0.0, 1).is_some());
2484            }
2485        }
2486
2487        let invalid_64 = KnipsaPath64 { points: TRIANGLE.as_ptr(), point_count: 2 };
2488        let invalid_d = KnipsaPathD { points: TRIANGLE_D.as_ptr(), point_count: 2 };
2489        let mut result_d = KnipsaPathsD::default();
2490        let mut offset_options = KnipsaOffsetOptions::default();
2491        assert_eq!(
2492            knipsa_offset64(
2493                std::ptr::null(),
2494                0,
2495                1.0,
2496                std::ptr::from_ref(&offset_options),
2497                std::ptr::null_mut(),
2498            ),
2499            KnipsaStatus::NullPointer
2500        );
2501        offset_options.join_type = 99;
2502        assert_eq!(
2503            knipsa_offset64(
2504                std::ptr::null(),
2505                0,
2506                1.0,
2507                std::ptr::from_ref(&offset_options),
2508                std::ptr::from_mut(&mut result_d),
2509            ),
2510            KnipsaStatus::InvalidArgument
2511        );
2512        offset_options.join_type = KnipsaJoinType::Round as u8;
2513        assert_eq!(
2514            knipsa_offset64(
2515                std::ptr::from_ref(&invalid_64),
2516                1,
2517                1.0,
2518                std::ptr::from_ref(&offset_options),
2519                std::ptr::from_mut(&mut result_d),
2520            ),
2521            KnipsaStatus::InvalidPath
2522        );
2523        assert_eq!(
2524            knipsa_offset_d(
2525                std::ptr::from_ref(&invalid_d),
2526                1,
2527                1.0,
2528                std::ptr::from_ref(&offset_options),
2529                std::ptr::from_mut(&mut result_d),
2530            ),
2531            KnipsaStatus::InvalidPath
2532        );
2533
2534        let mut result_64 = KnipsaPaths64::default();
2535        assert_eq!(
2536            knipsa_triangulate64(
2537                std::ptr::null(),
2538                0,
2539                FillRule::EvenOdd as u8,
2540                std::ptr::null_mut()
2541            ),
2542            KnipsaStatus::NullPointer
2543        );
2544        assert_eq!(
2545            knipsa_triangulate64(
2546                std::ptr::from_ref(&invalid_64),
2547                1,
2548                FillRule::EvenOdd as u8,
2549                std::ptr::from_mut(&mut result_64),
2550            ),
2551            KnipsaStatus::InvalidPath
2552        );
2553        assert_eq!(
2554            knipsa_triangulate_d(std::ptr::null(), 0, 99, std::ptr::from_mut(&mut result_d),),
2555            KnipsaStatus::InvalidArgument
2556        );
2557        assert_eq!(
2558            knipsa_triangulate_d(
2559                std::ptr::from_ref(&invalid_d),
2560                1,
2561                FillRule::EvenOdd as u8,
2562                std::ptr::from_mut(&mut result_d),
2563            ),
2564            KnipsaStatus::InvalidPath
2565        );
2566
2567        let oversized_64 = KnipsaPath64 {
2568            points: std::ptr::null(),
2569            point_count: ComplexityLimits::DEFAULT.max_vertices() + 1,
2570        };
2571        assert_eq!(
2572            knipsa_triangulate64(
2573                std::ptr::from_ref(&oversized_64),
2574                1,
2575                FillRule::EvenOdd as u8,
2576                std::ptr::from_mut(&mut result_64),
2577            ),
2578            KnipsaStatus::InvalidArgument
2579        );
2580        let oversized_d = KnipsaPathD {
2581            points: std::ptr::null(),
2582            point_count: ComplexityLimits::DEFAULT.max_vertices() + 1,
2583        };
2584        assert_eq!(
2585            knipsa_triangulate_d(
2586                std::ptr::from_ref(&oversized_d),
2587                1,
2588                FillRule::EvenOdd as u8,
2589                std::ptr::from_mut(&mut result_d),
2590            ),
2591            KnipsaStatus::InvalidArgument
2592        );
2593        assert_eq!(
2594            knipsa_triangulate64(
2595                std::ptr::NonNull::<KnipsaPath64>::dangling().as_ptr(),
2596                ComplexityLimits::DEFAULT.max_paths() + 1,
2597                FillRule::EvenOdd as u8,
2598                std::ptr::from_mut(&mut result_64),
2599            ),
2600            KnipsaStatus::InvalidArgument
2601        );
2602
2603        FORCE_BOOLEAN_PANIC.with(|panic| panic.set(true));
2604        assert_eq!(
2605            knipsa_offset64(
2606                std::ptr::null(),
2607                0,
2608                1.0,
2609                std::ptr::from_ref(&offset_options),
2610                std::ptr::from_mut(&mut result_d),
2611            ),
2612            KnipsaStatus::InternalError
2613        );
2614        assert_eq!(
2615            knipsa_offset_d(
2616                std::ptr::null(),
2617                0,
2618                1.0,
2619                std::ptr::from_ref(&offset_options),
2620                std::ptr::from_mut(&mut result_d),
2621            ),
2622            KnipsaStatus::InternalError
2623        );
2624        assert_eq!(
2625            knipsa_triangulate64(
2626                std::ptr::null(),
2627                0,
2628                FillRule::EvenOdd as u8,
2629                std::ptr::from_mut(&mut result_64),
2630            ),
2631            KnipsaStatus::InternalError
2632        );
2633        assert_eq!(
2634            knipsa_triangulate_d(
2635                std::ptr::null(),
2636                0,
2637                FillRule::EvenOdd as u8,
2638                std::ptr::from_mut(&mut result_d),
2639            ),
2640            KnipsaStatus::InternalError
2641        );
2642        assert_eq!(
2643            knipsa_simplify64(
2644                std::ptr::null(),
2645                0,
2646                FillRule::EvenOdd as u8,
2647                std::ptr::from_mut(&mut result_64),
2648            ),
2649            KnipsaStatus::InternalError
2650        );
2651        assert_eq!(
2652            knipsa_simplify_d(
2653                std::ptr::null(),
2654                0,
2655                FillRule::EvenOdd as u8,
2656                std::ptr::from_mut(&mut result_d),
2657            ),
2658            KnipsaStatus::InternalError
2659        );
2660        assert_eq!(
2661            knipsa_clip_to_rect64(
2662                std::ptr::null(),
2663                0,
2664                KnipsaRect64::default(),
2665                FillRule::EvenOdd as u8,
2666                std::ptr::from_mut(&mut result_64),
2667            ),
2668            KnipsaStatus::InternalError
2669        );
2670        assert_eq!(
2671            knipsa_clip_to_rect_d(
2672                std::ptr::null(),
2673                0,
2674                KnipsaRectD::default(),
2675                FillRule::EvenOdd as u8,
2676                std::ptr::from_mut(&mut result_d),
2677            ),
2678            KnipsaStatus::InternalError
2679        );
2680        FORCE_BOOLEAN_PANIC.with(|panic| panic.set(false));
2681    }
2682
2683    #[test]
2684    fn offset_preflight_rejects_oversized_descriptors() {
2685        let mut offset = KnipsaPathsD::default();
2686        let oversized_64 = KnipsaPath64 {
2687            points: std::ptr::null(),
2688            point_count: ComplexityLimits::DEFAULT.max_vertices() + 1,
2689        };
2690        assert_eq!(
2691            knipsa_offset64(
2692                std::ptr::from_ref(&oversized_64),
2693                1,
2694                1.0,
2695                std::ptr::from_ref(&KnipsaOffsetOptions::default()),
2696                std::ptr::from_mut(&mut offset),
2697            ),
2698            KnipsaStatus::InvalidArgument
2699        );
2700        let oversized_d = KnipsaPathD {
2701            points: std::ptr::null(),
2702            point_count: ComplexityLimits::DEFAULT.max_vertices() + 1,
2703        };
2704        assert_eq!(
2705            knipsa_offset_d(
2706                std::ptr::from_ref(&oversized_d),
2707                1,
2708                1.0,
2709                std::ptr::from_ref(&KnipsaOffsetOptions::default()),
2710                std::ptr::from_mut(&mut offset),
2711            ),
2712            KnipsaStatus::InvalidArgument
2713        );
2714    }
2715
2716    #[test]
2717    fn rejects_bad_offset_and_triangulation_arguments() {
2718        assert_eq!(
2719            check_ffi_complexity::<KnipsaPath64>(
2720                std::ptr::null(),
2721                1,
2722                ComplexityLimits::DEFAULT,
2723                |path| path.point_count,
2724            ),
2725            Err(KnipsaStatus::NullPointer)
2726        );
2727        assert_eq!(
2728            check_ffi_complexity::<KnipsaPath64>(
2729                std::ptr::null(),
2730                0,
2731                ComplexityLimits::DEFAULT,
2732                |path| path.point_count,
2733            ),
2734            Ok(())
2735        );
2736        assert_eq!(offset_options_from_u8(99, 0, 2.0, 0.0, 0), None);
2737        assert_eq!(offset_options_from_u8(0, 99, 2.0, 0.0, 0), None);
2738        assert!(offset_options_from_u8(0, 0, 2.0, 0.0, 1).is_some());
2739        let invalid_options =
2740            KnipsaOffsetOptions { join_type: 99, ..KnipsaOffsetOptions::default() };
2741        let reserved_options =
2742            KnipsaOffsetOptions { reserved: 1, ..KnipsaOffsetOptions::default() };
2743        let mut offset = KnipsaPathsD::default();
2744        assert_eq!(
2745            knipsa_offset_d(
2746                std::ptr::null(),
2747                0,
2748                1.0,
2749                std::ptr::from_ref(&invalid_options),
2750                std::ptr::from_mut(&mut offset),
2751            ),
2752            KnipsaStatus::InvalidArgument
2753        );
2754        assert_eq!(
2755            knipsa_offset_d(
2756                std::ptr::null(),
2757                0,
2758                1.0,
2759                std::ptr::null(),
2760                std::ptr::from_mut(&mut offset),
2761            ),
2762            KnipsaStatus::NullPointer
2763        );
2764        assert_eq!(
2765            knipsa_offset_d(
2766                std::ptr::null(),
2767                0,
2768                1.0,
2769                std::ptr::from_ref(&reserved_options),
2770                std::ptr::from_mut(&mut offset),
2771            ),
2772            KnipsaStatus::InvalidArgument
2773        );
2774        assert_eq!(
2775            knipsa_offset_d(
2776                std::ptr::null(),
2777                0,
2778                1.0,
2779                std::ptr::from_ref(&KnipsaOffsetOptions::default()),
2780                std::ptr::null_mut(),
2781            ),
2782            KnipsaStatus::NullPointer
2783        );
2784        let mut triangles = KnipsaPaths64::default();
2785        assert_eq!(
2786            knipsa_triangulate64(std::ptr::null(), 0, 99, std::ptr::from_mut(&mut triangles),),
2787            KnipsaStatus::InvalidArgument
2788        );
2789        assert_eq!(
2790            knipsa_triangulate_d(
2791                std::ptr::null(),
2792                0,
2793                FillRule::EvenOdd as u8,
2794                std::ptr::null_mut(),
2795            ),
2796            KnipsaStatus::NullPointer
2797        );
2798    }
2799
2800    #[test]
2801    #[allow(clippy::too_many_lines)]
2802    fn rejects_bad_boolean_arguments_and_pointers() {
2803        assert_eq!(copy_paths_d(std::ptr::null(), 1), Err(KnipsaStatus::NullPointer));
2804        assert_eq!(clip_type_from_u8(1), Some(ClipType::Intersection));
2805        assert_eq!(clip_type_from_u8(2), Some(ClipType::Union));
2806        assert_eq!(clip_type_from_u8(3), Some(ClipType::Difference));
2807        assert_eq!(clip_type_from_u8(4), Some(ClipType::Xor));
2808        assert_eq!(fill_rule_from_u8(0), Some(FillRule::EvenOdd));
2809        assert_eq!(fill_rule_from_u8(1), Some(FillRule::NonZero));
2810        assert_eq!(fill_rule_from_u8(2), Some(FillRule::Positive));
2811        assert_eq!(fill_rule_from_u8(3), Some(FillRule::Negative));
2812
2813        let mut result = KnipsaPaths64::default();
2814        assert_eq!(
2815            knipsa_boolean64(
2816                std::ptr::null(),
2817                0,
2818                std::ptr::null(),
2819                0,
2820                99,
2821                FillRule::EvenOdd as u8,
2822                std::ptr::from_mut(&mut result),
2823            ),
2824            KnipsaStatus::InvalidArgument
2825        );
2826        assert_eq!(
2827            knipsa_boolean64(
2828                std::ptr::null(),
2829                0,
2830                std::ptr::null(),
2831                0,
2832                ClipType::Union as u8,
2833                99,
2834                std::ptr::from_mut(&mut result),
2835            ),
2836            KnipsaStatus::InvalidArgument
2837        );
2838        assert_eq!(
2839            knipsa_boolean64(
2840                std::ptr::null(),
2841                1,
2842                std::ptr::null(),
2843                0,
2844                ClipType::Union as u8,
2845                FillRule::EvenOdd as u8,
2846                std::ptr::from_mut(&mut result),
2847            ),
2848            KnipsaStatus::NullPointer
2849        );
2850
2851        let mut result_d = KnipsaPathsD::default();
2852        assert_eq!(
2853            knipsa_boolean_d(
2854                std::ptr::null(),
2855                0,
2856                std::ptr::null(),
2857                0,
2858                99,
2859                FillRule::EvenOdd as u8,
2860                std::ptr::from_mut(&mut result_d),
2861            ),
2862            KnipsaStatus::InvalidArgument
2863        );
2864        assert_eq!(
2865            knipsa_boolean_d(
2866                std::ptr::null(),
2867                0,
2868                std::ptr::null(),
2869                0,
2870                ClipType::Union as u8,
2871                99,
2872                std::ptr::from_mut(&mut result_d),
2873            ),
2874            KnipsaStatus::InvalidArgument
2875        );
2876        assert_eq!(
2877            knipsa_boolean_d(
2878                std::ptr::null(),
2879                1,
2880                std::ptr::null(),
2881                0,
2882                ClipType::Union as u8,
2883                FillRule::EvenOdd as u8,
2884                std::ptr::from_mut(&mut result_d),
2885            ),
2886            KnipsaStatus::NullPointer
2887        );
2888        assert_eq!(
2889            knipsa_boolean_d(
2890                std::ptr::null(),
2891                0,
2892                std::ptr::null(),
2893                0,
2894                ClipType::Union as u8,
2895                FillRule::EvenOdd as u8,
2896                std::ptr::null_mut(),
2897            ),
2898            KnipsaStatus::NullPointer
2899        );
2900        let bad_point = [
2901            KnipsaPointD { x: f64::NAN, y: 0.0 },
2902            KnipsaPointD { x: 1.0, y: 0.0 },
2903            KnipsaPointD { x: 0.0, y: 1.0 },
2904        ];
2905        let bad_path = KnipsaPathD { points: bad_point.as_ptr(), point_count: 3 };
2906        assert_eq!(
2907            knipsa_boolean_d(
2908                std::ptr::from_ref(&bad_path),
2909                1,
2910                std::ptr::null(),
2911                0,
2912                ClipType::Union as u8,
2913                FillRule::EvenOdd as u8,
2914                std::ptr::from_mut(&mut result_d),
2915            ),
2916            KnipsaStatus::NonFiniteCoordinate
2917        );
2918        let bad_integer_point = [KnipsaPoint64 { x: 0, y: 0 }];
2919        let bad_integer_path = KnipsaPath64 {
2920            points: bad_integer_point.as_ptr(),
2921            point_count: bad_integer_point.len(),
2922        };
2923        assert_eq!(
2924            knipsa_boolean64(
2925                std::ptr::from_ref(&bad_integer_path),
2926                1,
2927                std::ptr::null(),
2928                0,
2929                ClipType::Union as u8,
2930                FillRule::EvenOdd as u8,
2931                std::ptr::from_mut(&mut result),
2932            ),
2933            KnipsaStatus::InvalidPath
2934        );
2935        assert_eq!(
2936            knipsa_boolean64(
2937                std::ptr::null(),
2938                0,
2939                std::ptr::null(),
2940                0,
2941                ClipType::Union as u8,
2942                FillRule::EvenOdd as u8,
2943                std::ptr::null_mut(),
2944            ),
2945            KnipsaStatus::NullPointer
2946        );
2947
2948        let empty_d = KnipsaPathD { points: std::ptr::null(), point_count: 0 };
2949        assert_eq!(copy_paths_d(std::ptr::from_ref(&empty_d), 1).unwrap().len(), 1);
2950        assert_eq!(
2951            copy_paths_d(
2952                std::ptr::from_ref(&KnipsaPathD { points: std::ptr::null(), point_count: 1 }),
2953                1,
2954            ),
2955            Err(KnipsaStatus::NullPointer)
2956        );
2957        let empty_64_result = {
2958            let mut output = KnipsaPaths64::default();
2959            let status = knipsa_boolean64(
2960                std::ptr::null(),
2961                0,
2962                std::ptr::null(),
2963                0,
2964                ClipType::Union as u8,
2965                FillRule::EvenOdd as u8,
2966                std::ptr::from_mut(&mut output),
2967            );
2968            assert_eq!(status, KnipsaStatus::Ok);
2969            output
2970        };
2971        assert_eq!(empty_64_result, KnipsaPaths64::default());
2972        let mut empty_d_result = KnipsaPathsD::default();
2973        assert_eq!(
2974            knipsa_boolean_d(
2975                std::ptr::null(),
2976                0,
2977                std::ptr::null(),
2978                0,
2979                ClipType::Union as u8,
2980                FillRule::EvenOdd as u8,
2981                std::ptr::from_mut(&mut empty_d_result),
2982            ),
2983            KnipsaStatus::Ok
2984        );
2985        assert_eq!(empty_d_result, KnipsaPathsD::default());
2986
2987        FORCE_BOOLEAN_PANIC.with(|panic| panic.set(true));
2988        let mut panic_result = KnipsaPaths64::default();
2989        assert_eq!(
2990            knipsa_boolean64(
2991                std::ptr::null(),
2992                0,
2993                std::ptr::null(),
2994                0,
2995                ClipType::Union as u8,
2996                FillRule::EvenOdd as u8,
2997                std::ptr::from_mut(&mut panic_result),
2998            ),
2999            KnipsaStatus::InternalError
3000        );
3001        let mut panic_result_d = KnipsaPathsD::default();
3002        assert_eq!(
3003            knipsa_boolean_d(
3004                std::ptr::null(),
3005                0,
3006                std::ptr::null(),
3007                0,
3008                ClipType::Union as u8,
3009                FillRule::EvenOdd as u8,
3010                std::ptr::from_mut(&mut panic_result_d),
3011            ),
3012            KnipsaStatus::InternalError
3013        );
3014        FORCE_BOOLEAN_PANIC.with(|panic| panic.set(false));
3015
3016        let descriptors_64 =
3017            vec![KnipsaPath64 { points: std::ptr::null(), point_count: 0 }].into_boxed_slice();
3018        let mut owned_64 = KnipsaPaths64 {
3019            paths: Box::into_raw(descriptors_64).cast::<KnipsaPath64>(),
3020            path_count: 1,
3021        };
3022        knipsa_free_paths64(std::ptr::from_mut(&mut owned_64));
3023        assert_eq!(owned_64, KnipsaPaths64::default());
3024        let descriptors_d =
3025            vec![KnipsaPathD { points: std::ptr::null(), point_count: 0 }].into_boxed_slice();
3026        let mut owned_d = KnipsaPathsD {
3027            paths: Box::into_raw(descriptors_d).cast::<KnipsaPathD>(),
3028            path_count: 1,
3029        };
3030        knipsa_free_paths_d(std::ptr::from_mut(&mut owned_d));
3031        assert_eq!(owned_d, KnipsaPathsD::default());
3032    }
3033}