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