From 8595fb7ce94be07ad9298cc1385c5381b0dfc45a Mon Sep 17 00:00:00 2001 From: Michael Kirk Date: Tue, 7 May 2024 13:05:17 -0700 Subject: [PATCH] inline error checking --- src/lib.rs | 29 +++++++++++++---------------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index ade7a80..e04b4f6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -23,7 +23,7 @@ //! It is thus advisable to pay careful attention to the order of the coordinates you use for encoding and decoding. use geo_types::{Coord, LineString}; -use std::{char, cmp}; +use std::char; const MIN_LONGITUDE: f64 = -180.0; const MAX_LONGITUDE: f64 = 180.0; @@ -35,17 +35,6 @@ fn scale(n: f64, factor: i32) -> i64 { scaled.round() as i64 } -// Bounds checking for input values -fn check(to_check: T, bounds: (T, T)) -> Result -where - T: cmp::PartialOrd + Copy, -{ - match to_check { - to_check if bounds.0 <= to_check && to_check <= bounds.1 => Ok(to_check), - _ => Err(to_check), - } -} - fn encode(delta: i64, output: &mut String) -> Result<(), String> { let mut value = delta << 1; if value < 0 { @@ -84,10 +73,18 @@ where let mut previous = Coord { x: 0, y: 0 }; for (i, next) in coordinates.into_iter().enumerate() { - check(next.y, (MIN_LATITUDE, MAX_LATITUDE)) - .map_err(|e| format!("Latitude error at position {0}: {1}", i, e))?; - check(next.x, (MIN_LONGITUDE, MAX_LONGITUDE)) - .map_err(|e| format!("Longitude error at position {0}: {1}", i, e))?; + if !(MIN_LATITUDE..MAX_LATITUDE).contains(&next.y) { + return Err(format!( + "Invalid latitude: {lat} at position {i}", + lat = next.y + )); + } + if !(MIN_LONGITUDE..MAX_LONGITUDE).contains(&next.x) { + return Err(format!( + "Invalid longitude: {lon} at position {i}", + lon = next.x + )); + } let scaled_next = Coord { x: scale(next.x, factor),