geo-repair 0.13.0

Fix invalid GIS geometries in parallel using rewritten GEOS/JTS repair module
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//! C-compatible FFI bindings for geo-repair.
//!
//! Enable the `ffi` feature for a C-compatible API using WKB.
//!
//! # C header
//!
//! ```c
//! #include <stdint.h>
//! #include <stdbool.h>
//!
//! typedef struct {
//!     bool      success;
//!     uint8_t*  wkb_data;
//!     size_t    wkb_len;
//!     char*     error_msg;
//! } GeoRepairResult;
//!
//! // --- Repair ---
//! GeoRepairResult geo_repair_make_valid(const uint8_t* wkb_data, size_t wkb_len);
//! GeoRepairResult geo_repair_make_valid_with_config(
//!     const uint8_t* wkb_data, size_t wkb_len,
//!     bool keep_collapsed, uint8_t poly_method);
//! GeoRepairResult geo_repair_make_valid_with_config_full(
//!     const uint8_t* wkb_data, size_t wkb_len,
//!     bool keep_collapsed, uint8_t poly_method,
//!     uint8_t fill_rule, int32_t epsg_code);
//!
//! // --- Validation ---
//! uint8_t         geo_repair_is_valid(const uint8_t* wkb_data, size_t wkb_len);
//! GeoRepairResult geo_repair_validate(const uint8_t* wkb_data, size_t wkb_len);
//! GeoRepairResult geo_repair_validate_reason(const uint8_t* wkb_data, size_t wkb_len);
//!
//! // --- Combined validate + fix ---
//! // Returns fixed WKB on success.  error_msg is null when input was valid,
//! // or contains validation errors when input was invalid.
//! GeoRepairResult geo_repair_validate_and_fix(const uint8_t* wkb_data, size_t wkb_len);
//! GeoRepairResult geo_repair_validate_and_fix_with_config(
//!     const uint8_t* wkb_data, size_t wkb_len,
//!     bool keep_collapsed, uint8_t poly_method);
//!
//! // --- Memory management ---
//! void            geo_repair_free_result(GeoRepairResult* result);
//! ```
use std::ffi::{c_char, CString};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::ptr;

use crate::core::MakeValidConfig;
use crate::make_valid::MakeValid;
use crate::validation::GeoValidation;
use geo::Geometry;

/// Result returned by geo-repair C FFI functions.
///
/// On success, `wkb_data` / `wkb_len` contain the output WKB geometry
/// and `error_msg` is null.  On failure, `wkb_data` is null and
/// `error_msg` points to a NUL-terminated error string.
///
/// # Safety
///
/// The caller must call [`geo_repair_free_result`] to release the
/// allocated memory when the result is no longer needed.
#[repr(C)]
#[derive(Debug)]
pub struct GeoRepairResult {
    /// Whether the operation succeeded. When `true`, `wkb_data`/`wkb_len` are valid.
    pub success: bool,
    /// Pointer to the output WKB byte buffer (valid when `success` is true).
    pub wkb_data: *mut u8,
    /// Length of the output WKB buffer in bytes.
    pub wkb_len: usize,
    /// NUL-terminated error message string (non-null when `success` is false).
    pub error_msg: *mut c_char,
}

impl GeoRepairResult {
    fn success(wkb: Vec<u8>) -> Self {
        let mut wkb = wkb;
        wkb.shrink_to_fit();
        let len = wkb.len();
        let ptr = wkb.as_mut_ptr();
        std::mem::forget(wkb);
        Self {
            success: true,
            wkb_data: ptr,
            wkb_len: len,
            error_msg: ptr::null_mut(),
        }
    }

    fn error(msg: &str) -> Self {
        let c_msg = CString::new(msg).unwrap_or_default();
        Self {
            success: false,
            wkb_data: ptr::null_mut(),
            wkb_len: 0,
            error_msg: c_msg.into_raw(),
        }
    }
}

fn geometry_from_wkb(data: *const u8, len: usize) -> Result<Geometry<f64>, String> {
    if data.is_null() {
        return Err("null pointer".to_string());
    }
    if len == 0 || len > isize::MAX as usize {
        return Err("invalid length".to_string());
    }
    let buf = unsafe { std::slice::from_raw_parts(data, len) };
    let wkb_geom = wkb::reader::read_wkb(buf).map_err(|e| format!("WKB parse error: {e}"))?;
    let geo_geom = geo_traits::to_geo::ToGeoGeometry::to_geometry(&wkb_geom);
    Ok(geo_geom)
}

fn geometry_to_wkb(geom: &Geometry<f64>) -> Result<Vec<u8>, String> {
    use std::io::Cursor;
    use wkb::writer::{geometry_wkb_size, write_geometry, WriteOptions};

    let opts = WriteOptions::default();
    let size = geometry_wkb_size(geom);
    let mut buf = vec![0u8; size];
    write_geometry(&mut Cursor::new(&mut buf[..]), geom, &opts)
        .map_err(|e| format!("WKB write error: {e}"))?;
    Ok(buf)
}

/// Repair a geometry from WKB using default configuration.
///
/// # Safety
///
/// `wkb_data` must point to a valid WKB buffer of `wkb_len` bytes.
/// The returned [`GeoRepairResult`] must be freed with
/// [`geo_repair_free_result`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn geo_repair_make_valid(
    wkb_data: *const u8,
    wkb_len: usize,
) -> GeoRepairResult {
    match catch_unwind(AssertUnwindSafe(|| {
        let geom = match geometry_from_wkb(wkb_data, wkb_len) {
            Ok(g) => g,
            Err(e) => return GeoRepairResult::error(&e),
        };
        let fixed = geom.make_valid();
        match geometry_to_wkb(&fixed) {
            Ok(wkb) => GeoRepairResult::success(wkb),
            Err(e) => GeoRepairResult::error(&e),
        }
    })) {
        Ok(r) => r,
        Err(_) => GeoRepairResult::error("internal error: repair panicked"),
    }
}

/// Repair a geometry from WKB with configuration.
///
/// `poly_method`: 0 = Auto, 1 = Arrange, 2 = Structure.
///
/// # Safety
///
/// `wkb_data` must point to a valid WKB buffer of `wkb_len` bytes.
/// The returned [`GeoRepairResult`] must be freed with
/// [`geo_repair_free_result`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn geo_repair_make_valid_with_config(
    wkb_data: *const u8,
    wkb_len: usize,
    keep_collapsed: bool,
    poly_method: u8,
) -> GeoRepairResult {
    match catch_unwind(AssertUnwindSafe(|| {
        let geom = match geometry_from_wkb(wkb_data, wkb_len) {
            Ok(g) => g,
            Err(e) => return GeoRepairResult::error(&e),
        };
        let config = MakeValidConfig {
            keep_collapsed,
            poly_method: match poly_method {
                0 => crate::PolyMethod::Auto,
                1 => crate::PolyMethod::Arrange,
                2 => crate::PolyMethod::Structure,
                _ => crate::PolyMethod::Auto,
            },
            fill_rule: Default::default(),
            crs: None,
            target_crs: None,
        };
        let fixed = geom.make_valid_with_config(&config);
        match geometry_to_wkb(&fixed) {
            Ok(wkb) => GeoRepairResult::success(wkb),
            Err(e) => GeoRepairResult::error(&e),
        }
    })) {
        Ok(r) => r,
        Err(_) => GeoRepairResult::error("internal error: repair panicked"),
    }
}

/// Repair a geometry from WKB with full configuration.
///
/// `poly_method`: 0 = Auto, 1 = Arrange, 2 = Structure.
/// `fill_rule`: 0 = EvenOdd, 1 = NonZero.
///
/// # Safety
///
/// `wkb_data` must point to a valid WKB buffer of `wkb_len` bytes.
/// The returned [`GeoRepairResult`] must be freed with
/// [`geo_repair_free_result`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn geo_repair_make_valid_with_config_full(
    wkb_data: *const u8,
    wkb_len: usize,
    keep_collapsed: bool,
    poly_method: u8,
    fill_rule: u8,
    epsg_code: i32,
) -> GeoRepairResult {
    match catch_unwind(AssertUnwindSafe(|| {
        let geom = match geometry_from_wkb(wkb_data, wkb_len) {
            Ok(g) => g,
            Err(e) => return GeoRepairResult::error(&e),
        };
        let config = MakeValidConfig {
            keep_collapsed,
            poly_method: match poly_method {
                0 => crate::PolyMethod::Auto,
                1 => crate::PolyMethod::Arrange,
                2 => crate::PolyMethod::Structure,
                _ => crate::PolyMethod::Auto,
            },
            fill_rule: match fill_rule {
                0 => geo::algorithm::bool_ops::FillRule::EvenOdd,
                _ => geo::algorithm::bool_ops::FillRule::NonZero,
            },
            crs: if epsg_code > 0 {
                Some(crate::Crs::from_epsg(epsg_code as u32))
            } else {
                None
            },
            target_crs: None,
        };
        let fixed = geom.make_valid_with_config(&config);
        match geometry_to_wkb(&fixed) {
            Ok(wkb) => GeoRepairResult::success(wkb),
            Err(e) => GeoRepairResult::error(&e),
        }
    })) {
        Ok(r) => r,
        Err(_) => GeoRepairResult::error("internal error: repair panicked"),
    }
}

/// Check whether a WKB-encoded geometry is OGC-valid.
///
/// Returns 1 if valid, 0 if invalid, and sets `error_msg` on the result
/// when invalid to describe the violation.
///
/// # Safety
///
/// `wkb_data` must point to a valid WKB buffer of `wkb_len` bytes.
/// The returned [`GeoRepairResult`] must be freed with
/// [`geo_repair_free_result`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn geo_repair_is_valid(wkb_data: *const u8, wkb_len: usize) -> u8 {
    catch_unwind(AssertUnwindSafe(|| {
        let geom = match geometry_from_wkb(wkb_data, wkb_len) {
            Ok(g) => g,
            Err(_) => return 0,
        };
        if geom.is_valid() {
            1
        } else {
            0
        }
    }))
    .unwrap_or_default()
}

/// Validate a WKB-encoded geometry and return a human-readable reason.
///
/// # Safety
///
/// `wkb_data` must point to a valid WKB buffer of `wkb_len` bytes.
/// The returned string must be freed with [`geo_repair_free_result`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn geo_repair_validate_reason(
    wkb_data: *const u8,
    wkb_len: usize,
) -> GeoRepairResult {
    match catch_unwind(AssertUnwindSafe(|| {
        let geom = match geometry_from_wkb(wkb_data, wkb_len) {
            Ok(g) => g,
            Err(e) => return GeoRepairResult::error(&e),
        };
        if geom.is_valid() {
            GeoRepairResult::success(Vec::new())
        } else {
            let reason = geom.validate_reason();
            GeoRepairResult::error(&reason)
        }
    })) {
        Ok(r) => r,
        Err(_) => GeoRepairResult::error("internal error: validation panicked"),
    }
}

/// Validate a WKB-encoded geometry.
///
/// Returns a result with:
/// - `success = true` and `wkb_len == 0` when the geometry is valid.
/// - `success = false` and `error_msg` set to the violation reasons when invalid.
///
/// # Safety
///
/// `wkb_data` must point to a valid WKB buffer of `wkb_len` bytes.
/// The returned [`GeoRepairResult`] must be freed with
/// [`geo_repair_free_result`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn geo_repair_validate(
    wkb_data: *const u8,
    wkb_len: usize,
) -> GeoRepairResult {
    match catch_unwind(AssertUnwindSafe(|| {
        let geom = match geometry_from_wkb(wkb_data, wkb_len) {
            Ok(g) => g,
            Err(e) => return GeoRepairResult::error(&e),
        };
        if geom.is_valid() {
            GeoRepairResult::success(Vec::new())
        } else {
            let reason = geom.validate_reason();
            GeoRepairResult::error(&reason)
        }
    })) {
        Ok(r) => r,
        Err(_) => GeoRepairResult::error("internal error: validation panicked"),
    }
}

/// Validate a WKB geometry, then repair it if invalid.
///
/// On success (`result.success == true`):
/// - `wkb_data` / `wkb_len` contain the (possibly repaired) WKB geometry.
/// - `error_msg` is `NULL` when the input was already valid, or contains
///   the validation error reasons when the input was repaired.
///
/// # Safety
///
/// `wkb_data` must point to a valid WKB buffer of `wkb_len` bytes.
/// The returned [`GeoRepairResult`] must be freed with
/// [`geo_repair_free_result`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn geo_repair_validate_and_fix(
    wkb_data: *const u8,
    wkb_len: usize,
) -> GeoRepairResult {
    match catch_unwind(AssertUnwindSafe(|| {
        let geom = match geometry_from_wkb(wkb_data, wkb_len) {
            Ok(g) => g,
            Err(e) => return GeoRepairResult::error(&e),
        };
        let errors = if geom.is_valid() {
            None
        } else {
            Some(geom.validate_reason())
        };
        let fixed = geom.make_valid();
        let wkb = match geometry_to_wkb(&fixed) {
            Ok(w) => w,
            Err(e) => return GeoRepairResult::error(&e),
        };
        match errors {
            Some(reason) => {
                let mut res = GeoRepairResult::success(wkb);
                res.error_msg = CString::new(reason).unwrap_or_default().into_raw();
                res
            }
            None => GeoRepairResult::success(wkb),
        }
    })) {
        Ok(r) => r,
        Err(_) => GeoRepairResult::error("internal error: validate_and_fix panicked"),
    }
}

/// Validate a WKB geometry, then repair it with configuration.
///
/// `poly_method`: 0 = Auto, 1 = Arrange, 2 = Structure.
///
/// On success (`result.success == true`):
/// - `wkb_data` / `wkb_len` contain the (possibly repaired) WKB geometry.
/// - `error_msg` is `NULL` when the input was already valid, or contains
///   the validation error reasons when the input was repaired.
///
/// # Safety
///
/// `wkb_data` must point to a valid WKB buffer of `wkb_len` bytes.
/// The returned [`GeoRepairResult`] must be freed with
/// [`geo_repair_free_result`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn geo_repair_validate_and_fix_with_config(
    wkb_data: *const u8,
    wkb_len: usize,
    keep_collapsed: bool,
    poly_method: u8,
) -> GeoRepairResult {
    match catch_unwind(AssertUnwindSafe(|| {
        let geom = match geometry_from_wkb(wkb_data, wkb_len) {
            Ok(g) => g,
            Err(e) => return GeoRepairResult::error(&e),
        };
        let errors = if geom.is_valid() {
            None
        } else {
            Some(geom.validate_reason())
        };
        let config = MakeValidConfig {
            keep_collapsed,
            poly_method: match poly_method {
                0 => crate::PolyMethod::Auto,
                1 => crate::PolyMethod::Arrange,
                2 => crate::PolyMethod::Structure,
                _ => crate::PolyMethod::Auto,
            },
            fill_rule: Default::default(),
            crs: None,
            target_crs: None,
        };
        let fixed = geom.make_valid_with_config(&config);
        let wkb = match geometry_to_wkb(&fixed) {
            Ok(w) => w,
            Err(e) => return GeoRepairResult::error(&e),
        };
        match errors {
            Some(reason) => {
                let mut res = GeoRepairResult::success(wkb);
                res.error_msg = CString::new(reason).unwrap_or_default().into_raw();
                res
            }
            None => GeoRepairResult::success(wkb),
        }
    })) {
        Ok(r) => r,
        Err(_) => GeoRepairResult::error("internal error: validate_and_fix panicked"),
    }
}

/// Free a [`GeoRepairResult`] returned by any `geo_repair_*` function.
///
/// After calling this function the result struct is zeroed so that
/// double-free is harmless (the inner pointers will be null).
///
/// # Safety
///
/// `result` must not be null and must point to a valid result that has
/// not been freed before.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn geo_repair_free_result(result: *mut GeoRepairResult) {
    if result.is_null() {
        return;
    }
    // SAFETY: caller guarantees result is a valid, non-null pointer.
    let r = unsafe { &mut *result };
    if !r.wkb_data.is_null() {
        // SAFETY: the WKB buffer was allocated by Vec in success().
        unsafe { drop(Vec::from_raw_parts(r.wkb_data, r.wkb_len, r.wkb_len)) };
    }
    if !r.error_msg.is_null() {
        // SAFETY: the error string was allocated by CString in error().
        unsafe { drop(CString::from_raw(r.error_msg)) };
    }
    r.success = false;
    r.wkb_data = ptr::null_mut();
    r.wkb_len = 0;
    r.error_msg = ptr::null_mut();
}