oxigdal-algorithms 0.1.4

High-performance SIMD-optimized raster and vector algorithms for OxiGDAL - Pure Rust geospatial processing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
//! Object pooling for geometry types to reduce allocations
//!
//! This module provides thread-local object pools for frequently allocated
//! geometry types (Point, LineString, Polygon). Object pooling can significantly
//! reduce allocation overhead in batch spatial operations.
//!
//! # Performance Benefits
//!
//! When performing many spatial operations in sequence, object pooling can:
//! - Reduce allocations by 2-3x for batch operations
//! - Decrease GC pressure and memory fragmentation
//! - Improve cache locality for frequently reused objects
//!
//! # Thread Safety
//!
//! All pools are thread-local, eliminating synchronization overhead.
//! Each thread maintains its own independent pools.
//!
//! # Usage Example
//!
//! ```
//! use oxigdal_algorithms::vector::{Point, buffer_point_pooled, BufferOptions};
//!
//! let point = Point::new(0.0, 0.0);
//! let options = BufferOptions::default();
//!
//! // Get a pooled polygon - automatically returned to pool when guard drops
//! let buffered = buffer_point_pooled(&point, 10.0, &options)?;
//! // Use the buffered geometry...
//! // Automatically returned to pool here
//! # Ok::<(), oxigdal_algorithms::error::AlgorithmError>(())
//! ```

use oxigdal_core::vector::{Coordinate, LineString, Point, Polygon};
use std::cell::RefCell;
use std::mem::ManuallyDrop;
use std::ops::{Deref, DerefMut};

/// Initial capacity for each object pool
const INITIAL_POOL_CAPACITY: usize = 16;

/// Maximum number of objects to keep in pool to avoid unbounded growth
const MAX_POOL_SIZE: usize = 128;

/// Generic object pool for reusable objects
///
/// The pool maintains a collection of reusable objects to reduce allocation
/// overhead. Objects are returned to the pool automatically via `PoolGuard`.
pub struct Pool<T> {
    objects: Vec<T>,
    capacity: usize,
}

impl<T> Pool<T> {
    /// Creates a new empty pool with the given capacity
    pub fn new(capacity: usize) -> Self {
        Self {
            objects: Vec::with_capacity(capacity),
            capacity,
        }
    }

    /// Gets an object from the pool, or creates a new one if pool is empty
    pub fn get<F>(&mut self, create: F) -> T
    where
        F: FnOnce() -> T,
    {
        self.objects.pop().unwrap_or_else(create)
    }

    /// Returns an object to the pool for reuse
    ///
    /// If the pool is at maximum capacity, the object is dropped instead
    pub fn put(&mut self, obj: T) {
        if self.objects.len() < MAX_POOL_SIZE {
            self.objects.push(obj);
        }
        // Otherwise drop the object to prevent unbounded growth
    }

    /// Clears all objects from the pool
    pub fn clear(&mut self) {
        self.objects.clear();
    }

    /// Returns the number of objects currently in the pool
    pub fn len(&self) -> usize {
        self.objects.len()
    }

    /// Returns true if the pool is empty
    pub fn is_empty(&self) -> bool {
        self.objects.is_empty()
    }
}

impl<T> Default for Pool<T> {
    fn default() -> Self {
        Self::new(INITIAL_POOL_CAPACITY)
    }
}

/// RAII guard that returns an object to the pool when dropped
///
/// This ensures objects are automatically returned to the pool even if
/// an error occurs or early return happens.
///
/// The guard uses `ManuallyDrop` internally to avoid double-drop issues
/// when converting to the inner value.
pub struct PoolGuard<'a, T> {
    object: ManuallyDrop<T>,
    pool: &'a RefCell<Pool<T>>,
    /// Track if into_inner() was called to prevent double-drop
    consumed: bool,
}

impl<'a, T> PoolGuard<'a, T> {
    /// Creates a new pool guard
    fn new(object: T, pool: &'a RefCell<Pool<T>>) -> Self {
        Self {
            object: ManuallyDrop::new(object),
            pool,
            consumed: false,
        }
    }

    /// Consumes the guard and returns the inner object without returning to pool
    #[allow(unsafe_code)]
    pub fn into_inner(mut self) -> T {
        self.consumed = true;
        // SAFETY: We take ownership via into_inner, and set consumed flag
        // to prevent Drop from running
        unsafe { ManuallyDrop::take(&mut self.object) }
    }
}

impl<'a, T> Deref for PoolGuard<'a, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.object
    }
}

impl<'a, T> DerefMut for PoolGuard<'a, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.object
    }
}

impl<'a, T> Drop for PoolGuard<'a, T> {
    #[allow(unsafe_code)]
    fn drop(&mut self) {
        if !self.consumed {
            // SAFETY: We only take here if not consumed, and we're in Drop
            // so this is the last time we'll access this object
            let object = unsafe { ManuallyDrop::take(&mut self.object) };
            if let Ok(mut pool) = self.pool.try_borrow_mut() {
                pool.put(object);
            }
            // If we can't borrow the pool (shouldn't happen), object is dropped here
        }
    }
}

// Thread-local pools for each geometry type
thread_local! {
    static POINT_POOL: RefCell<Pool<Point>> = RefCell::new(Pool::default());
    static LINESTRING_POOL: RefCell<Pool<LineString>> = RefCell::new(Pool::default());
    static POLYGON_POOL: RefCell<Pool<Polygon>> = RefCell::new(Pool::default());
    static COORDINATE_VEC_POOL: RefCell<Pool<Vec<Coordinate>>> = RefCell::new(Pool::default());
}

/// Gets a Point from the thread-local pool
///
/// If the pool is empty, creates a new Point with the given coordinates.
#[allow(unsafe_code)]
pub fn get_pooled_point(x: f64, y: f64) -> PoolGuard<'static, Point> {
    POINT_POOL.with(|pool| {
        let mut pool_ref = pool.borrow_mut();
        let mut point = pool_ref.get(|| Point::new(0.0, 0.0));
        // Update the point coordinates via the public coord field
        point.coord.x = x;
        point.coord.y = y;
        point.coord.z = None;
        drop(pool_ref);
        // SAFETY: The RefCell will live for the entire 'static lifetime as it's thread_local
        // The guard holds a reference that prevents the pool from being dropped while in use
        PoolGuard::new(point, unsafe { &*(pool as *const RefCell<Pool<Point>>) })
    })
}

/// Gets a LineString from the thread-local pool
///
/// Returns a LineString with 2 origin coordinates. The caller should replace
/// the coordinates via `coords_mut()` to set the actual line geometry.
///
/// Note: LineStrings require at least 2 points. The returned LineString will
/// have placeholder coordinates that should be replaced by the caller.
#[allow(unsafe_code)]
pub fn get_pooled_linestring() -> PoolGuard<'static, LineString> {
    LINESTRING_POOL.with(|pool| {
        let mut pool_ref = pool.borrow_mut();
        let mut linestring = pool_ref.get(|| {
            // Create minimal valid linestring (2 points required)
            // Note: We cannot return Result here, so we use minimal valid geometry
            // In practice, LineString::new should never fail with valid coordinates
            match LineString::new(vec![
                Coordinate::new_2d(0.0, 0.0),
                Coordinate::new_2d(0.0, 0.0),
            ]) {
                Ok(ls) => ls,
                Err(_) => {
                    // This should never happen with valid coordinates
                    // Create with slightly different coords to ensure validity
                    match LineString::new(vec![
                        Coordinate::new_2d(0.0, 0.0),
                        Coordinate::new_2d(1.0, 1.0),
                    ]) {
                        Ok(ls) => ls,
                        Err(_) => {
                            // Truly should never reach here - coordinates are valid
                            // Direct construction as last resort (safe because we control the data)
                            LineString {
                                coords: vec![
                                    Coordinate::new_2d(0.0, 0.0),
                                    Coordinate::new_2d(1.0, 1.0),
                                ],
                            }
                        }
                    }
                }
            }
        });
        // Reset to minimal valid state using public field access
        if linestring.len() < 2 {
            linestring.coords.clear();
            linestring.coords.push(Coordinate::new_2d(0.0, 0.0));
            linestring.coords.push(Coordinate::new_2d(0.0, 0.0));
        }
        drop(pool_ref);
        // SAFETY: The RefCell will live for the entire 'static lifetime as it's thread_local
        // The guard holds a reference that prevents the pool from being dropped while in use
        PoolGuard::new(linestring, unsafe {
            &*(pool as *const RefCell<Pool<LineString>>)
        })
    })
}

/// Gets a Polygon from the thread-local pool
///
/// Returns a minimal triangle polygon. The caller should replace the exterior
/// ring coordinates and add holes as needed via `exterior_mut()` and `holes_mut()`.
///
/// Note: Polygons require at least 4 points in the exterior ring (including closing point).
/// The returned Polygon will have placeholder coordinates that should be replaced.
#[allow(unsafe_code)]
pub fn get_pooled_polygon() -> PoolGuard<'static, Polygon> {
    POLYGON_POOL.with(|pool| {
        let mut pool_ref = pool.borrow_mut();
        let mut polygon = pool_ref.get(|| {
            // Create minimal valid polygon (triangle = 4 points including closing)
            let ring = match LineString::new(vec![
                Coordinate::new_2d(0.0, 0.0),
                Coordinate::new_2d(1.0, 0.0),
                Coordinate::new_2d(0.0, 1.0),
                Coordinate::new_2d(0.0, 0.0),
            ]) {
                Ok(ls) => ls,
                Err(_) => {
                    // This should never happen - coordinates are valid
                    // Fallback to direct construction
                    LineString {
                        coords: vec![
                            Coordinate::new_2d(0.0, 0.0),
                            Coordinate::new_2d(1.0, 0.0),
                            Coordinate::new_2d(0.0, 1.0),
                            Coordinate::new_2d(0.0, 0.0),
                        ],
                    }
                }
            };
            match Polygon::new(ring, vec![]) {
                Ok(poly) => poly,
                Err(_) => {
                    // This should never happen with valid ring
                    // Direct construction as fallback
                    Polygon {
                        exterior: LineString {
                            coords: vec![
                                Coordinate::new_2d(0.0, 0.0),
                                Coordinate::new_2d(1.0, 0.0),
                                Coordinate::new_2d(0.0, 1.0),
                                Coordinate::new_2d(0.0, 0.0),
                            ],
                        },
                        interiors: vec![],
                    }
                }
            }
        });
        // Reset to minimal valid state using public field access
        if polygon.exterior.len() < 4 {
            polygon.exterior.coords.clear();
            polygon.exterior.coords.push(Coordinate::new_2d(0.0, 0.0));
            polygon.exterior.coords.push(Coordinate::new_2d(1.0, 0.0));
            polygon.exterior.coords.push(Coordinate::new_2d(0.0, 1.0));
            polygon.exterior.coords.push(Coordinate::new_2d(0.0, 0.0));
        }
        polygon.interiors.clear();
        drop(pool_ref);
        // SAFETY: The RefCell will live for the entire 'static lifetime as it's thread_local
        // The guard holds a reference that prevents the pool from being dropped while in use
        PoolGuard::new(polygon, unsafe {
            &*(pool as *const RefCell<Pool<Polygon>>)
        })
    })
}

/// Gets a `Vec<Coordinate>` from the thread-local pool
///
/// The returned vector will be empty and must be populated by the caller.
#[allow(unsafe_code)]
pub fn get_pooled_coordinate_vec() -> PoolGuard<'static, Vec<Coordinate>> {
    COORDINATE_VEC_POOL.with(|pool| {
        let mut pool_ref = pool.borrow_mut();
        let mut vec = pool_ref.get(Vec::new);
        vec.clear();
        drop(pool_ref);
        PoolGuard::new(vec, unsafe {
            &*(pool as *const RefCell<Pool<Vec<Coordinate>>>)
        })
    })
}

/// Clears all thread-local pools
///
/// This can be useful for releasing memory after batch operations complete.
pub fn clear_all_pools() {
    POINT_POOL.with(|pool| pool.borrow_mut().clear());
    LINESTRING_POOL.with(|pool| pool.borrow_mut().clear());
    POLYGON_POOL.with(|pool| pool.borrow_mut().clear());
    COORDINATE_VEC_POOL.with(|pool| pool.borrow_mut().clear());
}

/// Gets statistics about pool usage for the current thread
#[derive(Debug, Clone)]
pub struct PoolStats {
    pub points_pooled: usize,
    pub linestrings_pooled: usize,
    pub polygons_pooled: usize,
    pub coordinate_vecs_pooled: usize,
}

/// Returns statistics about current pool usage
pub fn get_pool_stats() -> PoolStats {
    PoolStats {
        points_pooled: POINT_POOL.with(|pool| pool.borrow().len()),
        linestrings_pooled: LINESTRING_POOL.with(|pool| pool.borrow().len()),
        polygons_pooled: POLYGON_POOL.with(|pool| pool.borrow().len()),
        coordinate_vecs_pooled: COORDINATE_VEC_POOL.with(|pool| pool.borrow().len()),
    }
}

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

    #[test]
    fn test_pool_basic_operations() {
        clear_all_pools();

        let stats = get_pool_stats();
        assert_eq!(stats.points_pooled, 0);

        // Get a point from the pool
        {
            let _point = get_pooled_point(1.0, 2.0);
            // Point should not be in pool while guard is alive
            let stats = get_pool_stats();
            assert_eq!(stats.points_pooled, 0);
        }

        // Point should be returned to pool after guard drops
        let stats = get_pool_stats();
        assert_eq!(stats.points_pooled, 1);
    }

    #[test]
    fn test_pool_guard_deref() {
        clear_all_pools();

        let point = get_pooled_point(3.0, 4.0);
        assert_eq!(point.x(), 3.0);
        assert_eq!(point.y(), 4.0);
    }

    #[test]
    fn test_pool_guard_deref_mut() {
        clear_all_pools();

        let mut point = get_pooled_point(1.0, 1.0);
        point.coord.x = 5.0;
        point.coord.y = 6.0;
        assert_eq!(point.x(), 5.0);
        assert_eq!(point.y(), 6.0);
    }

    #[test]
    fn test_pool_reuse() {
        clear_all_pools();

        // Create and drop several points (each iteration reuses the same point)
        for i in 0..5 {
            let _point = get_pooled_point(i as f64, i as f64);
        }

        // Should have 1 point in the pool (reused across all iterations)
        let stats = get_pool_stats();
        assert_eq!(stats.points_pooled, 1);

        // Getting a point should reuse from pool
        let _point = get_pooled_point(100.0, 100.0);
        let stats = get_pool_stats();
        assert_eq!(stats.points_pooled, 0);
    }

    #[test]
    fn test_linestring_pool() {
        clear_all_pools();

        let mut linestring = get_pooled_linestring();
        linestring.coords.clear();
        linestring.coords.push(Coordinate::new_2d(0.0, 0.0));
        linestring.coords.push(Coordinate::new_2d(1.0, 1.0));

        assert_eq!(linestring.len(), 2);
        drop(linestring);

        let stats = get_pool_stats();
        assert_eq!(stats.linestrings_pooled, 1);

        // Get another linestring - should be cleared
        let linestring = get_pooled_linestring();
        assert_eq!(linestring.len(), 2);
    }

    #[test]
    fn test_polygon_pool() {
        clear_all_pools();

        let polygon = get_pooled_polygon();
        assert_eq!(polygon.exterior().len(), 4);
        assert_eq!(polygon.interiors().len(), 0);
        drop(polygon);

        let stats = get_pool_stats();
        assert_eq!(stats.polygons_pooled, 1);
    }

    #[test]
    fn test_coordinate_vec_pool() {
        clear_all_pools();

        let mut coords = get_pooled_coordinate_vec();
        coords.push(Coordinate::new_2d(1.0, 2.0));
        coords.push(Coordinate::new_2d(3.0, 4.0));
        assert_eq!(coords.len(), 2);
        drop(coords);

        let stats = get_pool_stats();
        assert_eq!(stats.coordinate_vecs_pooled, 1);

        // Get another vec - should be cleared
        let coords = get_pooled_coordinate_vec();
        assert_eq!(coords.len(), 0);
    }

    #[test]
    fn test_pool_max_size() {
        clear_all_pools();

        // Add more than MAX_POOL_SIZE objects
        for i in 0..(MAX_POOL_SIZE + 10) {
            let _point = get_pooled_point(i as f64, i as f64);
        }

        // Pool should not exceed max size
        let stats = get_pool_stats();
        assert!(stats.points_pooled <= MAX_POOL_SIZE);
    }

    #[test]
    fn test_into_inner() {
        clear_all_pools();

        let guard = get_pooled_point(7.0, 8.0);
        let point = guard.into_inner();

        assert_eq!(point.x(), 7.0);
        assert_eq!(point.y(), 8.0);

        // Point should not be returned to pool
        let stats = get_pool_stats();
        assert_eq!(stats.points_pooled, 0);
    }

    #[test]
    fn test_clear_all_pools() {
        // Add objects to all pools
        let _p = get_pooled_point(1.0, 1.0);
        let _l = get_pooled_linestring();
        let _poly = get_pooled_polygon();
        let _coords = get_pooled_coordinate_vec();

        drop(_p);
        drop(_l);
        drop(_poly);
        drop(_coords);

        // Verify pools have objects
        let stats = get_pool_stats();
        assert!(stats.points_pooled > 0);
        assert!(stats.linestrings_pooled > 0);
        assert!(stats.polygons_pooled > 0);
        assert!(stats.coordinate_vecs_pooled > 0);

        // Clear all pools
        clear_all_pools();

        // Verify pools are empty
        let stats = get_pool_stats();
        assert_eq!(stats.points_pooled, 0);
        assert_eq!(stats.linestrings_pooled, 0);
        assert_eq!(stats.polygons_pooled, 0);
        assert_eq!(stats.coordinate_vecs_pooled, 0);
    }

    #[test]
    fn test_thread_local_isolation() {
        use std::thread;

        clear_all_pools();

        // Add object to main thread pool
        {
            let _point = get_pooled_point(1.0, 1.0);
        }

        let main_stats = get_pool_stats();
        assert_eq!(main_stats.points_pooled, 1);

        // Spawn a thread and check its pool is independent
        let handle = thread::spawn(|| {
            let stats = get_pool_stats();
            assert_eq!(stats.points_pooled, 0);

            {
                let _point = get_pooled_point(2.0, 2.0);
            }

            let stats = get_pool_stats();
            assert_eq!(stats.points_pooled, 1);
        });

        handle.join().expect("Thread panicked");

        // Main thread pool should still have 1 object
        let main_stats = get_pool_stats();
        assert_eq!(main_stats.points_pooled, 1);
    }
}