Skip to main content

mlt_core/
errors.rs

1use std::num::TryFromIntError;
2
3use num_enum::TryFromPrimitiveError;
4
5use crate::decoder::{
6    GeometryType, LogicalEncoding, LogicalTechnique, PhysicalEncoding, StreamType,
7};
8
9pub type MltResult<T> = Result<T, MltError>;
10pub(crate) type MltRefResult<'a, T> = Result<(&'a [u8], T), MltError>;
11
12#[derive(Debug, thiserror::Error)]
13#[non_exhaustive]
14pub enum MltError {
15    #[error("cannot decode {0} as {1}")]
16    DataWidthMismatch(&'static str, &'static str),
17    #[error("dictionary index {0} out of bounds (len={1})")]
18    DictIndexOutOfBounds(u32, usize),
19    #[error("duplicate value found where unique required")]
20    DuplicateValue,
21    #[error("Integer overflow")]
22    IntegerOverflow,
23    #[error("missing geometry column in feature table")]
24    MissingGeometry,
25    #[error("missing layer name")]
26    MissingLayerName,
27    #[error("missing string stream: {0}")]
28    MissingStringStream(&'static str),
29    #[error("multiple geometry columns found (only one allowed)")]
30    MultipleGeometryColumns,
31    #[error("multiple ID columns found (only one allowed)")]
32    MultipleIdColumns,
33    #[error("varint uses more bytes than necessary (non-canonical encoding)")]
34    NonCanonicalVarInt,
35    #[error("{0} is not decoded")]
36    NotDecoded(&'static str),
37    #[error("decoded data is not in encoded form")]
38    NotEncoded,
39    #[error("error parsing column type: code={0}")]
40    ParsingColumnType(u8),
41    #[error("error parsing logical technique: code={0}")]
42    ParsingLogicalTechnique(u8),
43    #[error("error parsing physical encoding: code={0}")]
44    ParsingPhysicalEncoding(u8),
45    #[error("error parsing stream type: code={0}")]
46    ParsingStreamType(u8),
47    #[error("found {0} bytes after the expected end of layer")]
48    TrailingLayerData(usize),
49    #[error("unexpected end of input (unable to take {0} bytes)")]
50    UnableToTake(u32),
51    #[error("unexpected stream type {0:?}")]
52    UnexpectedStreamType(StreamType),
53    #[error("unexpected stream type {0:?}, expected {1} for {2}")]
54    UnexpectedStreamType2(StreamType, &'static str, &'static str),
55    #[error("unsupported logical encoding {0:?} for {1}")]
56    UnsupportedLogicalEncoding(LogicalEncoding, &'static str),
57    #[error("invalid combination of logical encodings: {0:?} + {1:?}")]
58    InvalidLogicalEncodings(LogicalTechnique, LogicalTechnique),
59    #[error("layer has zero size")]
60    ZeroLayerSize,
61    #[error("The encoder used to optimise data is incompatible")]
62    BadEncoderDataCombination,
63    #[error("StagedLayer::encode_explicit requires Encoder.explicit to be Some(_)")]
64    MissingExplicitEncoder,
65
66    // Wire/codec decoding (bytes → primitives)
67    #[error("buffer underflow: needed {0} bytes, but only {1} remain")]
68    BufferUnderflow(u32, usize),
69    #[error("FastPFor decode failed: expected={0} got={1}")]
70    FastPforDecode(u32, usize),
71    #[error("invalid RLE run length (cannot convert to usize): value={0}")]
72    RleRunLenInvalid(i128),
73
74    // Structural constraints (lengths, counts, shapes)
75    #[error("geometry requires at least 1 stream, got 0")]
76    GeometryWithoutStreams,
77    #[error("FastPFor data byte length expected multiple of 4, got {0}")]
78    InvalidFastPforByteLength(usize),
79    #[error("vec2 delta stream size expected to be non-empty and multiple of 2, got {0}")]
80    InvalidPairStreamSize(usize),
81    #[error("decodable stream size expected {1}, got {0}")]
82    InvalidDecodingStreamSize(usize, usize),
83    #[error("IDs missing for encoding (expected Some IDs, got None)")]
84    IdsMissingForEncoding,
85    #[error("missing struct encoder for struct")]
86    MissingStructEncoderForStruct,
87    #[error("previous decode/parsing attempt failed")]
88    PriorParseFailure,
89    #[error("presence stream has {0} bits set but {1} values provided")]
90    PresenceValueCountMismatch(usize, usize),
91    #[error("need to encode before being able to write")]
92    NeedsEncodingBeforeWriting,
93    #[error("memory limit exceeded: limit={limit}, used={used}, requested={requested}")]
94    MemoryLimitExceeded {
95        limit: u32,
96        used: u32,
97        requested: u32,
98    },
99    #[error("not implemented: {0}")]
100    NotImplemented(&'static str),
101    #[error("unsupported property value and encoder combination: {0:?} + {1:?}")]
102    UnsupportedPropertyEncoderCombination(&'static str, &'static str),
103    #[error("mixed property types are not allowed in column {0} ({1})")]
104    MixedPropertyTypes(usize, String),
105    #[error("shared dictionary requires at least 2 streams, got {0}")]
106    SharedDictRequiresStreams(usize),
107    #[error("unsupported string stream count (expected between 2 and 5): {0}")]
108    UnsupportedStringStreamCount(usize),
109    #[error("Structs are not allowed to be optional")]
110    TriedToEncodeOptionalStruct,
111    #[error(
112        "encoding instruction count mismatch: expected {input_len} instructions for {input_len} properties, got {config_len}"
113    )]
114    EncodingInstructionCountMismatch { input_len: usize, config_len: usize },
115    #[error("struct child data streams expected exactly 1 value, got {0}")]
116    UnexpectedStructChildCount(u32),
117    // Note that {expected}+1 is allowed for the legacy Java encoder bug
118    #[error("SharedDict stream count is {actual}, expected {expected}")]
119    InvalidSharedDictStreamCount { actual: u32, expected: u32 },
120    #[error("unsupported physical encoding: {0}")]
121    UnsupportedPhysicalEncoding(&'static str),
122    #[error("unsupported physical encoding: {0:?} for {1}")]
123    UnsupportedPhysicalEncodingForType(PhysicalEncoding, &'static str),
124    #[error(
125        "Extent {extent} cannot be encoded to morton due to morton allowing max. 16 bits, but {required_bits} would be required"
126    )]
127    VertexMortonNotCompatibleWithExtent { extent: u32, required_bits: u32 },
128    #[error("Morton stream uses {0} bits, but at most 16 bits are supported")]
129    InvalidMortonBits(u32),
130
131    // Geometry decode errors (field = variable name, geom_type for context)
132    #[error("MVT error: {0}")]
133    BadMvtGeometry(&'static str),
134    #[error("geometry[{0}]: index out of bounds")]
135    GeometryIndexOutOfBounds(usize),
136    #[error("geometry[{index}]: {field}[{idx}] out of bounds (len={len})")]
137    GeometryOutOfBounds {
138        index: usize,
139        field: &'static str,
140        idx: usize,
141        len: usize,
142    },
143    #[error("geometry[{index}]: vertex {vertex} out of bounds (count={count})")]
144    GeometryVertexOutOfBounds {
145        index: usize,
146        vertex: usize,
147        count: usize,
148    },
149    #[error("geometry[{0}]: {1} requires geometry_offsets")]
150    NoGeometryOffsets(usize, GeometryType),
151    #[error("geometry[{0}]: {1} requires part_offsets")]
152    NoPartOffsets(usize, GeometryType),
153    #[error("geometry[{0}]: {1} requires ring_offsets")]
154    NoRingOffsets(usize, GeometryType),
155    #[error("geometry[{0}]: unexpected offset combination for {1}")]
156    UnexpectedOffsetCombination(usize, GeometryType),
157
158    #[error("FastPFor error: {0}")]
159    FastPfor(#[from] fastpfor::FastPForError),
160    #[error(transparent)]
161    Io(#[from] std::io::Error),
162    #[error("Serde JSON error: {0}")]
163    SerdeJsonError(#[from] serde_json::Error),
164    #[error("integer conversion error: {0}")]
165    TryFromIntError(#[from] TryFromIntError),
166    #[error("num_enum conversion error: {0}")]
167    TryFromPrimitive(#[from] TryFromPrimitiveError<GeometryType>),
168    #[error("UTF-8 decode error: {0}")]
169    Utf8(#[from] std::str::Utf8Error),
170    #[error("UTF-8 decode error: {0}")]
171    FromUtf8(#[from] std::string::FromUtf8Error),
172    #[error("MVT error: {0}")]
173    Mvt(#[from] fast_mvt::MvtError),
174    #[error("MVT JSON value error: {0}")]
175    MvtJsonValue(#[from] fast_mvt::MvtJsonValueError),
176}
177
178impl From<MltError> for std::io::Error {
179    fn from(value: MltError) -> Self {
180        match value {
181            MltError::Io(e) => e,
182            other => Self::other(other),
183        }
184    }
185}
186
187pub(crate) trait AsMltError<T> {
188    fn or_overflow(&self) -> MltResult<T>;
189}
190
191impl<T: Copy> AsMltError<T> for Option<T> {
192    #[inline]
193    fn or_overflow(&self) -> MltResult<T> {
194        self.ok_or(MltError::IntegerOverflow)
195    }
196}
197
198impl AsMltError<u32> for Result<u32, TryFromIntError> {
199    #[inline]
200    fn or_overflow(&self) -> MltResult<u32> {
201        self.map_err(|_| MltError::IntegerOverflow)
202    }
203}
204
205#[inline]
206pub(crate) fn fail_if_invalid_stream_size(actual: usize, expected: usize) -> MltResult<()> {
207    if actual == expected {
208        Ok(())
209    } else {
210        Err(MltError::InvalidDecodingStreamSize(actual, expected))
211    }
212}