oxiproj-transformations 0.1.1

Datum transformations and coordinate conversions for OxiProj.
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
//! `push` and `pop` pipeline coordinate-stack operations.
//!
//! Ported from PROJ `src/conversions/push_pop.cpp` (part of the pipeline
//! implementation in `src/pipeline.cpp`).
//!
//! # Overview
//!
//! Within a PROJ pipeline, `push` saves selected coordinate components onto a
//! per-thread stack and `pop` restores them. This lets the pipeline temporarily
//! overwrite components for an intermediate step and then recover the originals.
//!
//! Example pipeline (preserve X/Y, do a vertical-only transform):
//!
//! ```text
//! +proj=pipeline
//!   +step +proj=push +v_1 +v_2
//!   +step +proj=somevert ...
//!   +step +proj=pop  +v_1 +v_2
//! ```
//!
//! # Component selection
//!
//! The parameters `+v_1`, `+v_2`, `+v_3`, `+v_4` select which of the four
//! coordinate slots (X/Y/Z/T) are pushed or popped. If **none** of the four
//! flags is present the operation applies to **all four** components, mirroring
//! PROJ's default behaviour.
//!
//! # Directionality
//!
//! | operation | forward  | inverse  |
//! |-----------|----------|----------|
//! | `push`    | save      | restore  |
//! | `pop`     | restore   | save     |
//!
//! # Thread safety
//!
//! The stack is stored in a `thread_local!` `RefCell`, which is never shared
//! across threads. The operation structs themselves contain only `[bool; 4]`
//! and are therefore `Send + Sync`.

use std::cell::RefCell;

use crate::{TransBuild, TransParams};
use oxiproj_core::{Coord, IoUnits, Operation, ProjError, ProjResult};

// ---------------------------------------------------------------------------
// Thread-local coordinate stacks
// ---------------------------------------------------------------------------

thread_local! {
    /// Per-thread coordinate stacks for `push`/`pop` pipeline operations.
    ///
    /// Four independent stacks, one per coordinate component:
    /// index 0 → X (or λ), 1 → Y (or φ), 2 → Z, 3 → T.
    ///
    /// Using `RefCell` is safe here because each thread owns its own instance;
    /// there is never cross-thread aliasing. The operation structs do **not**
    /// hold a reference to this `RefCell`; they access it only via the
    /// `thread_local!` key, so they remain `Send + Sync`.
    static COORD_STACKS: RefCell<[Vec<f64>; 4]> =
        const { RefCell::new([Vec::new(), Vec::new(), Vec::new(), Vec::new()]) };
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Push selected components of `c` onto the thread-local stacks.
///
/// Returns `c` unmodified; `push` is a pure side-effect on the stack.
fn do_push(c: Coord, which: [bool; 4]) -> ProjResult<Coord> {
    let v = c.v();
    COORD_STACKS.with(|cell| {
        let mut stacks = cell.borrow_mut();
        for i in 0..4 {
            if which[i] {
                stacks[i].push(v[i]);
            }
        }
    });
    Ok(c)
}

/// Pop selected components from the thread-local stacks into `c`.
///
/// Components not selected by `which` are passed through unchanged.
/// If a stack is empty for a selected component (underflow), that component
/// is left at its current value — this matches PROJ's silent behaviour.
fn do_pop(c: Coord, which: [bool; 4]) -> ProjResult<Coord> {
    let mut v = c.v();
    COORD_STACKS.with(|cell| {
        let mut stacks = cell.borrow_mut();
        for i in 0..4 {
            if which[i] {
                if let Some(val) = stacks[i].pop() {
                    v[i] = val;
                }
                // Stack underflow: leave `v[i]` unchanged (PROJ silent pass-through)
            }
        }
    });
    Ok(Coord::new(v[0], v[1], v[2], v[3]))
}

// ---------------------------------------------------------------------------
// Operation structs
// ---------------------------------------------------------------------------

/// `push` pipeline operation — saves coordinate components onto the thread-local stack.
///
/// Forward direction: push (save). Inverse direction: pop (restore).
#[derive(Debug)]
struct PushOp {
    /// Which of the four coordinate components to push/pop.
    which: [bool; 4],
}

/// `pop` pipeline operation — restores coordinate components from the thread-local stack.
///
/// Forward direction: pop (restore). Inverse direction: push (save).
#[derive(Debug)]
struct PopOp {
    /// Which of the four coordinate components to push/pop.
    which: [bool; 4],
}

// SAFETY: `PushOp`/`PopOp` contain only `[bool; 4]`, which is `Send + Sync`.
// The thread-local `COORD_STACKS` is never stored in the struct; it is accessed
// only at call time via the `thread_local!` key. Therefore the structs are safe
// to move and share across threads even though the backing storage is thread-local.

impl Operation for PushOp {
    /// Forward: save selected components onto the stack, return `c` unchanged.
    fn forward_4d(&self, c: Coord) -> ProjResult<Coord> {
        do_push(c, self.which)
    }

    /// Inverse: restore selected components from the stack into `c`.
    fn inverse_4d(&self, c: Coord) -> ProjResult<Coord> {
        do_pop(c, self.which)
    }

    fn has_inverse(&self) -> bool {
        true
    }
}

impl Operation for PopOp {
    /// Forward: restore selected components from the stack into `c`.
    fn forward_4d(&self, c: Coord) -> ProjResult<Coord> {
        do_pop(c, self.which)
    }

    /// Inverse: save selected components onto the stack, return `c` unchanged.
    fn inverse_4d(&self, c: Coord) -> ProjResult<Coord> {
        do_push(c, self.which)
    }

    fn has_inverse(&self) -> bool {
        true
    }
}

// ---------------------------------------------------------------------------
// Parameter parsing
// ---------------------------------------------------------------------------

/// Parse `+v_1` … `+v_4` flags from the parameter block.
///
/// If **none** of the four flags is present, all four components are selected
/// (PROJ default: push/pop everything when no component filter is given).
fn parse_which(p: &TransParams) -> [bool; 4] {
    let v1 = p.params.exists("v_1");
    let v2 = p.params.exists("v_2");
    let v3 = p.params.exists("v_3");
    let v4 = p.params.exists("v_4");
    if !v1 && !v2 && !v3 && !v4 {
        // No filter → apply to all four components (PROJ default behaviour)
        [true, true, true, true]
    } else {
        [v1, v2, v3, v4]
    }
}

// ---------------------------------------------------------------------------
// Public constructors
// ---------------------------------------------------------------------------

/// Construct the `push` coordinate-stack operation.
///
/// Reads `+v_1` … `+v_4` flags to determine which components are saved.
/// If none are specified all four components are saved.
pub fn new_push(p: &TransParams) -> ProjResult<TransBuild> {
    let _ = ProjError::InvalidOp; // ensure error type is used (suppress lint)
    Ok(TransBuild::new(
        Box::new(PushOp {
            which: parse_which(p),
        }),
        IoUnits::Whatever,
        IoUnits::Whatever,
    ))
}

/// Construct the `pop` coordinate-stack operation.
///
/// Reads `+v_1` … `+v_4` flags to determine which components are restored.
/// If none are specified all four components are restored.
pub fn new_pop(p: &TransParams) -> ProjResult<TransBuild> {
    Ok(TransBuild::new(
        Box::new(PopOp {
            which: parse_which(p),
        }),
        IoUnits::Whatever,
        IoUnits::Whatever,
    ))
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use oxiproj_core::{Coord, Ellipsoid};

    // Minimal no-op parameter set for constructors that don't need params.
    struct NoParams;
    impl crate::TransParamLookup for NoParams {
        fn get_dms(&self, _key: &str) -> Option<f64> {
            None
        }
        fn get_f64(&self, _key: &str) -> Option<f64> {
            None
        }
        fn get_int(&self, _key: &str) -> Option<i64> {
            None
        }
        fn get_str(&self, _key: &str) -> Option<&str> {
            None
        }
        fn get_bool(&self, _key: &str) -> bool {
            false
        }
        fn exists(&self, _key: &str) -> bool {
            false
        }
    }

    // Parameter set that marks v_1 and v_2 as present.
    struct V1V2Params;
    impl crate::TransParamLookup for V1V2Params {
        fn get_dms(&self, _key: &str) -> Option<f64> {
            None
        }
        fn get_f64(&self, _key: &str) -> Option<f64> {
            None
        }
        fn get_int(&self, _key: &str) -> Option<i64> {
            None
        }
        fn get_str(&self, _key: &str) -> Option<&str> {
            None
        }
        fn get_bool(&self, _key: &str) -> bool {
            false
        }
        fn exists(&self, key: &str) -> bool {
            key == "v_1" || key == "v_2"
        }
    }

    fn wgs84() -> Ellipsoid {
        Ellipsoid::named("WGS84").expect("WGS84 ellipsoid must be available")
    }

    /// Clear the thread-local stacks before each test to avoid state leakage.
    fn clear_stacks() {
        COORD_STACKS.with(|cell| {
            let mut stacks = cell.borrow_mut();
            for stack in stacks.iter_mut() {
                stack.clear();
            }
        });
    }

    #[test]
    fn push_all_then_pop_all_round_trips() -> ProjResult<()> {
        clear_stacks();
        let push = PushOp {
            which: [true, true, true, true],
        };
        let pop = PopOp {
            which: [true, true, true, true],
        };
        let original = Coord::new(1.0, 2.0, 3.0, 4.0);
        let after_push = push.forward_4d(original)?;
        // push does not modify coordinates
        assert_eq!(after_push.v(), [1.0, 2.0, 3.0, 4.0]);

        // Overwrite the coordinate
        let modified = Coord::new(9.0, 8.0, 7.0, 6.0);
        let restored = pop.forward_4d(modified)?;
        // pop should restore all four components
        assert_eq!(restored.v(), [1.0, 2.0, 3.0, 4.0]);
        Ok(())
    }

    #[test]
    fn push_v1_v2_only_preserves_v3_v4() -> ProjResult<()> {
        clear_stacks();
        let push = PushOp {
            which: [true, true, false, false],
        };
        let pop = PopOp {
            which: [true, true, false, false],
        };
        let original = Coord::new(10.0, 20.0, 30.0, 40.0);
        push.forward_4d(original)?;

        // After modification only v3/v4 changed on the current coord
        let modified = Coord::new(99.0, 88.0, 77.0, 66.0);
        let restored = pop.forward_4d(modified)?;
        // v_1 and v_2 restored; v_3 and v_4 come from `modified`
        assert_eq!(restored.v()[0], 10.0);
        assert_eq!(restored.v()[1], 20.0);
        assert_eq!(restored.v()[2], 77.0);
        assert_eq!(restored.v()[3], 66.0);
        Ok(())
    }

    #[test]
    fn push_inverse_acts_as_pop() -> ProjResult<()> {
        clear_stacks();
        let push = PushOp {
            which: [true, true, true, true],
        };
        // Save via forward (push)
        let saved = Coord::new(5.0, 6.0, 7.0, 8.0);
        push.forward_4d(saved)?;

        // Restore via inverse (pop)
        let modified = Coord::new(0.0, 0.0, 0.0, 0.0);
        let restored = push.inverse_4d(modified)?;
        assert_eq!(restored.v(), [5.0, 6.0, 7.0, 8.0]);
        Ok(())
    }

    #[test]
    fn pop_inverse_acts_as_push() -> ProjResult<()> {
        clear_stacks();
        let pop = PopOp {
            which: [true, true, true, true],
        };
        // Save via inverse (push)
        let saved = Coord::new(11.0, 22.0, 33.0, 44.0);
        pop.inverse_4d(saved)?;

        // Restore via forward (pop)
        let modified = Coord::new(0.0, 0.0, 0.0, 0.0);
        let restored = pop.forward_4d(modified)?;
        assert_eq!(restored.v(), [11.0, 22.0, 33.0, 44.0]);
        Ok(())
    }

    #[test]
    fn no_params_defaults_to_all_components() {
        let which = parse_which(&TransParams {
            ellipsoid: &wgs84(),
            params: &NoParams,
            registry: None,
        });
        assert_eq!(which, [true, true, true, true]);
    }

    #[test]
    fn v1_v2_params_selects_first_two() {
        let which = parse_which(&TransParams {
            ellipsoid: &wgs84(),
            params: &V1V2Params,
            registry: None,
        });
        assert_eq!(which, [true, true, false, false]);
    }

    #[test]
    fn new_push_builds_successfully() {
        let ell = wgs84();
        let p = TransParams {
            ellipsoid: &ell,
            params: &NoParams,
            registry: None,
        };
        assert!(new_push(&p).is_ok());
    }

    #[test]
    fn new_pop_builds_successfully() {
        let ell = wgs84();
        let p = TransParams {
            ellipsoid: &ell,
            params: &NoParams,
            registry: None,
        };
        assert!(new_pop(&p).is_ok());
    }

    #[test]
    fn stack_underflow_leaves_component_unchanged() -> ProjResult<()> {
        clear_stacks();
        let pop = PopOp {
            which: [true, false, false, false],
        };
        // Stack is empty; component should remain as-is (no panic, no error)
        let c = Coord::new(99.0, 1.0, 2.0, 3.0);
        let result = pop.forward_4d(c)?;
        assert_eq!(result.v()[0], 99.0); // unchanged since stack was empty
        Ok(())
    }

    #[test]
    fn push_and_pop_have_inverse() {
        let push = PushOp { which: [true; 4] };
        let pop = PopOp { which: [true; 4] };
        assert!(push.has_inverse());
        assert!(pop.has_inverse());
    }
}