1use thiserror::Error;
4
5pub type Result<T> = std::result::Result<T, Error>;
7
8pub fn check_range(name: &str, value: f64, min: f64, max: f64) -> Result<()> {
15 if value >= min && value <= max {
16 Ok(())
17 } else {
18 Err(Error::OutOfRange {
19 parameter: name.to_string(),
20 id: None,
21 min: Some(min),
22 max: Some(max),
23 exclusive_min: None,
24 exclusive_max: None,
25 got: value,
26 range: format!("in [{min}, {max}]"),
27 })
28 }
29}
30
31pub fn check_at_least(name: &str, value: f64, min: f64) -> Result<()> {
38 if value.is_finite() && value >= min {
39 Ok(())
40 } else {
41 Err(Error::OutOfRange {
42 parameter: name.to_string(),
43 id: None,
44 min: Some(min),
45 max: None,
46 exclusive_min: None,
47 exclusive_max: None,
48 got: value,
49 range: format!("a finite number >= {min}"),
50 })
51 }
52}
53
54pub fn check_above(name: &str, value: f64, bound: f64) -> Result<()> {
61 if value.is_finite() && value > bound {
62 Ok(())
63 } else {
64 Err(Error::OutOfRange {
65 parameter: name.to_string(),
66 id: None,
67 min: None,
68 max: None,
69 exclusive_min: Some(bound),
70 exclusive_max: None,
71 got: value,
72 range: format!("a finite number > {bound}"),
73 })
74 }
75}
76
77pub trait WholeNumber: TryFrom<i128> + Copy {
80 const MAX: i128;
82}
83
84impl WholeNumber for u32 {
85 const MAX: i128 = u32::MAX as i128;
86}
87
88impl WholeNumber for u64 {
89 const MAX: i128 = u64::MAX as i128;
90}
91
92impl WholeNumber for usize {
93 const MAX: i128 = usize::MAX as i128;
94}
95
96pub fn whole_at_least<T: WholeNumber>(parameter: &str, value: i128, min: i128) -> Result<T> {
107 match T::try_from(value) {
108 Ok(v) if value >= min => Ok(v),
109 _ => {
110 let above = value > T::MAX;
111 Err(Error::OutOfRange {
112 parameter: parameter.to_string(),
113 id: None,
114 min: Some(min as f64),
115 max: above.then_some(T::MAX as f64),
116 exclusive_min: None,
117 exclusive_max: None,
118 got: value as f64,
119 range: if above {
120 format!("a whole number in [{min}, {}]", T::MAX)
121 } else {
122 format!("a whole number >= {min}")
123 },
124 })
125 }
126 }
127}
128
129#[derive(Debug, Clone, PartialEq, Error)]
134#[non_exhaustive]
135pub enum Error {
136 #[error("{parameter} must be {range}, got {got}")]
143 OutOfRange {
144 parameter: String,
145 id: Option<String>,
146 min: Option<f64>,
147 max: Option<f64>,
148 exclusive_min: Option<f64>,
149 exclusive_max: Option<f64>,
150 got: f64,
151 range: String,
152 },
153
154 #[error("{parameter} is empty; give at least one")]
157 EmptyInput { parameter: String },
158
159 #[error("{parameter}: {message}")]
162 InvalidOption { parameter: String, message: String },
163
164 #[error("unknown {parameter} '{got}'; expected one of {}", expected.join(", "))]
167 UnknownOption {
168 parameter: String,
169 got: String,
170 expected: Vec<String>,
171 },
172
173 #[error("{message}")]
176 MalformedInput {
177 parameter: Option<String>,
178 message: String,
179 },
180
181 #[error("cancelled by the caller")]
183 Cancelled,
184
185 #[error("Invalid geometry: {message}")]
188 InvalidGeometry { id: Option<String>, message: String },
189
190 #[error(
193 "the id '{id}' is given twice, at positions {first} and {second} of geometries \
194 (counting from 0); placements name geometries by id, so every geometry needs \
195 its own"
196 )]
197 DuplicateId {
198 id: String,
199 first: usize,
200 second: usize,
201 },
202
203 #[error("Invalid boundary: {message}")]
206 InvalidBoundary {
207 parameter: Option<String>,
208 message: String,
209 },
210
211 #[error("Internal error: {0}")]
213 Internal(String),
214}
215
216impl Error {
217 pub fn code(&self) -> &'static str {
222 match self {
223 Error::OutOfRange { .. } => "parameter_out_of_range",
224 Error::EmptyInput { .. } => "empty_input",
225 Error::InvalidOption { .. } => "invalid_option",
226 Error::UnknownOption { .. } => "unknown_option",
227 Error::MalformedInput { .. } => "malformed_input",
228 Error::Cancelled => "cancelled",
229 Error::InvalidGeometry { .. } => "invalid_geometry",
230 Error::DuplicateId { .. } => "duplicate_id",
231 Error::InvalidBoundary { .. } => "invalid_boundary",
232 Error::Internal(_) => "internal",
233 }
234 }
235
236 pub fn parameter(&self) -> Option<&str> {
238 match self {
239 Error::OutOfRange { parameter, .. }
240 | Error::EmptyInput { parameter }
241 | Error::InvalidOption { parameter, .. }
242 | Error::UnknownOption { parameter, .. } => Some(parameter),
243 Error::MalformedInput { parameter, .. } | Error::InvalidBoundary { parameter, .. } => {
244 parameter.as_deref()
245 }
246 Error::DuplicateId { .. } => Some("geometries"),
247 _ => None,
248 }
249 }
250
251 pub fn located(mut self, section: &str, fields: &[&str]) -> Self {
259 let parameter = match &mut self {
260 Error::OutOfRange { parameter, .. }
261 | Error::EmptyInput { parameter }
262 | Error::InvalidOption { parameter, .. }
263 | Error::UnknownOption { parameter, .. } => Some(parameter),
264 Error::MalformedInput { parameter, .. } | Error::InvalidBoundary { parameter, .. } => {
265 parameter.as_mut()
266 }
267 _ => None,
268 };
269 if let Some(parameter) = parameter {
270 if fields.contains(¶meter.as_str()) {
271 *parameter = format!("{section}.{parameter}");
272 }
273 }
274 self
275 }
276
277 pub fn empty_input(parameter: &str) -> Self {
279 Error::EmptyInput {
280 parameter: parameter.to_string(),
281 }
282 }
283
284 pub fn invalid_option(parameter: &str, message: String) -> Self {
286 Error::InvalidOption {
287 parameter: parameter.to_string(),
288 message,
289 }
290 }
291
292 pub fn invalid_geometry(id: Option<&str>, message: String) -> Self {
294 Error::InvalidGeometry {
295 id: id.map(str::to_string),
296 message,
297 }
298 }
299
300 pub fn malformed(parameter: Option<&str>, message: String) -> Self {
302 Error::MalformedInput {
303 parameter: parameter.map(str::to_string),
304 message,
305 }
306 }
307
308 pub fn invalid_boundary(parameter: Option<&str>, message: String) -> Self {
310 Error::InvalidBoundary {
311 parameter: parameter.map(str::to_string),
312 message,
313 }
314 }
315}