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