diff --git a/src/errors.rs b/src/errors.rs index b170096..5c68eeb 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -1,5 +1,7 @@ //! Errors that can occur during encoding / decoding of Polylines +use geo_types::Coord; + #[derive(Debug, PartialEq)] #[non_exhaustive] pub enum PolylineError { @@ -23,7 +25,12 @@ pub enum PolylineError { /// The string index of the character that caused the decoding error idx: usize, }, - DecodeCharError, + EncodeToCharError, + CoordEncodingError { + coord: Coord, + /// The array index of the coordinate error + idx: usize, + }, } impl std::error::Error for PolylineError {} @@ -31,10 +38,10 @@ impl std::fmt::Display for PolylineError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { PolylineError::LongitudeCoordError { coord, idx } => { - write!(f, "invalid longitude: {} at position {}", coord, idx) + write!(f, "longitude out of bounds: {} at position {}", coord, idx) } PolylineError::LatitudeCoordError { coord, idx } => { - write!(f, "invalid latitude: {} at position {}", coord, idx) + write!(f, "latitude out of bounds: {} at position {}", coord, idx) } PolylineError::DecodeError { idx } => { write!(f, "cannot decode character at index {}", idx) @@ -42,7 +49,14 @@ impl std::fmt::Display for PolylineError { PolylineError::NoLongError { idx } => { write!(f, "no longitude to go with latitude at index: {}", idx) } - PolylineError::DecodeCharError => write!(f, "couldn't decode character"), + PolylineError::EncodeToCharError => write!(f, "couldn't encode character"), + PolylineError::CoordEncodingError { coord, idx } => { + write!( + f, + "the coordinate {:?} at index: {} could not be encoded", + coord, idx + ) + } } } } diff --git a/src/lib.rs b/src/lib.rs index f9d3c5f..506a582 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -47,11 +47,11 @@ fn encode(delta: i64, output: &mut String) -> Result<(), PolylineError> { } while value >= 0x20 { let from_char = char::from_u32(((0x20 | (value & 0x1f)) + 63) as u32) - .ok_or(PolylineError::DecodeCharError)?; + .ok_or(PolylineError::EncodeToCharError)?; output.push(from_char); value >>= 5; } - let from_char = char::from_u32((value + 63) as u32).ok_or(PolylineError::DecodeCharError)?; + let from_char = char::from_u32((value + 63) as u32).ok_or(PolylineError::EncodeToCharError)?; output.push(from_char); Ok(()) } @@ -95,8 +95,18 @@ where x: scale(next.x, factor), y: scale(next.y, factor), }; - encode(scaled_next.y - previous.y, &mut output)?; - encode(scaled_next.x - previous.x, &mut output)?; + encode(scaled_next.y - previous.y, &mut output).map_err(|_| { + PolylineError::CoordEncodingError { + coord: next, + idx: i, + } + })?; + encode(scaled_next.x - previous.x, &mut output).map_err(|_| { + PolylineError::CoordEncodingError { + coord: next, + idx: i, + } + })?; previous = scaled_next; } Ok(output)