use super::{CodecError, Encode, FORMAT_VERSION, Reader, tag};
use crate::topology::de9im::IntersectionMatrix;
use crate::topology::label::{Dimension, Location};
use crate::types::{
Coord2d, CoordSeq, Envelope, Geometry, GeometryCollection, LineString, LinearRing,
MultiLineString, MultiPoint, MultiPolygon, Point, Polygon,
};
#[cfg(feature = "3d")]
use crate::types3d::{
Coord3d, CoordSeq3d, LineString3d, LinearRing3d, MultiLineString3d, MultiPoint3d,
MultiPolygon3d, Point3d, Polygon3d,
};
pub trait Decode: Sized + Encode {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError>;
}
pub fn decode<T: Decode>(bytes: &[u8]) -> Result<T, CodecError> {
let mut r = Reader::new(bytes);
let version = r.u8()?;
if version != FORMAT_VERSION {
return Err(CodecError::UnsupportedVersion { found: version });
}
let found = r.u8()?;
if found != T::TAG {
return Err(CodecError::UnexpectedTag {
expected: T::TAG,
found,
});
}
let value = T::decode_body(&mut r)?;
let remaining = r.remaining();
if remaining > 0 {
return Err(CodecError::TrailingBytes { remaining });
}
Ok(value)
}
fn read_n<T, F>(r: &mut Reader<'_>, n: usize, mut each: F) -> Result<Vec<T>, CodecError>
where
F: FnMut(&mut Reader<'_>) -> Result<T, CodecError>,
{
const CAPACITY_CLAMP: usize = 1024;
let mut out = Vec::with_capacity(n.min(CAPACITY_CLAMP));
for _ in 0..n {
out.push(each(r)?);
}
Ok(out)
}
impl Decode for Coord2d {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
let x = r.f64()?;
let y = r.f64()?;
Ok(Coord2d::new(x, y))
}
}
impl Decode for CoordSeq {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
let n = r.count()?;
Ok(CoordSeq::new(read_n(r, n, Coord2d::decode_body)?))
}
}
impl Decode for Point {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
Ok(Point::new(Coord2d::decode_body(r)?)?)
}
}
impl Decode for LineString {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
Ok(LineString::new(CoordSeq::decode_body(r)?)?)
}
}
impl Decode for LinearRing {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
Ok(LinearRing::from_distinct(CoordSeq::decode_body(r)?)?)
}
}
impl Decode for Polygon {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
let exterior = LinearRing::decode_body(r)?;
let n = r.count()?;
let holes = read_n(r, n, LinearRing::decode_body)?;
Ok(Polygon::new(exterior, holes)?)
}
}
impl Decode for MultiPoint {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
let n = r.count()?;
Ok(MultiPoint::new(read_n(r, n, Point::decode_body)?))
}
}
impl Decode for MultiLineString {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
let n = r.count()?;
Ok(MultiLineString::new(read_n(r, n, LineString::decode_body)?))
}
}
impl Decode for MultiPolygon {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
let n = r.count()?;
MultiPolygon::new(read_n(r, n, Polygon::decode_body)?).map_err(CodecError::Geometry)
}
}
impl Decode for Geometry {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
match r.u8()? {
tag::GEOMETRY_COLLECTION => Ok(Geometry::GeometryCollection(
GeometryCollection::decode_body(r)?,
)),
variant => decode_leaf(variant, r),
}
}
}
fn decode_leaf(variant: u8, r: &mut Reader<'_>) -> Result<Geometry, CodecError> {
Ok(match variant {
tag::POINT => Geometry::Point(Point::decode_body(r)?),
tag::LINE_STRING => Geometry::LineString(LineString::decode_body(r)?),
tag::POLYGON => Geometry::Polygon(Polygon::decode_body(r)?),
tag::MULTI_POINT => Geometry::MultiPoint(MultiPoint::decode_body(r)?),
tag::MULTI_LINE_STRING => Geometry::MultiLineString(MultiLineString::decode_body(r)?),
tag::MULTI_POLYGON => Geometry::MultiPolygon(MultiPolygon::decode_body(r)?),
found => return Err(CodecError::UnknownVariant { found }),
})
}
struct Frame {
remaining: usize,
elements: Vec<Geometry>,
}
impl Frame {
fn open(r: &mut Reader<'_>) -> Result<Self, CodecError> {
const CAPACITY_CLAMP: usize = 1024;
let remaining = r.count()?;
Ok(Self {
remaining,
elements: Vec::with_capacity(remaining.min(CAPACITY_CLAMP)),
})
}
}
impl Decode for GeometryCollection {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
let mut stack = vec![Frame::open(r)?];
loop {
let Some(top) = stack.last_mut() else {
return Err(CodecError::UnexpectedEnd {
needed: 1,
available: r.remaining(),
});
};
if top.remaining == 0 {
let done = stack.pop().map_or_else(Vec::new, |f| f.elements);
let c = GeometryCollection::new(done)?;
match stack.last_mut() {
None => return Ok(c),
Some(parent) => parent.elements.push(Geometry::GeometryCollection(c)),
}
continue;
}
top.remaining -= 1;
let variant = r.u8()?;
if variant == tag::GEOMETRY_COLLECTION {
if stack.len() >= GeometryCollection::MAX_NESTING {
return Err(CodecError::NestingTooDeep {
limit: GeometryCollection::MAX_NESTING,
});
}
stack.push(Frame::open(r)?);
} else {
let g = decode_leaf(variant, r)?;
top.elements.push(g);
}
}
}
}
impl Decode for Envelope {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
let min_x = r.f64()?;
let min_y = r.f64()?;
let max_x = r.f64()?;
let max_y = r.f64()?;
Ok(Envelope::new(
Coord2d::new(min_x, min_y),
Coord2d::new(max_x, max_y),
)?)
}
}
impl Decode for Location {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
match r.u8()? {
0 => Ok(Location::Interior),
1 => Ok(Location::Boundary),
2 => Ok(Location::Exterior),
found => Err(CodecError::InvalidEnumValue {
type_name: "Location",
found: i16::from(found),
}),
}
}
}
impl Decode for Dimension {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
match r.i8()? {
-1 => Ok(Dimension::Empty),
0 => Ok(Dimension::Point),
1 => Ok(Dimension::Line),
2 => Ok(Dimension::Area),
found => Err(CodecError::InvalidEnumValue {
type_name: "Dimension",
found: i16::from(found),
}),
}
}
}
impl Decode for IntersectionMatrix {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
Ok(IntersectionMatrix {
interior_interior: Dimension::decode_body(r)?,
interior_boundary: Dimension::decode_body(r)?,
interior_exterior: Dimension::decode_body(r)?,
boundary_interior: Dimension::decode_body(r)?,
boundary_boundary: Dimension::decode_body(r)?,
boundary_exterior: Dimension::decode_body(r)?,
exterior_interior: Dimension::decode_body(r)?,
exterior_boundary: Dimension::decode_body(r)?,
exterior_exterior: Dimension::decode_body(r)?,
})
}
}
#[cfg(feature = "3d")]
#[cfg_attr(docsrs, doc(cfg(feature = "3d")))]
impl Decode for Coord3d {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
let x = r.f64()?;
let y = r.f64()?;
let z = r.f64()?;
Ok(Coord3d::new(x, y, z))
}
}
#[cfg(feature = "3d")]
#[cfg_attr(docsrs, doc(cfg(feature = "3d")))]
impl Decode for CoordSeq3d {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
let n = r.count()?;
Ok(CoordSeq3d::new(read_n(r, n, Coord3d::decode_body)?))
}
}
#[cfg(feature = "3d")]
#[cfg_attr(docsrs, doc(cfg(feature = "3d")))]
impl Decode for Point3d {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
Ok(Point3d::new(Coord3d::decode_body(r)?)?)
}
}
#[cfg(feature = "3d")]
#[cfg_attr(docsrs, doc(cfg(feature = "3d")))]
impl Decode for LineString3d {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
Ok(LineString3d::new(CoordSeq3d::decode_body(r)?)?)
}
}
#[cfg(feature = "3d")]
#[cfg_attr(docsrs, doc(cfg(feature = "3d")))]
impl Decode for LinearRing3d {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
Ok(LinearRing3d::from_distinct(CoordSeq3d::decode_body(r)?)?)
}
}
#[cfg(feature = "3d")]
#[cfg_attr(docsrs, doc(cfg(feature = "3d")))]
impl Decode for Polygon3d {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
let exterior = LinearRing3d::decode_body(r)?;
let n = r.count()?;
let holes = read_n(r, n, LinearRing3d::decode_body)?;
Ok(Polygon3d::new(exterior, holes)?)
}
}
#[cfg(feature = "3d")]
#[cfg_attr(docsrs, doc(cfg(feature = "3d")))]
impl Decode for MultiPoint3d {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
let n = r.count()?;
Ok(MultiPoint3d::new(read_n(r, n, Point3d::decode_body)?))
}
}
#[cfg(feature = "3d")]
#[cfg_attr(docsrs, doc(cfg(feature = "3d")))]
impl Decode for MultiLineString3d {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
let n = r.count()?;
Ok(MultiLineString3d::new(read_n(
r,
n,
LineString3d::decode_body,
)?))
}
}
#[cfg(feature = "3d")]
#[cfg_attr(docsrs, doc(cfg(feature = "3d")))]
impl Decode for MultiPolygon3d {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
let n = r.count()?;
Ok(MultiPolygon3d::new(read_n(r, n, Polygon3d::decode_body)?)?)
}
}