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("error parsing v2 layer header byte: 0x{0:02X}")]
78    ParsingLayerHeader02(u8),
79    #[cfg(feature = "unstable-v2")]
80    #[error("error parsing v2 layer layout byte: 0x{0:02X}")]
81    ParsingLayerLayout02(u8),
82    #[cfg(feature = "unstable-v2")]
83    #[error("v2 extent {0} is not a power of two in 64..=2097152")]
84    UnsupportedExtent02(u32),
85    #[cfg(feature = "unstable-v2")]
86    #[error(
87        "v2 geometry layout {0} gives no per-feature vertex count, so it cannot carry m-values"
88    )]
89    MValuesNeedVertexCounts(&'static str),
90    #[cfg(feature = "unstable-v2")]
91    #[error("the v2 layer header byte claims an m-value section, but it holds no columns")]
92    EmptyMValueSection,
93    #[cfg(feature = "unstable-v2")]
94    #[error(
95        "m-value column {name} has no implied count, so its leading stream must write one: encoding byte 0x{byte:02X}"
96    )]
97    MValueImplicitCount { name: String, byte: u8 },
98    #[cfg(feature = "unstable-v2")]
99    #[error(
100        "m-value column {name} holds {actual} values, but its features have {expected} vertices"
101    )]
102    MValueColumnLengthMismatch {
103        name: String,
104        expected: usize,
105        actual: usize,
106    },
107    #[cfg(feature = "unstable-v2")]
108    #[error(
109        "m-value column {name} holds {actual} values, so a feature's run of {count} at offset {start} is out of range"
110    )]
111    MValueRunOutOfRange {
112        name: String,
113        start: usize,
114        count: usize,
115        actual: usize,
116    },
117    #[cfg(feature = "unstable-v2")]
118    #[error("a feature carries {actual} m-value columns, but the layer has {expected}")]
119    MValueColumnCountMismatch { expected: usize, actual: usize },
120    #[cfg(feature = "unstable-v2")]
121    #[error("m-value key {index} belongs to another layer: this feature has {columns} columns")]
122    UnknownMValueKey { index: usize, columns: usize },
123    #[cfg(feature = "unstable-v2")]
124    #[error("m-value {index} kind mismatch: expected {expected:?}, got {actual:?}")]
125    MValueKindMismatch {
126        index: usize,
127        expected: crate::tile::PropKind,
128        actual: crate::tile::PropKind,
129    },
130    #[cfg(feature = "unstable-v2")]
131    #[error("m-value {index} holds {actual} values, but the feature has {expected} vertices")]
132    MValueVertexCountMismatch {
133        index: usize,
134        expected: usize,
135        actual: usize,
136    },
137    #[error("8-bit integers are a v2 feature, so column {0} cannot be written as v1")]
138    EightBitNeedsV2(String),
139    #[cfg(feature = "unstable-v2")]
140    #[error("m-values are a v2 feature, so layer {0} cannot be written as v1")]
141    MValuesNeedV2(String),
142    #[error("a vertex stream of {0} words does not hold whole vertices of {1} words")]
143    PartialVertex(u32, u32),
144    #[cfg(feature = "unstable-v2")]
145    #[error("z coordinates are a v2 feature, so layer {0} cannot be written as v1")]
146    ZNeedsV2(String),
147    #[cfg(feature = "unstable-v2")]
148    #[error("a z step of 10^{0} m is outside 10^-3..=10^4 m")]
149    InvalidZStep(i8),
150    #[cfg(feature = "unstable-v2")]
151    #[error("z step code {0} is outside 0..=7")]
152    InvalidZStepCode(u8),
153    #[cfg(feature = "unstable-v2")]
154    #[error(
155        "layer {0} already holds features without z coordinates, so it cannot be given a z step"
156    )]
157    ZStepOnNonEmptyLayer(String),
158    #[cfg(feature = "unstable-v2")]
159    #[error("a feature carries {actual} z coordinates, but the layer expects {expected}")]
160    ZVertexCountMismatch { expected: usize, actual: usize },
161    #[cfg(feature = "unstable-v2")]
162    #[error("the vertices already carry z coordinates")]
163    ZAlreadySet,
164    #[cfg(feature = "unstable-v2")]
165    #[error("a vertex stream of {0} words does not hold whole (x, y, z) triples")]
166    InvalidTripleStreamSize(usize),
167    #[cfg(feature = "unstable-v2")]
168    #[error("nested properties are a v2 feature, so layer {0} cannot be written as v1")]
169    NestedNeedsV2(String),
170    #[cfg(feature = "unstable-v2")]
171    #[error("duplicate field name in a struct node: {0}")]
172    DuplicateFieldName(String),
173    #[cfg(feature = "unstable-v2")]
174    #[error("a struct node holds no fields")]
175    EmptyStructNode,
176    #[cfg(feature = "unstable-v2")]
177    #[error("nested column {0} has a scalar root, which is an ordinary column")]
178    NestedRootIsLeaf(String),
179    #[cfg(feature = "unstable-v2")]
180    #[error("a nested column is {0} levels deep, more than the 8 the format allows")]
181    NestedTooDeep(usize),
182    #[cfg(feature = "unstable-v2")]
183    #[error("a nested lengths stream sums to {expected}, but the node below it holds {actual}")]
184    NestedCountMismatch { expected: u32, actual: u32 },
185    #[cfg(feature = "unstable-v2")]
186    #[error(
187        "nested node {name} has no implied count, so its leading stream must write one: encoding byte 0x{byte:02X}"
188    )]
189    NestedImplicitCount { name: String, byte: u8 },
190    #[cfg(feature = "unstable-v2")]
191    #[error("a feature carries {actual} nested columns, but the layer has {expected}")]
192    NestedColumnCountMismatch { expected: usize, actual: usize },
193    #[cfg(feature = "unstable-v2")]
194    #[error("nested key {index} belongs to another layer: this feature has {columns} columns")]
195    UnknownNestedKey { index: usize, columns: usize },
196    #[cfg(feature = "unstable-v2")]
197    #[error("nested column {index} ({name}) was given a value of another shape")]
198    NestedValueMismatch { index: usize, name: String },
199    #[cfg(feature = "unstable-v2")]
200    #[error("nested column {index} was given a value of another shape")]
201    NestedShapeMismatch { index: usize },
202    #[cfg(feature = "unstable-v2")]
203    #[error("nested column {name} runs over {expected} values, but its root holds {actual}")]
204    NestedRootCountMismatch {
205        name: String,
206        expected: u32,
207        actual: u32,
208    },
209    #[cfg(feature = "unstable-v2")]
210    #[error(
211        "nested node {name} must write its presence as a raw bitmap of one bit per value: encoding byte 0x{byte:02X}"
212    )]
213    NestedPresenceEncoding { name: String, byte: u8 },
214    #[cfg(feature = "unstable-v2")]
215    #[error("a nested lengths stream holds {len} lengths, so it has no row {row}")]
216    NestedRowOutOfRange { row: usize, len: usize },
217    #[cfg(feature = "unstable-v2")]
218    #[error("a nested map holds {len} keys, so it has no key for entry {entry}")]
219    NestedKeyOutOfRange { entry: usize, len: usize },
220    #[cfg(feature = "unstable-v2")]
221    #[error("a nested leaf holds {len} values, so it has no value at index {index}")]
222    NestedValueOutOfRange { index: usize, len: usize },
223    #[cfg(feature = "unstable-v2")]
224    #[error("a row-shape table of {bits} bits does not divide into shapes of {keys} keys")]
225    NestedRowShapeTableSize { bits: usize, keys: usize },
226    #[cfg(feature = "unstable-v2")]
227    #[error("a shape-coded nested node has {len} row shapes, so it has no shape {id}")]
228    NestedRowShapeOutOfRange { id: u32, len: usize },
229    #[cfg(feature = "unstable-v2")]
230    #[error("nested node {name} is shape-coded over {expected} rows, but holds {actual} shape ids")]
231    NestedRowShapeCount {
232        name: String,
233        expected: u32,
234        actual: u32,
235    },
236    #[cfg(feature = "unstable-v2")]
237    #[error(
238        "nested node {name} reads its presence from its parent's row shapes, so it stores none of its own"
239    )]
240    NestedRowShapeChildPresence { name: String },
241    #[cfg(feature = "unstable-v2")]
242    #[error("nested node {name} is a {kind}, which has no row shapes to read")]
243    NestedRowShapeUnsupported { name: String, kind: &'static str },
244    #[error("error parsing logical technique: code={0}")]
245    ParsingLogicalTechnique(u8),
246    #[error("error parsing physical encoding: code={0}")]
247    ParsingPhysicalEncoding(u8),
248    #[error("error parsing stream type: code={0}")]
249    ParsingStreamType(u8),
250    #[error("found {0} bytes after the expected end of layer")]
251    TrailingLayerData(usize),
252    #[error("unexpected end of input (unable to take {0} bytes)")]
253    UnableToTake(u32),
254    #[error("unexpected stream type {0:?}")]
255    UnexpectedStreamType(StreamType),
256    #[error("unexpected stream type {0:?}, expected {1} for {2}")]
257    UnexpectedStreamType2(StreamType, &'static str, &'static str),
258    #[error("unsupported logical encoding {0:?} for {1}")]
259    UnsupportedLogicalEncoding(LogicalEncoding, &'static str),
260    #[error("invalid combination of logical encodings: {0:?} + {1:?}")]
261    InvalidLogicalEncodings(LogicalTechnique, LogicalTechnique),
262    #[error("logical encoding {0:?} is not one a {1:?} stream has")]
263    LogicalEncodingNotInKind(LogicalCombination, ValueKind),
264    #[error("layer has zero size")]
265    ZeroLayerSize,
266    #[error("bit-packed stream width {0} is outside 1..=32")]
267    #[cfg(feature = "unstable-v2")]
268    ParsingBitWidth(u32),
269    #[error("The encoder used to optimise data is incompatible")]
270    BadEncoderDataCombination,
271    #[error("StagedLayer::encode_explicit requires Encoder.explicit to be Some(_)")]
272    MissingExplicitEncoder,
273
274    // Wire/codec decoding (bytes -> primitives)
275    #[error("buffer underflow: needed {0} bytes, but only {1} remain")]
276    BufferUnderflow(u32, usize),
277    #[error("FastPFor decode failed: expected={0} got={1}")]
278    FastPforDecode(u32, usize),
279    #[error("invalid RLE run length (cannot convert to usize): value={0}")]
280    RleRunLenInvalid(i128),
281    #[error("presence runs overflow the {0} features they cover")]
282    PresenceRunOverflow(u32),
283    #[error("presence names {0} present features out of {1}")]
284    PresenceRunShort(u32, u32),
285    #[error("presence indices are not strictly increasing within {0} features")]
286    PresenceIndexOrder(u32),
287    #[error("unknown presence coding byte: 0x{0:02X}")]
288    PresenceCodingByte(u8),
289
290    // Structural constraints (lengths, counts, shapes)
291    #[error("geometry requires at least 1 stream, got 0")]
292    GeometryWithoutStreams,
293    #[error("FastPFor data byte length expected multiple of 4, got {0}")]
294    InvalidFastPforByteLength(usize),
295    #[error("vec2 delta stream size expected to be non-empty and multiple of 2, got {0}")]
296    InvalidPairStreamSize(usize),
297    #[error("decodable stream size expected {1}, got {0}")]
298    InvalidDecodingStreamSize(usize, usize),
299    #[error("IDs missing for encoding (expected Some IDs, got None)")]
300    IdsMissingForEncoding,
301    #[error("missing struct encoder for struct")]
302    MissingStructEncoderForStruct,
303    #[error("previous decode/parsing attempt failed")]
304    PriorParseFailure,
305    #[error("FSST-compressed data is malformed: {0}")]
306    MalformedFsst(&'static str),
307    #[cfg(feature = "unstable-v2")]
308    #[error("rANS vertex stream is malformed: {0}")]
309    MalformedRans(&'static str),
310    #[cfg(feature = "unstable-v2")]
311    #[error("dictionary code {0} is out of range for a dictionary of {1} values")]
312    DictionaryCodeOutOfRange(u32, usize),
313    #[cfg(feature = "unstable-v2")]
314    #[error(
315        "front-coded lengths stream holds a prefix and a suffix length per entry, so its {0} values cannot be split in two"
316    )]
317    FrontCodedOddLengthCount(usize),
318    #[cfg(feature = "unstable-v2")]
319    #[error(
320        "front-coded entry {index} shares {shared} bytes with a predecessor of only {available}"
321    )]
322    FrontCodedPrefixTooLong {
323        index: usize,
324        shared: usize,
325        available: usize,
326    },
327    #[cfg(feature = "unstable-v2")]
328    #[error(
329        "front-coded entry {index} needs {needed} suffix bytes, but {available} remain in the blob"
330    )]
331    FrontCodedSuffixOutOfBounds {
332        index: usize,
333        needed: usize,
334        available: usize,
335    },
336    #[cfg(feature = "unstable-v2")]
337    #[error("front-coded dictionary leaves {0} suffix bytes after its last entry")]
338    FrontCodedTrailingSuffixBytes(usize),
339    #[cfg(feature = "unstable-v2")]
340    #[error("no Framed, Exception-Free ALP parameters return this float column bit-for-bit")]
341    NoAlpParameters,
342    #[error("invalid Framed, Exception-Free ALP parameters: e={0}, f={1}")]
343    InvalidAlpParams(u8, u8),
344    #[error("invalid Framed, Exception-Free ALP scale byte {0}")]
345    InvalidAlpScale(u8),
346    #[error("presence stream has {0} bits set but {1} values provided")]
347    PresenceValueCountMismatch(usize, usize),
348    #[error("need to encode before being able to write")]
349    NeedsEncodingBeforeWriting,
350    #[error("memory limit exceeded: limit={limit}, used={used}, requested={requested}")]
351    MemoryLimitExceeded {
352        limit: u32,
353        used: u32,
354        requested: u32,
355    },
356    #[error("not implemented: {0}")]
357    NotImplemented(&'static str),
358    #[error("unsupported property value and encoder combination: {0:?} + {1:?}")]
359    UnsupportedPropertyEncoderCombination(&'static str, &'static str),
360    #[error("mixed property types are not allowed in column {0} ({1})")]
361    MixedPropertyTypes(usize, String),
362    #[error("shared dictionary requires at least 2 streams, got {0}")]
363    SharedDictRequiresStreams(usize),
364    #[error("unsupported string stream count (expected between 2 and 5): {0}")]
365    UnsupportedStringStreamCount(usize),
366    #[error("Structs are not allowed to be optional")]
367    TriedToEncodeOptionalStruct,
368    #[error(
369        "encoding instruction count mismatch: expected {input_len} instructions for {input_len} properties, got {config_len}"
370    )]
371    EncodingInstructionCountMismatch { input_len: usize, config_len: usize },
372    #[error("struct child data streams expected exactly 1 value, got {0}")]
373    UnexpectedStructChildCount(u32),
374    // Note that {expected}+1 is allowed for the legacy Java encoder bug
375    #[error("SharedDict stream count is {actual}, expected {expected}")]
376    InvalidSharedDictStreamCount { actual: u32, expected: u32 },
377    #[error("unsupported physical encoding: {0}")]
378    UnsupportedPhysicalEncoding(&'static str),
379    #[error("unsupported physical encoding: {0:?} for {1}")]
380    UnsupportedPhysicalEncodingForType(PhysicalEncoding, &'static str),
381    #[error(
382        "Extent {extent} cannot be encoded to morton due to morton allowing max. 16 bits, but {required_bits} would be required"
383    )]
384    VertexMortonNotCompatibleWithExtent { extent: u32, required_bits: u32 },
385    #[error("Morton stream uses {0} bits, but at most 16 bits are supported")]
386    InvalidMortonBits(u32),
387
388    // Geometry decode errors (field = variable name, geom_type for context)
389    #[error("MVT error: {0}")]
390    BadMvtGeometry(&'static str),
391    #[error("geometry[{0}]: index out of bounds")]
392    GeometryIndexOutOfBounds(usize),
393    #[error("geometry[{index}]: {field}[{idx}] out of bounds (len={len})")]
394    GeometryOutOfBounds {
395        index: usize,
396        field: &'static str,
397        idx: usize,
398        len: usize,
399    },
400    #[error("geometry[{index}]: vertex {vertex} out of bounds (count={count})")]
401    GeometryVertexOutOfBounds {
402        index: usize,
403        vertex: usize,
404        count: usize,
405    },
406    #[error("geometry[{0}]: {1} requires geometry_offsets")]
407    NoGeometryOffsets(usize, GeometryType),
408    #[error("geometry[{0}]: {1} requires part_offsets")]
409    NoPartOffsets(usize, GeometryType),
410    #[error("geometry[{0}]: {1} requires ring_offsets")]
411    NoRingOffsets(usize, GeometryType),
412    #[error("geometry[{0}]: unexpected offset combination for {1}")]
413    UnexpectedOffsetCombination(usize, GeometryType),
414    #[error("geometry: ring lengths without part lengths")]
415    RingLengthsWithoutPartLengths,
416    #[error("geometry[{0}]: {1} requires outlines, which a triangles-only layer does not store")]
417    NonPolygonWithoutOutlines(usize, GeometryType),
418
419    #[error("FastPFor error: {0}")]
420    FastPfor(#[from] fastpfor::FastPForError),
421    #[error(transparent)]
422    Io(#[from] std::io::Error),
423    #[error("Serde JSON error: {0}")]
424    SerdeJsonError(#[from] serde_json::Error),
425    #[error("integer conversion error: {0}")]
426    TryFromIntError(#[from] TryFromIntError),
427    #[error("num_enum conversion error: {0}")]
428    TryFromPrimitive(#[from] TryFromPrimitiveError<GeometryType>),
429    #[error("UTF-8 decode error: {0}")]
430    Utf8(#[from] std::str::Utf8Error),
431    #[error("UTF-8 decode error: {0}")]
432    FromUtf8(#[from] std::string::FromUtf8Error),
433    #[error("MVT error: {0}")]
434    Mvt(#[from] fast_mvt::MvtError),
435    #[error("MVT JSON value error: {0}")]
436    MvtJsonValue(#[from] fast_mvt::MvtJsonValueError),
437}
438
439impl From<MltError> for std::io::Error {
440    fn from(value: MltError) -> Self {
441        if let MltError::Io(e) = value {
442            e
443        } else {
444            Self::other(value)
445        }
446    }
447}
448
449pub(crate) trait AsMltError<T> {
450    fn or_overflow(&self) -> MltResult<T>;
451}
452
453impl<T: Copy> AsMltError<T> for Option<T> {
454    #[inline]
455    fn or_overflow(&self) -> MltResult<T> {
456        self.ok_or(MltError::IntegerOverflow)
457    }
458}
459
460impl AsMltError<u32> for Result<u32, TryFromIntError> {
461    #[inline]
462    fn or_overflow(&self) -> MltResult<u32> {
463        self.map_err(|_| MltError::IntegerOverflow)
464    }
465}
466
467#[inline]
468pub(crate) fn fail_if_invalid_stream_size(actual: usize, expected: usize) -> MltResult<()> {
469    if actual == expected {
470        Ok(())
471    } else {
472        Err(MltError::InvalidDecodingStreamSize(actual, expected))
473    }
474}