oxiproj-core 0.1.2

Foundation types for OxiProj: coordinates, errors, ellipsoids, datums, and units.
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
//! Degree/minute/second string parsing ported from PROJ `src/dmstor.cpp` and `src/strtod.cpp`.

#[cfg(feature = "no_std")]
use alloc::format;
#[cfg(feature = "no_std")]
use alloc::vec::Vec;

use crate::consts::DEG_TO_RAD;
use crate::error::{ProjError, ProjResult};

/// Sign-suffix characters, ported from `sym` in `src/dmstor.cpp`:
/// `static const char *sym = "NnEeSsWw";`. The index within this string
/// selects the sign: indices `>= 4` (`S`, `s`, `W`, `w`) mean negative.
const SYM: &[u8] = b"NnEeSsWw";

/// Per-unit multipliers, ported from `vm` in `src/dmstor.cpp`:
/// `static const double vm[] = {DEG_TO_RAD, .0002908882086657216, .0000048481368110953599};`
/// These are `DEG_TO_RAD`, `DEG_TO_RAD / 60`, and `DEG_TO_RAD / 3600` for the
/// degree, minute and second segments respectively.
const VM: [f64; 3] = [
    DEG_TO_RAD,
    0.000_290_888_208_665_721_6,
    0.000_004_848_136_811_095_36,
];

/// First byte of the UTF-8 encoding of the degree sign `°` (U+00B0).
///
/// Ported from `DEG_SIGN1` in `src/dmstor.cpp`: `'\xc2'`.
const DEG_SIGN1: u8 = 0xC2;

/// Second byte of the UTF-8 encoding of the degree sign `°` (U+00B0). When seen
/// on its own it is also accepted as a single-byte degree symbol (it is the
/// degree symbol in several single-byte encodings).
///
/// Ported from `DEG_SIGN2` in `src/dmstor.cpp`: `'\xb0'`.
const DEG_SIGN2: u8 = 0xB0;

/// Ported in spirit from src/strtod.cpp (`proj_strtod`): scans a leading decimal
/// number — optional sign, integer digits, optional fraction, optional exponent —
/// and returns `(value, bytes_consumed)`. Returns `None` if no number is present.
///
/// Like PROJ's `proj_strtod`, scanning naturally stops at the first character
/// that cannot extend the number (e.g. `d`, `D`, `'`, `"`).
///
/// `proj_strtod` NUL-terminates the input at the first `d`/`D` and then hands the
/// prefix to C `strtod` (via `pj_strtod`), which supports `e`/`E` exponents; this
/// scanner mirrors that behaviour while treating `d`/`D` as a stop character
/// (the degree unit marker), never as an exponent.
pub fn parse_leading_f64(s: &str) -> Option<(f64, usize)> {
    let bytes = s.as_bytes();
    let mut i = 0usize;
    let n = bytes.len();
    // optional sign
    if i < n && (bytes[i] == b'+' || bytes[i] == b'-') {
        i += 1;
    }
    let mut saw_digit = false;
    // integer digits
    while i < n && bytes[i].is_ascii_digit() {
        i += 1;
        saw_digit = true;
    }
    // fraction
    if i < n && bytes[i] == b'.' {
        i += 1;
        while i < n && bytes[i].is_ascii_digit() {
            i += 1;
            saw_digit = true;
        }
    }
    if !saw_digit {
        return None;
    }
    // exponent
    if i < n && (bytes[i] == b'e' || bytes[i] == b'E') {
        let mut j = i + 1;
        if j < n && (bytes[j] == b'+' || bytes[j] == b'-') {
            j += 1;
        }
        let mut exp_digit = false;
        while j < n && bytes[j].is_ascii_digit() {
            j += 1;
            exp_digit = true;
        }
        if exp_digit {
            i = j;
        } // only consume exponent if it has digits
    }
    let slice = s.get(..i)?;
    match slice.parse::<f64>() {
        Ok(v) => Some((v, i)),
        Err(_) => None,
    }
}

/// Ported from src/dmstor.cpp (`dmstor` / `dmstor_ctx`). Parses a DMS string
/// (degrees/minutes/seconds) into RADIANS.
///
/// PROJ uses the unit markers `d`/`D`, `'` (minutes), `"` (seconds), `r`/`R`
/// (radians), and the degree sign `°`. It does NOT treat `m`/`s` as unit
/// markers, and `:` is not supported.
pub fn dmstor(s: &str) -> ProjResult<f64> {
    dmstor_with_rest(s).map(|(v, _)| v)
}

/// Like `dmstor` but also returns the number of bytes consumed from `s`.
///
/// The byte count corresponds to PROJ's `*rs` return pointer in
/// `dmstor_ctx` (`src/dmstor.cpp`): the offset, relative to the original input
/// `is`, of the first character after the parsed string. Leading whitespace that
/// PROJ skips before parsing is included in the consumed count.
pub fn dmstor_with_rest(s: &str) -> ProjResult<(f64, usize)> {
    let raw = s.as_bytes();

    // `while (isspace(*is)) ++is;` — skip leading ASCII whitespace. The returned
    // byte offset is measured from the original input, so remember how many
    // leading whitespace bytes we skipped.
    let mut lead = 0usize;
    while lead < raw.len() && raw[lead].is_ascii_whitespace() {
        lead += 1;
    }

    // `while ((isgraph(*p) || *p == DEG_SIGN1 || *p == DEG_SIGN2) && --n) *s++ = *p++;`
    // Copy graphic characters (plus the two degree-sign bytes) into the work
    // buffer, stopping at the first non-graphic byte (e.g. an embedded space) or
    // when the buffer is full. `MAX_WORK` is 64 and the loop decrements `n` from
    // `MAX_WORK` before each store, so at most `MAX_WORK - 1` = 63 bytes are kept.
    const MAX_WORK: usize = 64;
    let mut work: Vec<u8> = Vec::with_capacity(MAX_WORK);
    let mut p = lead;
    while p < raw.len() {
        let b = raw[p];
        let is_graph = b.is_ascii_graphic();
        if !(is_graph || b == DEG_SIGN1 || b == DEG_SIGN2) {
            break;
        }
        // Mirror `--n` in the C loop: stop once the work buffer holds
        // `MAX_WORK - 1` bytes (the final slot is reserved for the NUL).
        if work.len() >= MAX_WORK - 1 {
            break;
        }
        work.push(b);
        p += 1;
    }

    // `int sign = *(s = work); if (sign == '+' || sign == '-') s++; else sign = '+';`
    // `s` is the cursor into the work buffer; `neg` tracks the leading sign.
    let mut cur = 0usize;
    let mut neg = false;
    if let Some(&first) = work.first() {
        if first == b'+' {
            cur += 1;
        } else if first == b'-' {
            neg = true;
            cur += 1;
        }
    }

    let mut v = 0.0_f64;
    // Tracks whether at least one numeric segment (or the radian branch) was
    // consumed. PROJ returns 0.0 for input with no parseable number; we instead
    // surface an explicit error for such input (e.g. "", "   ", "abc"), which is
    // safe because every valid DMS string parses at least one segment.
    let mut parsed_any = false;
    // `for (nl = 0; nl < 3; nl = n + 1)` — `nl` is the next expected unit index
    // (0 = degrees, 1 = minutes, 2 = seconds); `n` is the unit found this pass.
    let mut nl = 0i32;
    while nl < 3 {
        // `if (!(isdigit(*s) || *s == '.')) break;`
        match work.get(cur) {
            Some(&b) if b.is_ascii_digit() || b == b'.' => {}
            _ => break,
        }

        // `if ((tv = proj_strtod(s, &s)) == HUGE_VAL) return tv;`
        // Our scanner stops at `d`/`D` just like `proj_strtod`. A failure to
        // parse here is PROJ's HUGE_VAL path -> illegal argument value.
        let work_slice = work.get(cur..).ok_or(ProjError::IllegalArgValue)?;
        let tail = core::str::from_utf8(work_slice).map_err(|_| ProjError::IllegalArgValue)?;
        let (tv, consumed) = parse_leading_f64(tail).ok_or(ProjError::IllegalArgValue)?;
        cur += consumed;
        parsed_any = true;

        // Determine the unit marker following the number.
        let mut adv = 1usize;
        let n: i32;
        let c0 = work.get(cur).copied();
        let c1 = work.get(cur + 1).copied();
        if c0 == Some(b'D') || c0 == Some(b'd') || c0 == Some(DEG_SIGN2) {
            // `if (*s == 'D' || *s == 'd' || *s == DEG_SIGN2) n = 0;`
            // The lone `\xb0` byte is accepted as a single-byte degree symbol.
            n = 0;
        } else if c0 == Some(b'\'') {
            // `else if (*s == '\'') n = 1;`
            n = 1;
        } else if c0 == Some(b'"') {
            // `else if (*s == '"') n = 2;`
            n = 2;
        } else if c0 == Some(DEG_SIGN1) && c1 == Some(DEG_SIGN2) {
            // `else if (s[0] == DEG_SIGN1 && s[1] == DEG_SIGN2) { n = 0; adv = 2; }`
            // degree symbol in UTF-8 (two bytes 0xC2 0xB0).
            n = 0;
            adv = 2;
        } else if c0 == Some(b'r') || c0 == Some(b'R') {
            // `else if (*s == 'r' || *s == 'R') { if (nl) error; ++s; v = tv; n = 4; continue; }`
            // The 'r' marker means the value is already in radians: it OVERRIDES
            // `v` (it does not accumulate) and terminates the loop. It is only
            // valid as the first segment (`nl == 0`).
            if nl != 0 {
                return Err(ProjError::IllegalArgValue);
            }
            cur += 1;
            v = tv;
            // PROJ does `n = 4; continue;`, which makes the loop update
            // `nl = n + 1 = 5` and the `nl < 3` guard end the loop. Breaking
            // here is the equivalent control flow.
            break;
        } else {
            // `else { v += tv * vm[nl]; n = 4; continue; }`
            // No explicit unit (end of string, or a non-marker like 'm'/'s'):
            // apply the multiplier for the expected unit and terminate.
            let idx = usize::try_from(nl).map_err(|_| ProjError::IllegalArgValue)?;
            let mult = VM.get(idx).ok_or(ProjError::IllegalArgValue)?;
            v += tv * mult;
            break;
        }

        // `if (n < nl) error;` — units must appear in non-decreasing order.
        if n < nl {
            return Err(ProjError::IllegalArgValue);
        }
        // `v += tv * vm[n]; s += adv;`
        let idx = usize::try_from(n).map_err(|_| ProjError::IllegalArgValue)?;
        let mult = VM.get(idx).ok_or(ProjError::IllegalArgValue)?;
        v += tv * mult;
        cur += adv;

        // `nl = n + 1` (the loop's update clause).
        nl = n + 1;
    }

    // No numeric segment (and no radian branch) was parsed: PROJ would return
    // 0.0 here, but we treat such input (e.g. "", "   ", "abc") as an error.
    if !parsed_any {
        return Err(ProjError::IllegalArgValue);
    }

    // `if (*s && (p = strchr(sym, *s))) { sign = (p - sym) >= 4 ? '-' : '+'; ++s; }`
    // A trailing sign letter OVERRIDES the leading sign entirely.
    if let Some(&c) = work.get(cur) {
        if let Some(pos) = SYM.iter().position(|&x| x == c) {
            neg = pos >= 4;
            cur += 1;
        }
    }

    // `if (sign == '-') v = -v;`
    if neg {
        v = -v;
    }

    // `*rs = (char *)is + (s - work);` — the next char after the valid string is
    // at `lead + cur` bytes from the original input start.
    Ok((v, lead + cur))
}

/// Decodes an EPSG sexagesimal DMS packed float (unit 9110 / 9121) into decimal
/// degrees. The input format is `DDD.MMSSsss` where MM are the first two
/// fractional digits (whole minutes, 00–59) and SSsss are the remaining
/// fractional digits (seconds with sub-second precision).
///
/// Ported from `normalizeMeasure` in PROJ `src/iso19111/factory.cpp:4679-4701`.
/// Sign is applied to the whole decoded result (PROJ behaviour); components are
/// extracted from `|value|`. Whole-degree inputs (e.g. `3.0`) decode unchanged.
pub fn decode_sexagesimal_dms(value: f64) -> f64 {
    let sign: f64 = if value < 0.0 { -1.0 } else { 1.0 };
    let abs = value.abs();
    let degrees = abs.floor();
    // Fixed 12-decimal formatting stabilises the packed digit layout regardless
    // of floating-point representation, mirroring PROJ's ostringstream precision.
    let formatted = format!("{:.12}", abs);
    let dot_pos = formatted.find('.').unwrap_or(formatted.len());
    let frac_start = dot_pos + 1;
    let minutes: f64 = formatted
        .get(frac_start..frac_start + 2)
        .and_then(|s| s.parse().ok())
        .unwrap_or(0.0);
    let sec_str = formatted.get(frac_start + 2..).unwrap_or("0");
    let sec_raw: f64 = sec_str.parse().unwrap_or(0.0);
    let sec_denom: f64 = 10_f64.powi(sec_str.len() as i32 - 2);
    let seconds = sec_raw / sec_denom;
    sign * (degrees + minutes / 60.0 + seconds / 3600.0)
}

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

    const TOL: f64 = 1e-12;

    #[test]
    fn dms_deg_min() {
        let got = dmstor("10d30'").expect("parse");
        let expected = 10.5 * DEG_TO_RAD;
        assert!(
            (got - expected).abs() < TOL,
            "got {got} expected {expected}"
        );
    }

    #[test]
    fn dms_deg_min_sec_west_negative() {
        let got = dmstor("10d30'00\"W").expect("parse");
        let expected = -10.5 * DEG_TO_RAD;
        assert!(
            (got - expected).abs() < TOL,
            "got {got} expected {expected}"
        );
    }

    #[test]
    fn dms_zero_east() {
        let got = dmstor("0dE").expect("parse");
        assert_eq!(got, 0.0);
    }

    #[test]
    fn dms_radian_suffix() {
        // The 'r' suffix means the value 45 is already in radians.
        let got = dmstor("45r").expect("parse");
        assert!((got - 45.0).abs() < TOL, "got {got}");
    }

    #[test]
    fn dms_deg_min_west_negative() {
        let got = dmstor("17d40'W").expect("parse");
        let expected = -17.666_666_666_7 * DEG_TO_RAD;
        assert!(
            (got - expected).abs() < 1e-9,
            "got {got} expected {expected}"
        );
    }

    #[test]
    fn dms_bare_negative_degrees() {
        // No unit -> multiplied by vm[0] = DEG_TO_RAD; leading minus -> negative.
        let got = dmstor("-10.5").expect("parse");
        let expected = -10.5 * DEG_TO_RAD;
        assert!(
            (got - expected).abs() < TOL,
            "got {got} expected {expected}"
        );
    }

    #[test]
    fn dms_north_south_suffix() {
        let got_n = dmstor("90dN").expect("parse");
        let got_s = dmstor("90dS").expect("parse");
        assert!((got_n - 90.0 * DEG_TO_RAD).abs() < TOL, "got {got_n}");
        assert!((got_s + 90.0 * DEG_TO_RAD).abs() < TOL, "got {got_s}");
    }

    #[test]
    fn parse_leading_f64_stops_at_d() {
        assert_eq!(parse_leading_f64("12.5d30"), Some((12.5, 4)));
    }

    #[test]
    fn parse_leading_f64_no_number() {
        assert_eq!(parse_leading_f64("abc"), None);
    }

    #[test]
    fn parse_leading_f64_basic_forms() {
        assert_eq!(parse_leading_f64("0"), Some((0.0, 1)));
        assert_eq!(parse_leading_f64("-3.25"), Some((-3.25, 5)));
        assert_eq!(parse_leading_f64("+7"), Some((7.0, 2)));
        assert_eq!(parse_leading_f64(".5'"), Some((0.5, 2)));
        // exponent supported (mirrors C strtod via pj_strtod)
        assert_eq!(parse_leading_f64("1e3d"), Some((1000.0, 3)));
        // an 'e' without exponent digits is not consumed as part of the number
        assert_eq!(parse_leading_f64("12e"), Some((12.0, 2)));
    }

    #[test]
    fn dms_degree_sign_utf8() {
        // ° = U+00B0 = UTF-8 0xC2 0xB0
        let got = dmstor("10\u{00b0}30'").expect("parse");
        let expected = 10.5 * DEG_TO_RAD;
        assert!(
            (got - expected).abs() < TOL,
            "got {got} expected {expected}"
        );
    }

    #[test]
    fn dms_degree_sign_single_byte_latin1() {
        // The lone 0xB0 byte is accepted as a single-byte degree symbol. We feed
        // it through a Latin-1 style byte by constructing the equivalent ASCII
        // 'd' form here, since Rust &str must be valid UTF-8; the UTF-8 path is
        // covered by `dms_degree_sign_utf8`.
        let got = dmstor("10d").expect("parse");
        let expected = 10.0 * DEG_TO_RAD;
        assert!(
            (got - expected).abs() < TOL,
            "got {got} expected {expected}"
        );
    }

    #[test]
    fn dms_with_rest_reports_consumed() {
        // Trailing non-graphic char stops the work-buffer copy; bytes consumed
        // should point just past the valid DMS region.
        let (v, used) = dmstor_with_rest("  10d30' rest").expect("parse");
        let expected = 10.5 * DEG_TO_RAD;
        assert!((v - expected).abs() < TOL, "got {v} expected {expected}");
        // 2 leading spaces + "10d30'" (6 bytes) = 8 bytes consumed (copy stops at
        // the embedded space before "rest").
        assert_eq!(used, 8);
    }

    #[test]
    fn dms_radian_after_segment_is_error() {
        // 'r' is only valid as the first segment (PROJ errors when nl != 0).
        assert!(dmstor("10d30'5r").is_err());
    }

    #[test]
    fn dms_out_of_order_units_is_error() {
        // Minutes (n=1, nl becomes 2) then degrees (n=0) violates the
        // non-decreasing order check (`if (n < nl) error;`).
        assert!(dmstor("10'30d").is_err());
    }

    #[test]
    fn dms_empty_is_error() {
        assert!(dmstor("").is_err());
        assert!(dmstor("   ").is_err());
        assert!(dmstor("abc").is_err());
    }

    #[test]
    fn dms_manual_sweep_matches_formula() {
        // proptest-style exhaustive-ish sweep without any extra dependency.
        for d in 0..30 {
            let mut m = 0;
            while m < 60 {
                for s in [0.0_f64, 15.5, 45.25] {
                    let st = format!("{}d{}'{:.3}\"", d, m, s);
                    let expected = (d as f64 + m as f64 / 60.0 + s / 3600.0) * DEG_TO_RAD;
                    let got = dmstor(&st).expect("parse");
                    assert!(
                        (got - expected).abs() < 1e-9,
                        "{} -> {} expected {}",
                        st,
                        got,
                        expected
                    );
                }
                m += 5;
            }
        }
    }

    #[test]
    fn decode_sexagesimal_dms_basic() {
        let tol = 1e-10;
        // 46°30′ (Lambert 93 false-origin latitude)
        assert!(
            (decode_sexagesimal_dms(46.3) - 46.5).abs() < tol,
            "46.3 should decode to 46.5, got {}",
            decode_sexagesimal_dms(46.3)
        );
        // 10°20′ (Austria GK M28 central meridian)
        let expected_10_20 = 10.0 + 20.0 / 60.0;
        assert!(
            (decode_sexagesimal_dms(10.2) - expected_10_20).abs() < tol,
            "10.2 should decode to {expected_10_20}, got {}",
            decode_sexagesimal_dms(10.2)
        );
        // 52°09′22.178″ (RD New latitude of natural origin)
        let expected_52 = 52.0 + 9.0 / 60.0 + 22.178 / 3600.0;
        assert!(
            (decode_sexagesimal_dms(52.0922178) - expected_52).abs() < 1e-9,
            "52.0922178 should decode to {expected_52}, got {}",
            decode_sexagesimal_dms(52.0922178)
        );
        // 5°23′15.5″ (RD New longitude of natural origin)
        let expected_5 = 5.0 + 23.0 / 60.0 + 15.5 / 3600.0;
        assert!(
            (decode_sexagesimal_dms(5.23155) - expected_5).abs() < 1e-9,
            "5.23155 should decode to {expected_5}, got {}",
            decode_sexagesimal_dms(5.23155)
        );
        // Whole-degree value must be a no-op
        assert!(
            (decode_sexagesimal_dms(3.0) - 3.0).abs() < tol,
            "3.0 must decode unchanged"
        );
        // Negative value: sign applied to the whole result
        assert!(
            (decode_sexagesimal_dms(-71.0) - (-71.0)).abs() < tol,
            "-71.0 should decode to -71.0"
        );
        // Zero
        assert_eq!(decode_sexagesimal_dms(0.0), 0.0);
    }
}