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
//! Error type ported from PROJ `src/proj.h` (PROJ_ERR_* codes).

#[cfg(feature = "no_std")]
use alloc::string::String;

use thiserror::Error;

/// Error type mirroring PROJ's `PROJ_ERR_*` codes.
///
/// The numeric codes are grouped by base values defined in `src/proj.h`:
/// - `PROJ_ERR_INVALID_OP` (1024): invalid operation / wrong setup.
/// - `PROJ_ERR_COORD_TRANSFM` (2048): coordinate transformation failures.
/// - `PROJ_ERR_OTHER` (4096): all other errors.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum ProjError {
    /// Generic invalid operation (`PROJ_ERR_INVALID_OP` = 1024).
    #[error("invalid PROJ string syntax or operation")]
    InvalidOp,

    /// Invalid PROJ string syntax (`PROJ_ERR_INVALID_OP_WRONG_SYNTAX` = 1025).
    #[error("invalid PROJ string syntax")]
    WrongSyntax,

    /// Missing required operation parameter
    /// (`PROJ_ERR_INVALID_OP_MISSING_ARG` = 1026).
    #[error("missing required operation parameter")]
    MissingArg,

    /// One of the operation parameters has an illegal value
    /// (`PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE` = 1027).
    #[error("one of the operation parameters has an illegal value")]
    IllegalArgValue,

    /// Mutually exclusive arguments
    /// (`PROJ_ERR_INVALID_OP_MUTUALLY_EXCLUSIVE_ARGS` = 1028).
    #[error("mutually exclusive arguments")]
    MutuallyExclusiveArgs,

    /// File not found or with invalid content
    /// (`PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID` = 1029).
    #[error("file not found or with invalid content")]
    FileNotFound,

    /// Value does not correspond to an ellipsoid (maps to code 1027,
    /// same as [`ProjError::IllegalArgValue`]).
    #[error("value does not correspond to an ellipsoid")]
    NotEllipsoid,

    /// Generic error of coordinate transformation
    /// (`PROJ_ERR_COORD_TRANSFM` = 2048).
    #[error("generic error of coordinate transformation")]
    CoordTransfm,

    /// Invalid coordinate (`PROJ_ERR_COORD_TRANSFM_INVALID_COORD` = 2049).
    #[error("invalid coordinate")]
    InvalidCoord,

    /// Coordinate outside projection domain
    /// (`PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN` = 2050).
    #[error("coordinate outside projection domain")]
    OutsideProjectionDomain,

    /// No operation found matching criteria
    /// (`PROJ_ERR_COORD_TRANSFM_NO_OPERATION` = 2051).
    #[error("no operation found matching criteria")]
    NoOperation,

    /// Point to transform falls outside grid or subgrid
    /// (`PROJ_ERR_COORD_TRANSFM_OUTSIDE_GRID` = 2052).
    #[error("point to transform falls outside grid or subgrid")]
    OutsideGrid,

    /// Point to transform falls in a grid cell that evaluates to nodata
    /// (`PROJ_ERR_COORD_TRANSFM_GRID_AT_NODATA` = 2053).
    #[error("point to transform falls in a grid cell that evaluates to nodata")]
    GridAtNodata,

    /// Iterative algorithm did not converge
    /// (`PROJ_ERR_COORD_TRANSFM_NO_CONVERGENCE` = 2054).
    #[error("iterative algorithm did not converge")]
    NoConvergence,

    /// Missing required time coordinate
    /// (`PROJ_ERR_COORD_TRANSFM_MISSING_TIME` = 2055).
    #[error("missing required time coordinate")]
    MissingTime,

    /// Invalid CRS definition with a descriptive message.
    ///
    /// Use this variant when the error is specifically a CRS definition
    /// problem and you can provide a helpful message (and optionally a
    /// suggestion for fixing it).
    #[error("Invalid CRS definition: {message}")]
    InvalidCrs {
        /// Human-readable description of the problem.
        message: String,
        /// Optional suggestion for resolving the error.
        suggestion: Option<String>,
    },

    /// Coordinate out of bounds.
    ///
    /// Carries a descriptive message and an optional suggestion.
    #[error("Coordinate out of bounds: {message}")]
    OutOfBounds {
        /// Human-readable description of the problem.
        message: String,
        /// Optional suggestion for resolving the error.
        suggestion: Option<String>,
    },

    /// Projection computation failed.
    ///
    /// Carries a descriptive message about the computation failure.
    #[error("Projection failed: {message}")]
    ProjectionFailed {
        /// Human-readable description of the failure.
        message: String,
    },

    /// Operation not supported (e.g. AD path not implemented for this projection).
    #[error("operation not supported")]
    UnsupportedOperation,

    /// Other error (`PROJ_ERR_OTHER` = 4096).
    #[error("other error")]
    Other,

    /// Error caused by incorrect use of PROJ API
    /// (`PROJ_ERR_OTHER_API_MISUSE` = 4097).
    #[error("error caused by incorrect use of PROJ API")]
    ApiMisuse,

    /// No inverse operation (`PROJ_ERR_OTHER_NO_INVERSE_OP` = 4098).
    #[error("no inverse operation")]
    NoInverseOp,

    /// Failure when accessing a network resource
    /// (`PROJ_ERR_OTHER_NETWORK_ERROR` = 4099).
    #[error("failure when accessing a network resource")]
    NetworkError,
}

impl ProjError {
    /// Ported from src/proj.h (PROJ_ERR_* numeric codes)
    pub fn code(&self) -> i32 {
        match self {
            ProjError::InvalidOp => 1024,
            ProjError::WrongSyntax => 1025,
            ProjError::MissingArg => 1026,
            ProjError::IllegalArgValue => 1027,
            ProjError::MutuallyExclusiveArgs => 1028,
            ProjError::FileNotFound => 1029,
            ProjError::NotEllipsoid => 1027,
            ProjError::CoordTransfm => 2048,
            ProjError::InvalidCoord => 2049,
            ProjError::OutsideProjectionDomain => 2050,
            ProjError::NoOperation => 2051,
            ProjError::OutsideGrid => 2052,
            ProjError::GridAtNodata => 2053,
            ProjError::NoConvergence => 2054,
            ProjError::MissingTime => 2055,
            ProjError::InvalidCrs { .. } => 1024,
            ProjError::OutOfBounds { .. } => 2050,
            ProjError::ProjectionFailed { .. } => 2048,
            ProjError::UnsupportedOperation => 4096,
            ProjError::Other => 4096,
            ProjError::ApiMisuse => 4097,
            ProjError::NoInverseOp => 4098,
            ProjError::NetworkError => 4099,
        }
    }

    /// Returns a human-readable suggestion for resolving this error, if one
    /// is available.
    ///
    /// Returns `Some` for variants that carry a `suggestion` field (when one
    /// was provided at construction time) as well as for several well-known
    /// unit variants where a static hint is always useful.
    pub fn suggestion(&self) -> Option<&str> {
        match self {
            ProjError::InvalidCrs { suggestion, .. } => suggestion.as_deref(),
            ProjError::OutOfBounds { suggestion, .. } => suggestion.as_deref(),
            ProjError::MissingArg => Some(
                "verify that +proj= is specified; \
                 common values: merc, lcc, tmerc, utm, stere, aeqd, longlat",
            ),
            ProjError::IllegalArgValue => {
                Some("check that all numeric parameters are valid and in the expected range")
            }
            ProjError::FileNotFound => Some(
                "ensure the grid file is accessible; \
                 use create_with_ctx() to register in-memory grids",
            ),
            ProjError::WrongSyntax => Some(
                "check the proj-string syntax; \
                 each keyword must start with + (e.g. +proj=merc +ellps=WGS84)",
            ),
            ProjError::NoInverseOp => Some(
                "this projection does not support an inverse operation; \
                 try a pipeline with an explicit inverse step",
            ),
            ProjError::InvalidCoord => Some(
                "verify that input coordinates are in the expected unit \
                 (degrees or metres) and within the projection domain",
            ),
            ProjError::OutsideGrid => Some(
                "the coordinate falls outside all available grid files; \
                 verify the grid coverage area",
            ),
            _ => None,
        }
    }
}

/// Convenience alias for results returning a [`ProjError`].
pub type ProjResult<T> = Result<T, ProjError>;

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(feature = "no_std")]
    use alloc::string::ToString;

    #[test]
    fn invalid_op_code() {
        assert_eq!(ProjError::InvalidOp.code(), 1024);
    }

    #[test]
    fn wrong_syntax_code() {
        assert_eq!(ProjError::WrongSyntax.code(), 1025);
    }

    #[test]
    fn missing_arg_code() {
        assert_eq!(ProjError::MissingArg.code(), 1026);
    }

    #[test]
    fn illegal_arg_value_code() {
        assert_eq!(ProjError::IllegalArgValue.code(), 1027);
    }

    #[test]
    fn mutually_exclusive_args_code() {
        assert_eq!(ProjError::MutuallyExclusiveArgs.code(), 1028);
    }

    #[test]
    fn file_not_found_code() {
        assert_eq!(ProjError::FileNotFound.code(), 1029);
    }

    #[test]
    fn not_ellipsoid_code() {
        assert_eq!(ProjError::NotEllipsoid.code(), 1027);
    }

    #[test]
    fn coord_transfm_code() {
        assert_eq!(ProjError::CoordTransfm.code(), 2048);
    }

    #[test]
    fn invalid_coord_code() {
        assert_eq!(ProjError::InvalidCoord.code(), 2049);
    }

    #[test]
    fn outside_projection_domain_code() {
        assert_eq!(ProjError::OutsideProjectionDomain.code(), 2050);
    }

    #[test]
    fn no_operation_code() {
        assert_eq!(ProjError::NoOperation.code(), 2051);
    }

    #[test]
    fn outside_grid_code() {
        assert_eq!(ProjError::OutsideGrid.code(), 2052);
    }

    #[test]
    fn grid_at_nodata_code() {
        assert_eq!(ProjError::GridAtNodata.code(), 2053);
    }

    #[test]
    fn no_convergence_code() {
        assert_eq!(ProjError::NoConvergence.code(), 2054);
    }

    #[test]
    fn missing_time_code() {
        assert_eq!(ProjError::MissingTime.code(), 2055);
    }

    #[test]
    fn other_code() {
        assert_eq!(ProjError::Other.code(), 4096);
    }

    #[test]
    fn api_misuse_code() {
        assert_eq!(ProjError::ApiMisuse.code(), 4097);
    }

    #[test]
    fn no_inverse_op_code() {
        assert_eq!(ProjError::NoInverseOp.code(), 4098);
    }

    #[test]
    fn network_error_code() {
        assert_eq!(ProjError::NetworkError.code(), 4099);
    }

    #[test]
    fn display_messages_non_empty() {
        assert!(!ProjError::InvalidCoord.to_string().is_empty());
        assert!(!ProjError::OutsideProjectionDomain.to_string().is_empty());
    }

    #[test]
    fn proj_result_alias_works() {
        let ok: ProjResult<i32> = Ok(7);
        let err: ProjResult<i32> = Err(ProjError::Other);
        assert_eq!(ok, Ok(7));
        assert_eq!(err, Err(ProjError::Other));
    }

    #[test]
    fn invalid_crs_code_and_suggestion() {
        let e = ProjError::InvalidCrs {
            message: "bad epsg".to_string(),
            suggestion: Some("try EPSG:4326".to_string()),
        };
        assert_eq!(e.code(), 1024);
        assert_eq!(e.suggestion(), Some("try EPSG:4326"));
        assert!(!e.to_string().is_empty());
    }

    #[test]
    fn out_of_bounds_code_and_suggestion() {
        let e = ProjError::OutOfBounds {
            message: "lat 100".to_string(),
            suggestion: None,
        };
        assert_eq!(e.code(), 2050);
        assert_eq!(e.suggestion(), None);
    }

    #[test]
    fn projection_failed_code() {
        let e = ProjError::ProjectionFailed {
            message: "singular matrix".to_string(),
        };
        assert_eq!(e.code(), 2048);
        assert_eq!(e.suggestion(), None);
    }

    #[test]
    fn suggestion_returns_none_for_unit_variants() {
        assert_eq!(ProjError::Other.suggestion(), None);
        assert_eq!(ProjError::InvalidOp.suggestion(), None);
    }

    #[test]
    fn suggestion_missing_arg() {
        assert!(ProjError::MissingArg.suggestion().is_some());
    }

    #[test]
    fn suggestion_illegal_arg_value() {
        assert!(ProjError::IllegalArgValue.suggestion().is_some());
    }

    #[test]
    fn suggestion_file_not_found() {
        assert!(ProjError::FileNotFound.suggestion().is_some());
    }

    #[test]
    fn suggestion_wrong_syntax() {
        assert!(ProjError::WrongSyntax.suggestion().is_some());
    }

    #[test]
    fn suggestion_no_inverse_op() {
        assert!(ProjError::NoInverseOp.suggestion().is_some());
    }

    #[test]
    fn suggestion_invalid_coord() {
        assert!(ProjError::InvalidCoord.suggestion().is_some());
    }

    #[test]
    fn suggestion_outside_grid() {
        assert!(ProjError::OutsideGrid.suggestion().is_some());
    }

    #[test]
    fn suggestion_other_returns_none() {
        assert!(ProjError::Other.suggestion().is_none());
        assert!(ProjError::CoordTransfm.suggestion().is_none());
        assert!(ProjError::NetworkError.suggestion().is_none());
    }
}