rapidgeo-distance 0.2.2

Fast and accurate geographic distance calculations with geodesic, haversine, and euclidean algorithms
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
use crate::formats::CoordSource;
use crate::LngLat;

#[cfg(feature = "batch")]
use super::parallel;
use super::sequential::{pairwise_haversine_any_extend, pairwise_haversine_iter_extend};

/// Buffer pool for coordinate processing operations.
///
/// Manages a pool of reusable `Vec<f64>` buffers to minimize memory allocations
/// during repeated coordinate calculations. This is particularly beneficial for
/// iterative processing of large datasets or real-time applications.
///
/// # Performance Benefits
///
/// - **Reduced allocations**: Reuses buffers instead of allocating new ones
/// - **Memory locality**: Keeps buffer capacity to avoid repeated growth
/// - **Pool management**: Limits pool size to prevent unbounded memory growth
/// - **RAII safety**: Automatic buffer return via scoped operations
///
/// # Usage Patterns
///
/// The pool supports two usage patterns:
/// 1. **Manual management**: `get_buffer()` and `return_buffer()`
/// 2. **Scoped operations**: `with_buffer()` for automatic lifecycle management
///
/// # Examples
///
/// ```
/// use rapidgeo_distance::format_batch::buffer_pool::BufferPool;
/// use rapidgeo_distance::LngLat;
///
/// // Create pool with initial buffer capacity of 1000 elements
/// let mut pool = BufferPool::new(1000);
///
/// // Scoped operation (recommended)
/// let result = pool.with_buffer(|buffer| {
///     // Use buffer for calculations
///     buffer.extend([1.0, 2.0, 3.0]);
///     buffer.len()
/// }); // Buffer automatically returned to pool
///
/// assert_eq!(result, 3);
/// assert_eq!(pool.pool_size(), 1); // Buffer was returned
/// ```
///
/// # Memory Management
///
/// - Buffers are cleared (length set to 0) when returned, but capacity is preserved
/// - Pool size is capped to prevent unbounded growth
/// - Dropped buffers are not returned to the pool once capacity is reached
///
/// # Thread Safety
///
/// This pool is **not** thread-safe. Use separate pools per thread or add
/// synchronization for concurrent access.
///
/// # See Also
///
/// - [`with_buffer`](BufferPool::with_buffer) for scoped buffer operations
/// - [`pairwise_haversine_any`](BufferPool::pairwise_haversine_any) for coordinate-specific operations
pub struct BufferPool {
    buffers: Vec<Vec<f64>>,
    initial_capacity: usize,
    max_pool_size: usize,
}

impl BufferPool {
    /// Creates a new buffer pool with the specified initial buffer capacity.
    ///
    /// # Arguments
    ///
    /// * `initial_capacity` - The initial capacity (in elements) for new buffers
    ///
    /// # Examples
    ///
    /// ```
    /// use rapidgeo_distance::format_batch::buffer_pool::BufferPool;
    ///
    /// // Pool for processing up to 1000 coordinate pairs
    /// let pool = BufferPool::new(1000);
    /// assert_eq!(pool.pool_size(), 0); // No buffers initially
    /// ```
    ///
    /// # Default Settings
    ///
    /// - **Maximum pool size**: 8 buffers
    /// - **Initial pool size**: 0 buffers (created on demand)
    pub fn new(initial_capacity: usize) -> Self {
        Self {
            buffers: Vec::new(),
            initial_capacity,
            max_pool_size: 8,
        }
    }

    /// Creates a new buffer pool with custom capacity and pool size limits.
    ///
    /// # Arguments
    ///
    /// * `initial_capacity` - The initial capacity (in elements) for new buffers
    /// * `max_pool_size` - Maximum number of buffers to keep in the pool
    ///
    /// # Examples
    ///
    /// ```
    /// use rapidgeo_distance::format_batch::buffer_pool::BufferPool;
    ///
    /// // Pool for memory-constrained environments
    /// let pool = BufferPool::with_max_size(500, 4);
    /// assert_eq!(pool.pool_size(), 0);
    /// ```
    ///
    /// # Pool Size Considerations
    ///
    /// - **Small pools (1-4)**: Lower memory usage, more allocations
    /// - **Large pools (8-16)**: Higher memory usage, fewer allocations
    /// - **Very large pools (>16)**: Diminishing returns, potential memory waste
    pub fn with_max_size(initial_capacity: usize, max_pool_size: usize) -> Self {
        Self {
            buffers: Vec::new(),
            initial_capacity,
            max_pool_size,
        }
    }

    /// Gets a buffer from the pool, creating a new one if the pool is empty.
    ///
    /// The returned buffer is empty (length 0) but may have existing capacity
    /// from previous use. You must call [`return_buffer`](Self::return_buffer)
    /// when finished to return it to the pool.
    ///
    /// # Returns
    ///
    /// An empty `Vec<f64>` ready for use
    ///
    /// # Examples
    ///
    /// ```
    /// use rapidgeo_distance::format_batch::buffer_pool::BufferPool;
    ///
    /// let mut pool = BufferPool::new(100);
    ///
    /// let mut buffer = pool.get_buffer();
    /// assert_eq!(buffer.len(), 0);
    /// assert!(buffer.capacity() >= 100);
    ///
    /// buffer.push(42.0);
    /// pool.return_buffer(buffer);
    /// ```
    ///
    /// # Performance Notes
    ///
    /// - Reused buffers retain their capacity from previous use
    /// - New buffers are allocated with the pool's initial capacity
    /// - Consider using [`with_buffer`](Self::with_buffer) for automatic management
    pub fn get_buffer(&mut self) -> Vec<f64> {
        self.buffers
            .pop()
            .unwrap_or_else(|| Vec::with_capacity(self.initial_capacity))
    }

    /// Returns a buffer to the pool for reuse.
    ///
    /// The buffer is cleared (length set to 0) but capacity is preserved.
    /// If the pool is full, the buffer is dropped instead of being stored.
    ///
    /// # Arguments
    ///
    /// * `buffer` - The buffer to return (will be cleared)
    ///
    /// # Examples
    ///
    /// ```
    /// use rapidgeo_distance::format_batch::buffer_pool::BufferPool;
    ///
    /// let mut pool = BufferPool::new(50);
    ///
    /// let mut buffer = pool.get_buffer();
    /// buffer.extend([1.0, 2.0, 3.0]);
    ///
    /// pool.return_buffer(buffer);
    /// assert_eq!(pool.pool_size(), 1);
    ///
    /// // Buffer is cleared but capacity preserved
    /// let buffer2 = pool.get_buffer();
    /// assert_eq!(buffer2.len(), 0);
    /// ```
    ///
    /// # Pool Capacity
    ///
    /// Buffers are only stored if there's room in the pool:
    ///
    /// ```
    /// use rapidgeo_distance::format_batch::buffer_pool::BufferPool;
    ///
    /// let mut pool = BufferPool::with_max_size(50, 2); // Max 2 buffers
    ///
    /// let buf1 = pool.get_buffer();
    /// let buf2 = pool.get_buffer();
    /// pool.return_buffer(buf1);
    /// pool.return_buffer(buf2);
    /// assert_eq!(pool.pool_size(), 2);
    ///
    /// // Third buffer is dropped, not stored
    /// let buf3 = pool.get_buffer();
    /// pool.return_buffer(buf3);
    /// assert_eq!(pool.pool_size(), 2); // Still 2
    /// ```
    pub fn return_buffer(&mut self, mut buffer: Vec<f64>) {
        if self.buffers.len() < self.max_pool_size {
            buffer.clear();
            self.buffers.push(buffer);
        }
    }

    /// Executes a closure with a temporary buffer, automatically managing its lifecycle.
    ///
    /// This is the recommended way to use the buffer pool as it ensures the buffer
    /// is always returned, even if the closure panics or returns early.
    ///
    /// # Arguments
    ///
    /// * `f` - Closure that receives a mutable buffer reference
    ///
    /// # Returns
    ///
    /// The result of the closure
    ///
    /// # Examples
    ///
    /// ```
    /// use rapidgeo_distance::format_batch::buffer_pool::BufferPool;
    ///
    /// let mut pool = BufferPool::new(100);
    ///
    /// let sum = pool.with_buffer(|buffer| {
    ///     buffer.extend([1.0, 2.0, 3.0, 4.0, 5.0]);
    ///     buffer.iter().sum::<f64>()
    /// });
    ///
    /// assert_eq!(sum, 15.0);
    /// assert_eq!(pool.pool_size(), 1); // Buffer was returned
    /// ```
    ///
    /// # Error Safety
    ///
    /// The buffer is returned to the pool even if the closure panics:
    ///
    /// ```should_panic
    /// use rapidgeo_distance::format_batch::buffer_pool::BufferPool;
    ///
    /// let mut pool = BufferPool::new(100);
    ///
    /// pool.with_buffer(|_buffer| {
    ///     panic!("Something went wrong!");
    /// });
    /// ```
    ///
    /// # Performance Benefits
    ///
    /// - **No manual tracking**: Impossible to forget buffer return
    /// - **Exception safety**: Buffer returned even on panic
    /// - **Zero overhead**: Inlined closure execution
    pub fn with_buffer<F, R>(&mut self, f: F) -> R
    where
        F: FnOnce(&mut Vec<f64>) -> R,
    {
        let mut buffer = self.get_buffer();
        let result = f(&mut buffer);
        self.return_buffer(buffer);
        result
    }

    /// Computes pairwise Haversine distances using a pooled buffer.
    ///
    /// Calculates the distance between consecutive coordinate pairs using the
    /// Haversine formula. The result buffer is obtained from the pool but
    /// **not** returned automatically - you own the returned vector.
    ///
    /// # Arguments
    ///
    /// * `iter` - Iterator over `LngLat` coordinates
    ///
    /// # Returns
    ///
    /// Vector of distances in meters between consecutive coordinate pairs
    ///
    /// # Examples
    ///
    /// ```
    /// use rapidgeo_distance::format_batch::buffer_pool::BufferPool;
    /// use rapidgeo_distance::LngLat;
    ///
    /// let mut pool = BufferPool::new(100);
    ///
    /// let coords = [
    ///     LngLat::new_deg(-122.4194, 37.7749), // San Francisco
    ///     LngLat::new_deg(-74.0060, 40.7128),  // New York
    ///     LngLat::new_deg(-87.6298, 41.8781),  // Chicago
    /// ];
    ///
    /// let distances = pool.pairwise_haversine_iter(coords.iter().copied());
    /// assert_eq!(distances.len(), 2); // n-1 distances for n points
    ///
    /// // SF to NYC is approximately 4100km
    /// assert!(distances[0] > 4_000_000.0 && distances[0] < 4_200_000.0);
    /// ```
    ///
    /// # Performance
    ///
    /// - **Buffer reuse**: Uses pooled buffer for intermediate calculations
    /// - **Single allocation**: Result vector allocated once with appropriate capacity
    /// - **Lazy evaluation**: Iterator is consumed on-demand
    ///
    /// # See Also
    ///
    /// - [`pairwise_haversine_any`](Self::pairwise_haversine_any) for `CoordSource` input
    /// - [`pairwise_haversine_iter`](super::sequential::pairwise_haversine_iter) for non-pooled version
    pub fn pairwise_haversine_iter<I>(&mut self, iter: I) -> Vec<f64>
    where
        I: Iterator<Item = LngLat>,
    {
        let mut result = self.get_buffer();
        pairwise_haversine_iter_extend(iter, &mut result);
        result
    }

    /// Computes pairwise Haversine distances from any coordinate source using a pooled buffer.
    ///
    /// Accepts any type implementing [`CoordSource`] (tuples, arrays, etc.) and computes
    /// distances between consecutive coordinates. Automatically handles format detection
    /// and conversion as needed.
    ///
    /// # Arguments
    ///
    /// * `coords` - Any coordinate source (Vec<LngLat>, Vec<(f64,f64)>, Vec<f64>, etc.)
    ///
    /// # Returns
    ///
    /// Vector of distances in meters between consecutive coordinate pairs
    ///
    /// # Examples
    ///
    /// ```
    /// use rapidgeo_distance::format_batch::buffer_pool::BufferPool;
    /// use rapidgeo_distance::LngLat;
    ///
    /// let mut pool = BufferPool::new(100);
    ///
    /// // Works with various coordinate formats
    /// let coords_lnglat = vec![
    ///     LngLat::new_deg(-122.4194, 37.7749),
    ///     LngLat::new_deg(-74.0060, 40.7128),
    /// ];
    /// let distances1 = pool.pairwise_haversine_any(&coords_lnglat);
    ///
    /// let coords_tuples = vec![
    ///     (-122.4194, 37.7749),
    ///     (-74.0060, 40.7128),
    /// ];
    /// let distances2 = pool.pairwise_haversine_any(&coords_tuples);
    ///
    /// // Results should be identical
    /// assert!((distances1[0] - distances2[0]).abs() < 1e-10);
    /// ```
    ///
    /// # Format Support
    ///
    /// Supports all coordinate formats:
    /// - `Vec<LngLat>` - Native format
    /// - `Vec<(f64, f64)>` - Tuples with format detection
    /// - `Vec<f64>` - Flat arrays (chunked into pairs)
    /// - `&[f64]` - Array slices
    ///
    /// # See Also
    ///
    /// - [`pairwise_haversine_iter`](Self::pairwise_haversine_iter) for iterator input
    /// - [`CoordSource`] trait for supported input types
    pub fn pairwise_haversine_any<T: CoordSource>(&mut self, coords: &T) -> Vec<f64> {
        let mut result = self.get_buffer();
        pairwise_haversine_any_extend(coords, &mut result);
        result
    }

    #[cfg(feature = "batch")]
    pub fn pairwise_haversine_par_iter<I>(&mut self, iter: I) -> Vec<f64>
    where
        I: Iterator<Item = LngLat>,
    {
        let mut result = self.get_buffer();
        parallel::pairwise_haversine_par_iter_extend(iter, &mut result);
        result
    }

    #[cfg(feature = "batch")]
    pub fn pairwise_haversine_par_any<T: CoordSource + Sync>(&mut self, coords: &T) -> Vec<f64> {
        let mut result = self.get_buffer();
        parallel::pairwise_haversine_par_any_extend(coords, &mut result);
        result
    }

    /// Returns the number of buffers currently stored in the pool.
    ///
    /// This count represents available buffers ready for reuse. It will be
    /// between 0 and the maximum pool size configured during construction.
    ///
    /// # Examples
    ///
    /// ```
    /// use rapidgeo_distance::format_batch::buffer_pool::BufferPool;
    ///
    /// let mut pool = BufferPool::new(100);
    /// assert_eq!(pool.pool_size(), 0); // Initially empty
    ///
    /// let buffer = pool.get_buffer();
    /// assert_eq!(pool.pool_size(), 0); // Buffer checked out
    ///
    /// pool.return_buffer(buffer);
    /// assert_eq!(pool.pool_size(), 1); // Buffer returned
    /// ```
    ///
    /// # Use Cases
    ///
    /// - **Debugging**: Verify buffers are being returned properly
    /// - **Monitoring**: Track pool utilization in long-running applications
    /// - **Testing**: Ensure proper resource management in tests
    pub fn pool_size(&self) -> usize {
        self.buffers.len()
    }

    /// Removes all buffers from the pool, freeing their memory.
    ///
    /// This is useful for releasing memory when the pool won't be used for
    /// an extended period, or for cleanup in tests and benchmarks.
    ///
    /// # Examples
    ///
    /// ```
    /// use rapidgeo_distance::format_batch::buffer_pool::BufferPool;
    ///
    /// let mut pool = BufferPool::new(100);
    ///
    /// // Use some buffers
    /// let buf1 = pool.get_buffer();
    /// let buf2 = pool.get_buffer();
    /// pool.return_buffer(buf1);
    /// pool.return_buffer(buf2);
    /// assert_eq!(pool.pool_size(), 2);
    ///
    /// // Clear all buffers
    /// pool.clear_pool();
    /// assert_eq!(pool.pool_size(), 0);
    /// ```
    ///
    /// # Memory Impact
    ///
    /// After clearing, subsequent `get_buffer()` calls will allocate new buffers
    /// with the pool's configured initial capacity. This may cause temporary
    /// performance degradation until the pool is rebuilt.
    ///
    /// # Use Cases
    ///
    /// - **Memory pressure**: Free memory when pool is idle
    /// - **Test cleanup**: Reset pool state between test cases
    /// - **Capacity changes**: Clear before changing buffer sizing strategy
    pub fn clear_pool(&mut self) {
        self.buffers.clear();
    }
}