Skip to main content

mlt_core/
errors.rs

1use std::num::TryFromIntError;
2
3use num_enum::TryFromPrimitiveError;
4
5use crate::decoder::{
6    GeometryType, LogicalCombination, LogicalEncoding, LogicalTechnique, PhysicalEncoding,
7    StreamType, ValueKind,
8};
9
10pub type MltResult<T> = Result<T, MltError>;
11pub(crate) type MltRefResult<'a, T> = Result<(&'a [u8], T), MltError>;
12
13#[derive(Debug, thiserror::Error)]
14#[non_exhaustive]
15pub enum MltError {
16    #[error("cannot decode {0} as {1}")]
17    DataWidthMismatch(&'static str, &'static str),
18    #[error("dictionary index {0} out of bounds (len={1})")]
19    DictIndexOutOfBounds(u32, usize),
20    #[error("duplicate value found where unique required")]
21    DuplicateValue,
22    #[error("Integer overflow")]
23    IntegerOverflow,
24    #[error("missing geometry column in feature table")]
25    MissingGeometry,
26    #[error("missing layer name")]
27    MissingLayerName,
28    #[error("invalid extent: {0}")]
29    InvalidExtent(u32),
30    #[error("missing property name")]
31    MissingPropertyName,
32    #[error("duplicate column name {name}: the {role} column repeats the {taken_by} column")]
33    DuplicateColumnName {
34        name: String,
35        role: crate::tile::ColumnRole,
36        taken_by: crate::tile::ColumnRole,
37    },
38    #[error("feature property count mismatch: expected {expected}, got {actual}")]
39    PropertyLengthMismatch { expected: usize, actual: usize },
40    #[error("property {index} kind mismatch: expected {expected:?}, got {actual:?}")]
41    PropertyKindMismatch {
42        index: usize,
43        expected: crate::tile::PropKind,
44        actual: crate::tile::PropKind,
45    },
46    #[error("staged column {column} feature count mismatch: expected {expected}, got {actual}")]
47    StagedFeatureCountMismatch {
48        column: String,
49        expected: usize,
50        actual: usize,
51    },
52    #[error("missing string stream: {0}")]
53    MissingStringStream(&'static str),
54    #[error("multiple geometry columns found (only one allowed)")]
55    MultipleGeometryColumns,
56    #[error("multiple ID columns found (only one allowed)")]
57    MultipleIdColumns,
58    #[error("varint uses more bytes than necessary (non-canonical encoding)")]
59    NonCanonicalVarInt,
60    #[error("{0} is not decoded")]
61    NotDecoded(&'static str),
62    #[error("decoded data is not in encoded form")]
63    NotEncoded,
64    #[error("error parsing column type: code={0}")]
65    ParsingColumnType(u8),
66    #[error("error parsing v2 stream encoding byte: 0x{0:02X}")]
67    ParsingEncodingByte(u8),
68    #[cfg(feature = "unstable-v2")]
69    #[error(
70        "a v2 {0:?} stream carries no value count, and nothing in its context implies one: encoding byte 0x{1:02X}"
71    )]
72    StreamWithoutCount(StreamType, u8),
73    #[cfg(feature = "unstable-v2")]
74    #[error("error parsing v2 geometry layout: code={0}")]
75    ParsingGeoLayout(u8),
76    #[cfg(feature = "unstable-v2")]
77    #[error(
78        "v2 geometry layout {0} gives no per-feature vertex count, so it cannot carry m-values"
79    )]
80    MValuesNeedVertexCounts(&'static str),
81    #[cfg(feature = "unstable-v2")]
82    #[error("the v2 layer layout byte claims an m-value section, but it holds no columns")]
83    EmptyMValueSection,
84    #[cfg(feature = "unstable-v2")]
85    #[error(
86        "m-value column {name} has no implied count, so its leading stream must write one: encoding byte 0x{byte:02X}"
87    )]
88    MValueImplicitCount { name: String, byte: u8 },
89    #[cfg(feature = "unstable-v2")]
90    #[error(
91        "m-value column {name} holds {actual} values, but its features have {expected} vertices"
92    )]
93    MValueColumnLengthMismatch {
94        name: String,
95        expected: usize,
96        actual: usize,
97    },
98    #[cfg(feature = "unstable-v2")]
99    #[error(
100        "m-value column {name} holds {actual} values, so a feature's run of {count} at offset {start} is out of range"
101    )]
102    MValueRunOutOfRange {
103        name: String,
104        start: usize,
105        count: usize,
106        actual: usize,
107    },
108    #[cfg(feature = "unstable-v2")]
109    #[error("a feature carries {actual} m-value columns, but the layer has {expected}")]
110    MValueColumnCountMismatch { expected: usize, actual: usize },
111    #[cfg(feature = "unstable-v2")]
112    #[error("m-value key {index} belongs to another layer: this feature has {columns} columns")]
113    UnknownMValueKey { index: usize, columns: usize },
114    #[cfg(feature = "unstable-v2")]
115    #[error("m-value {index} kind mismatch: expected {expected:?}, got {actual:?}")]
116    MValueKindMismatch {
117        index: usize,
118        expected: crate::tile::PropKind,
119        actual: crate::tile::PropKind,
120    },
121    #[cfg(feature = "unstable-v2")]
122    #[error("m-value {index} holds {actual} values, but the feature has {expected} vertices")]
123    MValueVertexCountMismatch {
124        index: usize,
125        expected: usize,
126        actual: usize,
127    },
128    #[cfg(feature = "unstable-v2")]
129    #[error("m-values are a v2 feature, so layer {0} cannot be written as v1")]
130    MValuesNeedV2(String),
131    #[cfg(feature = "unstable-v2")]
132    #[error("nested properties are a v2 feature, so layer {0} cannot be written as v1")]
133    NestedNeedsV2(String),
134    #[cfg(feature = "unstable-v2")]
135    #[error("duplicate field name in a struct node: {0}")]
136    DuplicateFieldName(String),
137    #[cfg(feature = "unstable-v2")]
138    #[error("a struct node holds no fields")]
139    EmptyStructNode,
140    #[cfg(feature = "unstable-v2")]
141    #[error("nested column {0} has a scalar root, which is an ordinary column")]
142    NestedRootIsLeaf(String),
143    #[cfg(feature = "unstable-v2")]
144    #[error("a nested column is {0} levels deep, more than the 8 the format allows")]
145    NestedTooDeep(usize),
146    #[cfg(feature = "unstable-v2")]
147    #[error("a nested lengths stream sums to {expected}, but the node below it holds {actual}")]
148    NestedCountMismatch { expected: u32, actual: u32 },
149    #[cfg(feature = "unstable-v2")]
150    #[error(
151        "nested node {name} has no implied count, so its leading stream must write one: encoding byte 0x{byte:02X}"
152    )]
153    NestedImplicitCount { name: String, byte: u8 },
154    #[cfg(feature = "unstable-v2")]
155    #[error("a feature carries {actual} nested columns, but the layer has {expected}")]
156    NestedColumnCountMismatch { expected: usize, actual: usize },
157    #[cfg(feature = "unstable-v2")]
158    #[error("nested key {index} belongs to another layer: this feature has {columns} columns")]
159    UnknownNestedKey { index: usize, columns: usize },
160    #[cfg(feature = "unstable-v2")]
161    #[error("nested column {index} ({name}) was given a value of another shape")]
162    NestedValueMismatch { index: usize, name: String },
163    #[cfg(feature = "unstable-v2")]
164    #[error("nested column {index} was given a value of another shape")]
165    NestedShapeMismatch { index: usize },
166    #[cfg(feature = "unstable-v2")]
167    #[error("nested column {name} runs over {expected} values, but its root holds {actual}")]
168    NestedRootCountMismatch {
169        name: String,
170        expected: u32,
171        actual: u32,
172    },
173    #[cfg(feature = "unstable-v2")]
174    #[error(
175        "nested node {name} must write its presence as a raw bitmap of one bit per value: encoding byte 0x{byte:02X}"
176    )]
177    NestedPresenceEncoding { name: String, byte: u8 },
178    #[cfg(feature = "unstable-v2")]
179    #[error("a nested lengths stream holds {len} lengths, so it has no row {row}")]
180    NestedRowOutOfRange { row: usize, len: usize },
181    #[cfg(feature = "unstable-v2")]
182    #[error("a nested map holds {len} keys, so it has no key for entry {entry}")]
183    NestedKeyOutOfRange { entry: usize, len: usize },
184    #[cfg(feature = "unstable-v2")]
185    #[error("a nested leaf holds {len} values, so it has no value at index {index}")]
186    NestedValueOutOfRange { index: usize, len: usize },
187    #[cfg(feature = "unstable-v2")]
188    #[error("a row-shape table of {bits} bits does not divide into shapes of {keys} keys")]
189    NestedRowShapeTableSize { bits: usize, keys: usize },
190    #[cfg(feature = "unstable-v2")]
191    #[error("a shape-coded nested node has {len} row shapes, so it has no shape {id}")]
192    NestedRowShapeOutOfRange { id: u32, len: usize },
193    #[cfg(feature = "unstable-v2")]
194    #[error("nested node {name} is shape-coded over {expected} rows, but holds {actual} shape ids")]
195    NestedRowShapeCount {
196        name: String,
197        expected: u32,
198        actual: u32,
199    },
200    #[cfg(feature = "unstable-v2")]
201    #[error(
202        "nested node {name} reads its presence from its parent's row shapes, so it stores none of its own"
203    )]
204    NestedRowShapeChildPresence { name: String },
205    #[cfg(feature = "unstable-v2")]
206    #[error("nested node {name} is a {kind}, which has no row shapes to read")]
207    NestedRowShapeUnsupported { name: String, kind: &'static str },
208    #[error("error parsing logical technique: code={0}")]
209    ParsingLogicalTechnique(u8),
210    #[error("error parsing physical encoding: code={0}")]
211    ParsingPhysicalEncoding(u8),
212    #[error("error parsing stream type: code={0}")]
213    ParsingStreamType(u8),
214    #[error("found {0} bytes after the expected end of layer")]
215    TrailingLayerData(usize),
216    #[error("unexpected end of input (unable to take {0} bytes)")]
217    UnableToTake(u32),
218    #[error("unexpected stream type {0:?}")]
219    UnexpectedStreamType(StreamType),
220    #[error("unexpected stream type {0:?}, expected {1} for {2}")]
221    UnexpectedStreamType2(StreamType, &'static str, &'static str),
222    #[error("unsupported logical encoding {0:?} for {1}")]
223    UnsupportedLogicalEncoding(LogicalEncoding, &'static str),
224    #[error("invalid combination of logical encodings: {0:?} + {1:?}")]
225    InvalidLogicalEncodings(LogicalTechnique, LogicalTechnique),
226    #[error("logical encoding {0:?} is not one a {1:?} stream has")]
227    LogicalEncodingNotInKind(LogicalCombination, ValueKind),
228    #[error("layer has zero size")]
229    ZeroLayerSize,
230    #[error("bit-packed stream width {0} is outside 1..=32")]
231    #[cfg(feature = "unstable-v2")]
232    ParsingBitWidth(u32),
233    #[error("The encoder used to optimise data is incompatible")]
234    BadEncoderDataCombination,
235    #[error("StagedLayer::encode_explicit requires Encoder.explicit to be Some(_)")]
236    MissingExplicitEncoder,
237
238    // Wire/codec decoding (bytes -> primitives)
239    #[error("buffer underflow: needed {0} bytes, but only {1} remain")]
240    BufferUnderflow(u32, usize),
241    #[error("FastPFor decode failed: expected={0} got={1}")]
242    FastPforDecode(u32, usize),
243    #[error("invalid RLE run length (cannot convert to usize): value={0}")]
244    RleRunLenInvalid(i128),
245
246    // Structural constraints (lengths, counts, shapes)
247    #[error("geometry requires at least 1 stream, got 0")]
248    GeometryWithoutStreams,
249    #[error("FastPFor data byte length expected multiple of 4, got {0}")]
250    InvalidFastPforByteLength(usize),
251    #[error("vec2 delta stream size expected to be non-empty and multiple of 2, got {0}")]
252    InvalidPairStreamSize(usize),
253    #[error("decodable stream size expected {1}, got {0}")]
254    InvalidDecodingStreamSize(usize, usize),
255    #[error("IDs missing for encoding (expected Some IDs, got None)")]
256    IdsMissingForEncoding,
257    #[error("missing struct encoder for struct")]
258    MissingStructEncoderForStruct,
259    #[error("previous decode/parsing attempt failed")]
260    PriorParseFailure,
261    #[error("FSST-compressed data is malformed: {0}")]
262    MalformedFsst(&'static str),
263    #[cfg(feature = "unstable-v2")]
264    #[error("dictionary code {0} is out of range for a dictionary of {1} values")]
265    DictionaryCodeOutOfRange(u32, usize),
266    #[cfg(feature = "unstable-v2")]
267    #[error(
268        "front-coded lengths stream holds a prefix and a suffix length per entry, so its {0} values cannot be split in two"
269    )]
270    FrontCodedOddLengthCount(usize),
271    #[cfg(feature = "unstable-v2")]
272    #[error(
273        "front-coded entry {index} shares {shared} bytes with a predecessor of only {available}"
274    )]
275    FrontCodedPrefixTooLong {
276        index: usize,
277        shared: usize,
278        available: usize,
279    },
280    #[cfg(feature = "unstable-v2")]
281    #[error(
282        "front-coded entry {index} needs {needed} suffix bytes, but {available} remain in the blob"
283    )]
284    FrontCodedSuffixOutOfBounds {
285        index: usize,
286        needed: usize,
287        available: usize,
288    },
289    #[cfg(feature = "unstable-v2")]
290    #[error("front-coded dictionary leaves {0} suffix bytes after its last entry")]
291    FrontCodedTrailingSuffixBytes(usize),
292    #[cfg(feature = "unstable-v2")]
293    #[error("no ALP parameters return this float column bit-for-bit")]
294    NoAlpParameters,
295    #[error("invalid ALP parameters: e={0}, f={1}")]
296    InvalidAlpParams(u8, u8),
297    #[error("presence stream has {0} bits set but {1} values provided")]
298    PresenceValueCountMismatch(usize, usize),
299    #[error("need to encode before being able to write")]
300    NeedsEncodingBeforeWriting,
301    #[error("memory limit exceeded: limit={limit}, used={used}, requested={requested}")]
302    MemoryLimitExceeded {
303        limit: u32,
304        used: u32,
305        requested: u32,
306    },
307    #[error("not implemented: {0}")]
308    NotImplemented(&'static str),
309    #[error("unsupported property value and encoder combination: {0:?} + {1:?}")]
310    UnsupportedPropertyEncoderCombination(&'static str, &'static str),
311    #[error("mixed property types are not allowed in column {0} ({1})")]
312    MixedPropertyTypes(usize, String),
313    #[error("shared dictionary requires at least 2 streams, got {0}")]
314    SharedDictRequiresStreams(usize),
315    #[error("unsupported string stream count (expected between 2 and 5): {0}")]
316    UnsupportedStringStreamCount(usize),
317    #[error("Structs are not allowed to be optional")]
318    TriedToEncodeOptionalStruct,
319    #[error(
320        "encoding instruction count mismatch: expected {input_len} instructions for {input_len} properties, got {config_len}"
321    )]
322    EncodingInstructionCountMismatch { input_len: usize, config_len: usize },
323    #[error("struct child data streams expected exactly 1 value, got {0}")]
324    UnexpectedStructChildCount(u32),
325    // Note that {expected}+1 is allowed for the legacy Java encoder bug
326    #[error("SharedDict stream count is {actual}, expected {expected}")]
327    InvalidSharedDictStreamCount { actual: u32, expected: u32 },
328    #[error("unsupported physical encoding: {0}")]
329    UnsupportedPhysicalEncoding(&'static str),
330    #[error("unsupported physical encoding: {0:?} for {1}")]
331    UnsupportedPhysicalEncodingForType(PhysicalEncoding, &'static str),
332    #[error(
333        "Extent {extent} cannot be encoded to morton due to morton allowing max. 16 bits, but {required_bits} would be required"
334    )]
335    VertexMortonNotCompatibleWithExtent { extent: u32, required_bits: u32 },
336    #[error("Morton stream uses {0} bits, but at most 16 bits are supported")]
337    InvalidMortonBits(u32),
338
339    // Geometry decode errors (field = variable name, geom_type for context)
340    #[error("MVT error: {0}")]
341    BadMvtGeometry(&'static str),
342    #[error("geometry[{0}]: index out of bounds")]
343    GeometryIndexOutOfBounds(usize),
344    #[error("geometry[{index}]: {field}[{idx}] out of bounds (len={len})")]
345    GeometryOutOfBounds {
346        index: usize,
347        field: &'static str,
348        idx: usize,
349        len: usize,
350    },
351    #[error("geometry[{index}]: vertex {vertex} out of bounds (count={count})")]
352    GeometryVertexOutOfBounds {
353        index: usize,
354        vertex: usize,
355        count: usize,
356    },
357    #[error("geometry[{0}]: {1} requires geometry_offsets")]
358    NoGeometryOffsets(usize, GeometryType),
359    #[error("geometry[{0}]: {1} requires part_offsets")]
360    NoPartOffsets(usize, GeometryType),
361    #[error("geometry[{0}]: {1} requires ring_offsets")]
362    NoRingOffsets(usize, GeometryType),
363    #[error("geometry[{0}]: unexpected offset combination for {1}")]
364    UnexpectedOffsetCombination(usize, GeometryType),
365    #[error("geometry: ring lengths without part lengths")]
366    RingLengthsWithoutPartLengths,
367
368    #[error("FastPFor error: {0}")]
369    FastPfor(#[from] fastpfor::FastPForError),
370    #[error(transparent)]
371    Io(#[from] std::io::Error),
372    #[error("Serde JSON error: {0}")]
373    SerdeJsonError(#[from] serde_json::Error),
374    #[error("integer conversion error: {0}")]
375    TryFromIntError(#[from] TryFromIntError),
376    #[error("num_enum conversion error: {0}")]
377    TryFromPrimitive(#[from] TryFromPrimitiveError<GeometryType>),
378    #[error("UTF-8 decode error: {0}")]
379    Utf8(#[from] std::str::Utf8Error),
380    #[error("UTF-8 decode error: {0}")]
381    FromUtf8(#[from] std::string::FromUtf8Error),
382    #[error("MVT error: {0}")]
383    Mvt(#[from] fast_mvt::MvtError),
384    #[error("MVT JSON value error: {0}")]
385    MvtJsonValue(#[from] fast_mvt::MvtJsonValueError),
386}
387
388impl From<MltError> for std::io::Error {
389    fn from(value: MltError) -> Self {
390        if let MltError::Io(e) = value {
391            e
392        } else {
393            Self::other(value)
394        }
395    }
396}
397
398pub(crate) trait AsMltError<T> {
399    fn or_overflow(&self) -> MltResult<T>;
400}
401
402impl<T: Copy> AsMltError<T> for Option<T> {
403    #[inline]
404    fn or_overflow(&self) -> MltResult<T> {
405        self.ok_or(MltError::IntegerOverflow)
406    }
407}
408
409impl AsMltError<u32> for Result<u32, TryFromIntError> {
410    #[inline]
411    fn or_overflow(&self) -> MltResult<u32> {
412        self.map_err(|_| MltError::IntegerOverflow)
413    }
414}
415
416#[inline]
417pub(crate) fn fail_if_invalid_stream_size(actual: usize, expected: usize) -> MltResult<()> {
418    if actual == expected {
419        Ok(())
420    } else {
421        Err(MltError::InvalidDecodingStreamSize(actual, expected))
422    }
423}