Skip to main content

mz_avro/
decode.rs

1// Copyright 2018 Flavien Raynaud.
2// Copyright Materialize, Inc. and contributors. All rights reserved.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License in the LICENSE file at the
7// root of this repository, or online at
8//
9//     http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16//
17// This file is derived from the avro-rs project, available at
18// https://github.com/flavray/avro-rs. It was incorporated
19// directly into Materialize on March 3, 2020.
20//
21// The original source code is subject to the terms of the MIT license, a copy
22// of which can be found in the LICENSE file at the root of this repository.
23
24use std::cmp;
25use std::collections::BTreeSet;
26use std::fmt::{self, Display};
27use std::fs::File;
28use std::io::{self, Cursor, Read, Seek, SeekFrom};
29
30use chrono::{DateTime, NaiveDate};
31use flate2::read::MultiGzDecoder;
32
33use crate::error::{DecodeError, Error as AvroError};
34use crate::schema::{
35    RecordField, ResolvedDefaultValueField, ResolvedRecordField, Schema, SchemaNode, SchemaPiece,
36    SchemaPieceOrNamed, SchemaPieceRefOrNamed,
37};
38use crate::types::{Scalar, Value};
39use crate::util::{TsUnit, safe_len, zag_i32, zag_i64};
40use crate::{TrivialDecoder, ValueDecoder};
41
42#[inline]
43fn decode_long_nonneg<R: Read>(reader: &mut R) -> Result<u64, AvroError> {
44    let u = match zag_i64(reader)? {
45        i if i >= 0 => i as u64,
46        i => return Err(AvroError::Decode(DecodeError::ExpectedNonnegInteger(i))),
47    };
48    Ok(u)
49}
50
51fn decode_int_nonneg<R: Read>(reader: &mut R) -> Result<u32, AvroError> {
52    let u = match zag_i32(reader)? {
53        i if i >= 0 => i as u32,
54        i => {
55            return Err(AvroError::Decode(DecodeError::ExpectedNonnegInteger(
56                i as i64,
57            )));
58        }
59    };
60    Ok(u)
61}
62
63#[inline]
64fn decode_len<R: Read>(reader: &mut R) -> Result<usize, AvroError> {
65    zag_i64(reader).and_then(|i| safe_len(i as usize))
66}
67
68#[inline]
69fn decode_float<R: Read>(reader: &mut R) -> Result<f32, AvroError> {
70    let mut buf = [0u8; 4];
71    reader.read_exact(&mut buf[..])?;
72    Ok(f32::from_le_bytes(buf))
73}
74
75#[inline]
76fn decode_double<R: Read>(reader: &mut R) -> Result<f64, AvroError> {
77    let mut buf = [0u8; 8];
78    reader.read_exact(&mut buf[..])?;
79    Ok(f64::from_le_bytes(buf))
80}
81
82impl Display for TsUnit {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        match self {
85            TsUnit::Millis => write!(f, "ms"),
86            TsUnit::Micros => write!(f, "us"),
87        }
88    }
89}
90
91#[cfg(test)]
92mod tests {
93    use chrono::DateTime;
94
95    use crate::types::Value;
96    use crate::util::TsUnit;
97
98    use super::build_ts_value;
99
100    #[mz_ore::test]
101    fn test_negative_timestamps() {
102        assert_eq!(
103            build_ts_value(-1, TsUnit::Millis).unwrap(),
104            Value::Timestamp(
105                DateTime::from_timestamp(-1, 999_000_000)
106                    .unwrap()
107                    .naive_utc()
108            )
109        );
110        assert_eq!(
111            build_ts_value(-1000, TsUnit::Millis).unwrap(),
112            Value::Timestamp(DateTime::from_timestamp(-1, 0).unwrap().naive_utc())
113        );
114        assert_eq!(
115            build_ts_value(-1000, TsUnit::Micros).unwrap(),
116            Value::Timestamp(
117                DateTime::from_timestamp(-1, 999_000_000)
118                    .unwrap()
119                    .naive_utc()
120            )
121        );
122        assert_eq!(
123            build_ts_value(-1, TsUnit::Micros).unwrap(),
124            Value::Timestamp(
125                DateTime::from_timestamp(-1, 999_999_000)
126                    .unwrap()
127                    .naive_utc()
128            )
129        );
130        assert_eq!(
131            build_ts_value(-123_456_789_123, TsUnit::Micros).unwrap(),
132            Value::Timestamp(
133                DateTime::from_timestamp(-123_457, (1_000_000 - 789_123) * 1_000)
134                    .unwrap()
135                    .naive_utc()
136            )
137        );
138    }
139
140    #[mz_ore::test]
141    fn array_block_len_bounded_by_remaining_input() {
142        // A tiny body claiming a huge array block must error, not allocate. A
143        // small (or hostile) message used to drive an unbounded `Vec<Value>` by
144        // claiming a multi-million-element block whose items decode from ~no
145        // input (e.g. an empty record). Regression for an OOM found by fuzzing.
146        use std::str::FromStr;
147
148        use super::{AvroDeserializer, GeneralDeserializer};
149        use crate::util::zig_i64;
150        use crate::{Schema, ValueDecoder};
151
152        let schema = Schema::from_str(r#"{"type": "array", "items": "long"}"#).unwrap();
153        let mut body = Vec::new();
154        zig_i64(8_000_000, &mut body); // block count dwarfs the (here, empty) element data
155        let dsr = GeneralDeserializer {
156            schema: schema.top_node(),
157        };
158        let mut reader: &[u8] = &body;
159        let res = dsr.deserialize(&mut reader, ValueDecoder);
160        assert!(
161            res.is_err(),
162            "an array block longer than the remaining input must be rejected, not allocated"
163        );
164    }
165
166    #[mz_ore::test]
167    fn zero_width_array_elements_decode() {
168        // The remaining-input bound must not reject valid arrays whose elements
169        // encode to zero bytes. `null` and empty records have no per-element byte
170        // floor, so a ten-element block legitimately follows its count with no
171        // element bytes at all (Materialize's own writer emits `array<null>` of
172        // ten as `[20, 0]`: block count 10, then the terminating zero block).
173        use std::str::FromStr;
174
175        use super::{AvroDeserializer, GeneralDeserializer};
176        use crate::types::Value;
177        use crate::util::zig_i64;
178        use crate::{Schema, ValueDecoder};
179
180        for (items, want) in [
181            (r#""null""#, Value::Null),
182            (
183                r#"{"type": "record", "name": "Empty", "fields": []}"#,
184                Value::Record(vec![]),
185            ),
186        ] {
187            let schema =
188                Schema::from_str(&format!(r#"{{"type": "array", "items": {items}}}"#)).unwrap();
189            let mut body = Vec::new();
190            zig_i64(10, &mut body); // ten elements...
191            body.push(0); // ...then the terminating zero block. No element bytes.
192            let dsr = GeneralDeserializer {
193                schema: schema.top_node(),
194            };
195            let mut reader: &[u8] = &body;
196            let decoded = dsr
197                .deserialize(&mut reader, ValueDecoder)
198                .expect("a zero-width array element type must decode, not be rejected");
199            assert_eq!(decoded, Value::Array(vec![want; 10]));
200        }
201    }
202
203    #[mz_ore::test]
204    fn valid_null_array_falsely_rejected() {
205        // Materialize's encoder emits no element bytes for `null` array
206        // elements, so decoding must not assume each element consumes at least
207        // one byte of remaining input.
208        use std::str::FromStr;
209
210        use super::{AvroDeserializer, GeneralDeserializer};
211        use crate::encode::encode_to_vec;
212        use crate::types::Value;
213        use crate::{Schema, ValueDecoder};
214
215        let schema = Schema::from_str(r#"{"type": "array", "items": "null"}"#).unwrap();
216        let value = Value::Array(vec![Value::Null, Value::Null]);
217        let body = encode_to_vec(&value, &schema);
218
219        let dsr = GeneralDeserializer {
220            schema: schema.top_node(),
221        };
222        let mut reader: &[u8] = &body;
223        let res = dsr.deserialize(&mut reader, ValueDecoder);
224        assert!(
225            res.is_ok(),
226            "an encoder-produced array of nulls should round-trip, but got: {res:?}"
227        );
228    }
229
230    #[mz_ore::test]
231    fn zero_width_array_elements_decode_across_blocks() {
232        // Zero-width arrays can be encoded as multiple blocks. The cumulative
233        // cap must not reject ordinary valid data below the limit.
234        use std::str::FromStr;
235
236        use super::{AvroDeserializer, GeneralDeserializer};
237        use crate::types::Value;
238        use crate::util::zig_i64;
239        use crate::{Schema, ValueDecoder};
240
241        let schema = Schema::from_str(r#"{"type": "array", "items": "null"}"#).unwrap();
242        let mut body = Vec::new();
243        zig_i64(4, &mut body);
244        zig_i64(6, &mut body);
245        body.push(0);
246
247        let dsr = GeneralDeserializer {
248            schema: schema.top_node(),
249        };
250        let mut reader: &[u8] = &body;
251        let decoded = dsr
252            .deserialize(&mut reader, ValueDecoder)
253            .expect("zero-width arrays may span multiple blocks below the cap");
254        assert_eq!(decoded, Value::Array(vec![Value::Null; 10]));
255    }
256
257    #[mz_ore::test]
258    fn zero_width_array_total_len_bounded_across_blocks() {
259        // A zero-width element type has no input-proportional per-block bound.
260        // Keep a cumulative cap so repeated legal-size blocks cannot drive an
261        // unbounded decode. Seed the shared node budget at the cap to test the
262        // edge without walking millions of null elements first.
263        use std::str::FromStr;
264
265        use super::{AvroArrayAccess, DECODE_NODES, MAX_VALUE_NODES, SimpleArrayAccess};
266        use crate::util::zig_i64;
267        use crate::{Schema, TrivialDecoder};
268
269        let schema = Schema::from_str(r#""null""#).unwrap();
270        let mut body = Vec::new();
271        zig_i64(1, &mut body);
272
273        let mut reader: &[u8] = &body;
274        let mut access = SimpleArrayAccess::new(&mut reader, schema.top_node());
275        // Drive `SimpleArrayAccess` directly (no top-level decode entry to reset
276        // the budget), so pre-charge the shared counter to the cap by hand.
277        DECODE_NODES.with(|n| n.set(MAX_VALUE_NODES));
278
279        let err = access
280            .decode_next(TrivialDecoder)
281            .expect_err("a new block past the cumulative node budget must be rejected");
282        DECODE_NODES.with(|n| n.set(0));
283        assert!(
284            err.to_string().contains("exceeds cumulative limit"),
285            "unexpected error: {err}"
286        );
287    }
288
289    #[mz_ore::test]
290    fn zero_width_record_array_bounded() {
291        // Regression for an OOM found by the reader_decode fuzz target: an
292        // `array<record{null}>` element is zero-width on the wire (the byte-floor
293        // check below can't bound it) yet each element still allocates a
294        // `Value::Record`, so a multi-million-element block claimed from a
295        // handful of bytes amplified into gigabytes. The cumulative node cap must
296        // reject it rather than allocate.
297        use std::str::FromStr;
298
299        use super::{AvroDeserializer, GeneralDeserializer};
300        use crate::util::zig_i64;
301        use crate::{Schema, ValueDecoder};
302
303        let schema = Schema::from_str(
304            r#"{"type": "array", "items":
305                {"type": "record", "name": "R", "fields": [{"name": "g0", "type": "null"}]}}"#,
306        )
307        .unwrap();
308        // A single block claiming far more zero-width records than the node cap,
309        // followed by no element bytes at all.
310        let mut body = Vec::new();
311        zig_i64(100_000_000, &mut body);
312        let dsr = GeneralDeserializer {
313            schema: schema.top_node(),
314        };
315        let mut reader: &[u8] = &body;
316        let res = dsr.deserialize(&mut reader, ValueDecoder);
317        assert!(
318            res.is_err(),
319            "an array of zero-width records longer than the node cap must be rejected, not allocated"
320        );
321    }
322
323    #[mz_ore::test]
324    fn small_zero_width_record_array_decodes() {
325        // The node cap must not reject an ordinary, below-cap array of zero-width
326        // records: ten `record{null}`s encode (like `array<null>`) as just the
327        // block count followed by the terminating zero block.
328        use std::str::FromStr;
329
330        use super::{AvroDeserializer, GeneralDeserializer};
331        use crate::types::Value;
332        use crate::util::zig_i64;
333        use crate::{Schema, ValueDecoder};
334
335        let schema = Schema::from_str(
336            r#"{"type": "array", "items":
337                {"type": "record", "name": "R", "fields": [{"name": "g0", "type": "null"}]}}"#,
338        )
339        .unwrap();
340        let mut body = Vec::new();
341        zig_i64(10, &mut body);
342        body.push(0);
343        let dsr = GeneralDeserializer {
344            schema: schema.top_node(),
345        };
346        let mut reader: &[u8] = &body;
347        let decoded = dsr
348            .deserialize(&mut reader, ValueDecoder)
349            .expect("a below-cap array of zero-width records must decode, not be rejected");
350        let want = Value::Record(vec![("g0".to_string(), Value::Null)]);
351        assert_eq!(decoded, Value::Array(vec![want; 10]));
352    }
353
354    #[mz_ore::test]
355    fn nested_zero_width_collection_shares_node_budget() {
356        // Regression: the node budget must be shared across every collection in
357        // one datum, not reset per collection. With a per-collection budget each
358        // inner array of `array<record{array<record{null}>}>` would get a fresh
359        // `MAX_VALUE_NODES` ceiling, so a few wire bytes amplify into
360        // ~`MAX_VALUE_NODES` *per outer element* (the same blow-up the cap exists
361        // to stop, one nesting level deeper). Drive the decode so an inner
362        // array's block-header charge — reached only after the enclosing record
363        // starts decoding — trips the *shared* cumulative cap, proving the inner
364        // collection sees the outer element's spend rather than a fresh budget.
365        use std::str::FromStr;
366
367        use super::{AvroDeserializer, GeneralDeserializer, MAX_VALUE_NODES};
368        use crate::util::zig_i64;
369        use crate::{Schema, ValueDecoder};
370
371        let schema = Schema::from_str(
372            r#"{"type": "array", "items":
373                {"type": "record", "name": "Outer", "fields": [
374                    {"name": "inner", "type":
375                        {"type": "array", "items":
376                            {"type": "record", "name": "Inner",
377                             "fields": [{"name": "g0", "type": "null"}]}}}]}}"#,
378        )
379        .unwrap();
380        // One outer element (charges 2 nodes), whose inner array then claims
381        // `MAX_VALUE_NODES / 2` zero-width records — exactly `MAX_VALUE_NODES`
382        // weighted nodes, which clears the inner block's own per-block check but
383        // pushes the *shared* total (2 + MAX_VALUE_NODES) over the cap. No inner
384        // element bytes follow: a correct decode rejects at the header before
385        // allocating anything; the per-collection bug would instead materialize
386        // ~2M `Value::Record`s and only later hit EOF.
387        let mut body = Vec::new();
388        zig_i64(1, &mut body);
389        zig_i64((MAX_VALUE_NODES / 2) as i64, &mut body);
390        let dsr = GeneralDeserializer {
391            schema: schema.top_node(),
392        };
393        let mut reader: &[u8] = &body;
394        let err = dsr.deserialize(&mut reader, ValueDecoder).expect_err(
395            "a nested array claiming MAX_VALUE_NODES on top of the outer spend must be rejected",
396        );
397        assert!(
398            err.to_string().contains("exceeds cumulative limit"),
399            "unexpected error: {err}"
400        );
401    }
402
403    #[mz_ore::test]
404    fn top_level_decode_resets_stale_node_budget() {
405        // A decode that errored partway can leave the thread-local node counter
406        // non-zero; the next top-level decode must reset it (depth 0 -> 1) or an
407        // unrelated datum on the same thread is wrongly rejected. Pin the counter
408        // at the cap to stand in for that leftover, then require a small array to
409        // still decode.
410        use std::str::FromStr;
411
412        use super::{AvroDeserializer, DECODE_NODES, GeneralDeserializer, MAX_VALUE_NODES};
413        use crate::types::Value;
414        use crate::util::zig_i64;
415        use crate::{Schema, ValueDecoder};
416
417        let schema = Schema::from_str(r#"{"type": "array", "items": "null"}"#).unwrap();
418        let mut body = Vec::new();
419        zig_i64(3, &mut body);
420        body.push(0);
421
422        DECODE_NODES.with(|n| n.set(MAX_VALUE_NODES));
423        let dsr = GeneralDeserializer {
424            schema: schema.top_node(),
425        };
426        let mut reader: &[u8] = &body;
427        let decoded = dsr
428            .deserialize(&mut reader, ValueDecoder)
429            .expect("the top-level entry must reset a stale node budget");
430        assert_eq!(decoded, Value::Array(vec![Value::Null; 3]));
431    }
432}
433
434/// A convenience function to build timestamp values from underlying longs.
435pub fn build_ts_value(value: i64, unit: TsUnit) -> Result<Value, AvroError> {
436    let result = match unit {
437        TsUnit::Millis => DateTime::from_timestamp_millis(value),
438        TsUnit::Micros => DateTime::from_timestamp_micros(value),
439    };
440    let ndt = result.ok_or(AvroError::Decode(DecodeError::BadTimestamp { unit, value }))?;
441    Ok(Value::Timestamp(ndt.naive_utc()))
442}
443
444/// A convenience trait for types that are both readable and skippable.
445///
446/// A blanket implementation is provided for all types that implement both
447/// [`Read`] and [`Skip`].
448pub trait AvroRead: Read + Skip {}
449
450impl<T> AvroRead for T where T: Read + Skip {}
451
452/// A trait that allows for efficient skipping forward while reading data.
453pub trait Skip: Read {
454    /// Advance the cursor by `len` bytes.
455    ///
456    /// If possible, the implementation should be more efficient than calling
457    /// [`Read::read`] and discarding the resulting bytes.
458    ///
459    /// Calling `skip` with a `len` that advances the cursor past the end of the
460    /// underlying data source is permissible. The only requirement is that the
461    /// next call to [`Read::read`] indicates EOF.
462    ///
463    /// # Errors
464    ///
465    /// Can return an error in all the same cases that [`Read::read`] can.
466    ///
467    /// TODO: Remove this clippy suppression when the issue is fixed.
468    /// See <https://github.com/rust-lang/rust-clippy/issues/12519>
469    #[allow(clippy::unused_io_amount)]
470    fn skip(&mut self, mut len: usize) -> Result<(), io::Error> {
471        const BUF_SIZE: usize = 512;
472        let mut buf = [0; BUF_SIZE];
473
474        while len > 0 {
475            let n = if len < BUF_SIZE {
476                self.read(&mut buf[..len])?
477            } else {
478                self.read(&mut buf)?
479            };
480            if n == 0 {
481                break;
482            }
483            len -= n;
484        }
485        Ok(())
486    }
487
488    /// An upper bound, if cheaply known, on the number of bytes still readable
489    /// from this source. Used to reject an array/map block that claims more
490    /// elements than the input could possibly contain: each element consumes at
491    /// least zero bytes, so a block longer than the remaining input only happens
492    /// when a small (or hostile) message claims a huge count, which would
493    /// otherwise drive an unbounded `Vec` allocation (length amplification).
494    /// Streaming sources that can't answer cheaply return `None`.
495    fn remaining_input(&self) -> Option<usize> {
496        None
497    }
498}
499
500impl Skip for File {
501    fn skip(&mut self, len: usize) -> Result<(), io::Error> {
502        self.seek(SeekFrom::Current(len as i64))?;
503        Ok(())
504    }
505}
506
507impl Skip for &[u8] {
508    fn skip(&mut self, len: usize) -> Result<(), io::Error> {
509        let len = cmp::min(len, self.len());
510        *self = &self[len..];
511        Ok(())
512    }
513
514    fn remaining_input(&self) -> Option<usize> {
515        Some(self.len())
516    }
517}
518
519impl<S: Skip + ?Sized> Skip for Box<S> {
520    fn skip(&mut self, len: usize) -> Result<(), io::Error> {
521        self.as_mut().skip(len)
522    }
523
524    fn remaining_input(&self) -> Option<usize> {
525        self.as_ref().remaining_input()
526    }
527}
528
529impl<T: AsRef<[u8]>> Skip for Cursor<T> {
530    fn skip(&mut self, len: usize) -> Result<(), io::Error> {
531        self.seek(SeekFrom::Current(len as i64))?;
532        Ok(())
533    }
534
535    fn remaining_input(&self) -> Option<usize> {
536        let total = self.get_ref().as_ref().len();
537        Some(total.saturating_sub(usize::try_from(self.position()).unwrap_or(usize::MAX)))
538    }
539}
540
541impl<R: Read> Skip for MultiGzDecoder<R> {}
542
543pub enum ValueOrReader<'a, V, R: AvroRead> {
544    Value(V),
545    Reader { len: usize, r: &'a mut R },
546}
547
548enum SchemaOrDefault<'b, R: AvroRead> {
549    Schema(&'b mut R, SchemaNode<'b>),
550    Default(&'b Value),
551}
552pub struct AvroFieldAccess<'b, R: AvroRead> {
553    schema: SchemaOrDefault<'b, R>,
554}
555
556impl<'b, R: AvroRead> AvroFieldAccess<'b, R> {
557    pub fn decode_field<D: AvroDecode>(self, d: D) -> Result<D::Out, AvroError> {
558        match self.schema {
559            SchemaOrDefault::Schema(r, schema) => {
560                let des = GeneralDeserializer { schema };
561                des.deserialize(r, d)
562            }
563            SchemaOrDefault::Default(value) => give_value(d, value),
564        }
565    }
566}
567
568pub trait AvroRecordAccess<R: AvroRead> {
569    fn next_field<'b>(
570        &'b mut self,
571    ) -> Result<Option<(&'b str, usize, AvroFieldAccess<'b, R>)>, AvroError>;
572}
573
574struct SimpleRecordAccess<'a, R: AvroRead> {
575    schema: SchemaNode<'a>,
576    r: &'a mut R,
577    fields: &'a [RecordField],
578    i: usize,
579}
580
581impl<'a, R: AvroRead> SimpleRecordAccess<'a, R> {
582    fn new(schema: SchemaNode<'a>, r: &'a mut R, fields: &'a [RecordField]) -> Self {
583        Self {
584            schema,
585            r,
586            fields,
587            i: 0,
588        }
589    }
590}
591
592impl<'a, R: AvroRead> AvroRecordAccess<R> for SimpleRecordAccess<'a, R> {
593    fn next_field<'b>(
594        &'b mut self,
595    ) -> Result<Option<(&'b str, usize, AvroFieldAccess<'b, R>)>, AvroError> {
596        assert!(self.i <= self.fields.len());
597        if self.i == self.fields.len() {
598            Ok(None)
599        } else {
600            let f = &self.fields[self.i];
601            self.i += 1;
602            Ok(Some((
603                f.name.as_str(),
604                f.position,
605                AvroFieldAccess {
606                    schema: SchemaOrDefault::Schema(self.r, self.schema.step(&f.schema)),
607                },
608            )))
609        }
610    }
611}
612
613struct ValueRecordAccess<'a> {
614    values: &'a [(String, Value)],
615    i: usize,
616}
617
618impl<'a> ValueRecordAccess<'a> {
619    fn new(values: &'a [(String, Value)]) -> Self {
620        Self { values, i: 0 }
621    }
622}
623
624impl<'a> AvroRecordAccess<&'a [u8]> for ValueRecordAccess<'a> {
625    fn next_field<'b>(
626        &'b mut self,
627    ) -> Result<Option<(&'b str, usize, AvroFieldAccess<'b, &'a [u8]>)>, AvroError> {
628        assert!(self.i <= self.values.len());
629        if self.i == self.values.len() {
630            Ok(None)
631        } else {
632            let (name, val) = &self.values[self.i];
633            self.i += 1;
634            Ok(Some((
635                name.as_str(),
636                self.i - 1,
637                AvroFieldAccess {
638                    schema: SchemaOrDefault::Default(val),
639                },
640            )))
641        }
642    }
643}
644
645struct ValueMapAccess<'a> {
646    values: &'a [(String, Value)],
647    i: usize,
648}
649
650impl<'a> ValueMapAccess<'a> {
651    fn new(values: &'a [(String, Value)]) -> Self {
652        Self { values, i: 0 }
653    }
654}
655
656impl<'a> AvroMapAccess for ValueMapAccess<'a> {
657    type R = &'a [u8];
658    fn next_entry<'b>(
659        &'b mut self,
660    ) -> Result<Option<(String, AvroFieldAccess<'b, Self::R>)>, AvroError> {
661        assert!(self.i <= self.values.len());
662        if self.i == self.values.len() {
663            Ok(None)
664        } else {
665            let (name, val) = &self.values[self.i];
666            self.i += 1;
667            Ok(Some((
668                name.clone(),
669                AvroFieldAccess {
670                    schema: SchemaOrDefault::Default(val),
671                },
672            )))
673        }
674    }
675}
676
677struct ResolvedRecordAccess<'a, R: AvroRead> {
678    defaults: &'a [ResolvedDefaultValueField],
679    i_defaults: usize,
680    fields: &'a [ResolvedRecordField],
681    i_fields: usize,
682    r: &'a mut R,
683    schema: SchemaNode<'a>,
684}
685
686impl<'a, R: AvroRead> ResolvedRecordAccess<'a, R> {
687    fn new(
688        defaults: &'a [ResolvedDefaultValueField],
689        fields: &'a [ResolvedRecordField],
690        r: &'a mut R,
691        schema: SchemaNode<'a>,
692    ) -> Self {
693        Self {
694            defaults,
695            i_defaults: 0,
696            fields,
697            i_fields: 0,
698            r,
699            schema,
700        }
701    }
702}
703
704impl<'a, R: AvroRead> AvroRecordAccess<R> for ResolvedRecordAccess<'a, R> {
705    fn next_field<'b>(
706        &'b mut self,
707    ) -> Result<Option<(&'b str, usize, AvroFieldAccess<'b, R>)>, AvroError> {
708        assert!(self.i_defaults <= self.defaults.len() && self.i_fields <= self.fields.len());
709        if self.i_defaults < self.defaults.len() {
710            let default = &self.defaults[self.i_defaults];
711            self.i_defaults += 1;
712            Ok(Some((
713                default.name.as_str(),
714                default.position,
715                AvroFieldAccess {
716                    schema: SchemaOrDefault::Default(&default.default),
717                },
718            )))
719        } else {
720            while self.i_fields < self.fields.len() {
721                let field = &self.fields[self.i_fields];
722                self.i_fields += 1;
723                match field {
724                    ResolvedRecordField::Absent(absent_schema) => {
725                        // we don't care what's in the value, but we still need to read it in order to skip ahead the proper amount in the input.
726                        let d = GeneralDeserializer {
727                            schema: absent_schema.top_node(),
728                        };
729                        d.deserialize(self.r, TrivialDecoder)?;
730                        continue;
731                    }
732                    ResolvedRecordField::Present(field) => {
733                        return Ok(Some((
734                            field.name.as_str(),
735                            field.position,
736                            AvroFieldAccess {
737                                schema: SchemaOrDefault::Schema(
738                                    self.r,
739                                    self.schema.step(&field.schema),
740                                ),
741                            },
742                        )));
743                    }
744                }
745            }
746            Ok(None)
747        }
748    }
749}
750
751pub trait AvroArrayAccess {
752    fn decode_next<D: AvroDecode>(&mut self, d: D) -> Result<Option<D::Out>, AvroError>;
753}
754
755pub trait AvroMapAccess {
756    type R: AvroRead;
757    fn next_entry<'b>(
758        &'b mut self,
759    ) -> Result<Option<(String, AvroFieldAccess<'b, Self::R>)>, AvroError>;
760}
761
762pub struct SimpleMapAccess<'a, R: AvroRead> {
763    entry_schema: SchemaNode<'a>,
764    r: &'a mut R,
765    done: bool,
766    remaining: usize,
767    /// Lower bound on the `Value` nodes a single entry materializes: the key
768    /// `String` plus the value's [`min_value_nodes`]. Charged against the shared
769    /// [`DECODE_NODES`] budget per block; see [`charge_value_nodes`].
770    entry_nodes: usize,
771}
772
773impl<'a, R: AvroRead> SimpleMapAccess<'a, R> {
774    fn new(entry_schema: SchemaNode<'a>, r: &'a mut R) -> Self {
775        Self {
776            entry_schema,
777            r,
778            done: false,
779            remaining: 0,
780            // One node for the key `String`, plus the value's own nodes.
781            entry_nodes: 1usize.saturating_add(min_value_nodes(entry_schema)),
782        }
783    }
784}
785
786impl<'a, R: AvroRead> AvroMapAccess for SimpleMapAccess<'a, R> {
787    type R = R;
788    fn next_entry<'b>(&'b mut self) -> Result<Option<(String, AvroFieldAccess<'b, R>)>, AvroError> {
789        if self.done {
790            return Ok(None);
791        }
792        if self.remaining == 0 {
793            // TODO -- we can use len_in_bytes to quickly skip non-demanded arrays
794            let (len, _len_in_bytes) = match zag_i64(self.r)? {
795                len if len > 0 => (len as usize, None),
796                neglen if neglen < 0 => (neglen.unsigned_abs() as usize, Some(decode_len(self.r)?)),
797                0 => {
798                    self.done = true;
799                    return Ok(None);
800                }
801                _ => unreachable!(),
802            };
803            // See `SimpleArrayAccess::decode_next` — same `MAX_VALUE_NODES`
804            // memory bound applies, weighting the entry count by the per-entry
805            // node lower bound so a block whose values are wide-but-zero-width
806            // records can't amplify a few wire bytes into millions of `Value`s.
807            let block_nodes = len.saturating_mul(self.entry_nodes);
808            if block_nodes > MAX_VALUE_NODES {
809                return Err(AvroError::Decode(DecodeError::Custom(format!(
810                    "Avro map block length {len} exceeds limit {MAX_VALUE_NODES} decoded values"
811                ))));
812            }
813            // Charge against the budget shared by every array/map in the datum,
814            // so nested collections can't each get a fresh cap (see
815            // `charge_value_nodes` / `MAX_VALUE_NODES`).
816            charge_value_nodes("map", block_nodes)?;
817            // A block can't hold more entries than there are bytes left to
818            // decode them from; reject a count that claims otherwise rather than
819            // letting it drive an unbounded allocation (see `Skip::remaining_input`).
820            // Unlike an array item, every map entry encodes at least a one-byte
821            // key-length varint, so each entry has a guaranteed one-byte floor and
822            // a count above the remaining input is always bogus.
823            if let Some(remaining) = self.r.remaining_input() {
824                if len > remaining {
825                    return Err(AvroError::Decode(DecodeError::Custom(format!(
826                        "Avro map block length {len} exceeds remaining input ({remaining} bytes)"
827                    ))));
828                }
829            }
830            self.remaining = len;
831        }
832        assert!(self.remaining > 0);
833        self.remaining -= 1;
834
835        // TODO - We can try to avoid this allocation, but  nobody uses maps in Materialize
836        // right now so it doesn't really matter.
837        let key_len = decode_len(self.r)?;
838        let mut key_buf = vec![];
839        key_buf.resize_with(key_len, Default::default);
840        self.r.read_exact(&mut key_buf)?;
841        let key = String::from_utf8(key_buf)
842            .map_err(|_e| AvroError::Decode(DecodeError::MapKeyUtf8Error))?;
843
844        let a = AvroFieldAccess {
845            schema: SchemaOrDefault::Schema(self.r, self.entry_schema),
846        };
847        Ok(Some((key, a)))
848    }
849}
850
851struct SimpleArrayAccess<'a, R: AvroRead> {
852    r: &'a mut R,
853    schema: SchemaNode<'a>,
854    remaining: usize,
855    /// Lower bound on the `Value` nodes a single element materializes (see
856    /// [`min_value_nodes`]). Charged against the shared [`DECODE_NODES`] budget
857    /// per block; see [`charge_value_nodes`].
858    element_nodes: usize,
859    done: bool,
860}
861
862impl<'a, R: AvroRead> SimpleArrayAccess<'a, R> {
863    fn new(r: &'a mut R, schema: SchemaNode<'a>) -> Self {
864        Self {
865            r,
866            schema,
867            remaining: 0,
868            element_nodes: min_value_nodes(schema),
869            done: false,
870        }
871    }
872}
873
874struct ValueArrayAccess<'a> {
875    values: &'a [Value],
876    i: usize,
877}
878
879impl<'a> ValueArrayAccess<'a> {
880    fn new(values: &'a [Value]) -> Self {
881        Self { values, i: 0 }
882    }
883}
884
885impl<'a> AvroArrayAccess for ValueArrayAccess<'a> {
886    fn decode_next<D: AvroDecode>(&mut self, d: D) -> Result<Option<D::Out>, AvroError> {
887        assert!(self.i <= self.values.len());
888        if self.i == self.values.len() {
889            Ok(None)
890        } else {
891            let val = give_value(d, &self.values[self.i])?;
892            self.i += 1;
893            Ok(Some(val))
894        }
895    }
896}
897
898/// Sanity cap on the number of `Value` nodes one top-level decode may
899/// materialize across *every* array and map in the datum. Arrays and maps apply
900/// it per block (a fast reject for an absurd single-block count) and against the
901/// shared cumulative budget threaded through the whole decode (see
902/// [`charge_value_nodes`] / [`DECODE_NODES`]).
903///
904/// This bounds *memory*, not element count: each element is weighted by
905/// [`min_value_nodes`], a lower bound on the `Value` nodes it decodes into. An
906/// element-count cap alone is not enough, because a zero-width element — `null`,
907/// or a record of only `null`/empty-record fields — occupies no input yet still
908/// allocates a `Value` (a `Vec` slot, plus a record's own `Vec` and field-name
909/// `String`s). The [`min_encoded_len`] byte-floor check below bounds a block by
910/// the remaining input only when each element occupies at least one wire byte,
911/// so a multi-million-element block of zero-width elements would otherwise
912/// amplify a handful of bytes into gigabytes. Weighting the count and capping
913/// the product bounds that amplification (as well as the analogous case of a
914/// huge block of wide, positive-floor records read from a large input).
915///
916/// The budget is shared across the whole datum rather than reset per collection
917/// so the bound *composes through nesting*: a per-collection budget would hand
918/// every `array`/`map` a fresh ceiling, letting a schema like
919/// `array<record{array<record{null}>}>` amplify a few wire bytes into roughly
920/// this cap raised to the nesting depth. Sharing one budget keeps the worst case
921/// flat regardless of nesting.
922///
923/// Without any cap, a malicious or corrupt file can claim up to `i64::MAX` items
924/// and the generic array/map decode loop runs until it OOMs or hits `Vec`
925/// capacity-overflow.
926///
927/// At `1 << 22` nodes the worst case (decoding zero-width records right up to the
928/// cap) peaks around 750 MiB — including the transient doubling of the element
929/// `Vec` mid-`push` — leaving comfortable headroom under the fuzzer's 2 GiB RSS
930/// limit, while still admitting any realistically-sized array/map.
931const MAX_VALUE_NODES: usize = 1 << 22;
932
933/// A *lower* bound on the number of bytes any value of `schema` encodes to on
934/// the wire.
935///
936/// Used to reject an array block whose claimed element count could not possibly
937/// fit in the remaining input: a block of `len` elements occupies at least
938/// `len * min_encoded_len` bytes. Only an under-estimate is ever safe here — an
939/// over-estimate would reject valid data — so anything whose floor we can't
940/// prove (schema-resolution pieces, named-type recursion cycles) contributes
941/// `0`, which simply relaxes the bound.
942///
943/// Crucially this returns `0` for zero-width types — `null`, an empty record, a
944/// record of only such fields — because those genuinely encode to no bytes.
945/// Materialize's own writer emits a ten-element `array<null>` as `[20, 0]`, so a
946/// blanket "count must not exceed remaining bytes" rule would reject valid
947/// input. For zero-width element types the caller falls back to the cumulative
948/// [`MAX_VALUE_NODES`] cap (weighted by [`min_value_nodes`]).
949fn min_encoded_len(schema: SchemaNode) -> usize {
950    let mut visited = BTreeSet::new();
951    min_encoded_len_piece(schema.root, schema.inner, &mut visited)
952}
953
954/// Resolves a (possibly named) schema reference, guarding against named-type
955/// cycles, then defers to [`min_encoded_len_piece`].
956fn min_encoded_len_or_named(
957    root: &Schema,
958    node: SchemaPieceRefOrNamed,
959    visited: &mut BTreeSet<usize>,
960) -> usize {
961    match node {
962        SchemaPieceRefOrNamed::Piece(piece) => min_encoded_len_piece(root, piece, visited),
963        SchemaPieceRefOrNamed::Named(idx) => {
964            // A named-type cycle can only close through a record field; treat
965            // the back-edge as zero-width so we never over-estimate.
966            if !visited.insert(idx) {
967                return 0;
968            }
969            let len = min_encoded_len_piece(root, &root.lookup(idx).piece, visited);
970            visited.remove(&idx);
971            len
972        }
973    }
974}
975
976fn min_encoded_len_piece(
977    root: &Schema,
978    piece: &SchemaPiece,
979    visited: &mut BTreeSet<usize>,
980) -> usize {
981    match piece {
982        // Encodes to nothing at all.
983        SchemaPiece::Null => 0,
984        // A single byte (zig-zag varint of 0 is one byte; a bool is one byte).
985        SchemaPiece::Boolean
986        | SchemaPiece::Int
987        | SchemaPiece::Long
988        | SchemaPiece::Date
989        | SchemaPiece::TimestampMilli
990        | SchemaPiece::TimestampMicro => 1,
991        SchemaPiece::Float => 4,
992        SchemaPiece::Double => 8,
993        // `fixed`-backed decimals are exactly their size; `bytes`-backed ones,
994        // like `bytes`/`string`, carry at least a one-byte length varint.
995        SchemaPiece::Decimal {
996            fixed_size: Some(size),
997            ..
998        } => *size,
999        SchemaPiece::Decimal {
1000            fixed_size: None, ..
1001        }
1002        | SchemaPiece::Bytes
1003        | SchemaPiece::String
1004        | SchemaPiece::Json
1005        | SchemaPiece::Uuid => 1,
1006        // An empty array/map encodes as a single zero-count byte regardless of
1007        // the element type, so don't recurse into it.
1008        SchemaPiece::Array(_) | SchemaPiece::Map(_) => 1,
1009        // A union always writes at least its one-byte branch index.
1010        SchemaPiece::Union(_) => 1,
1011        // An enum writes a one-byte symbol index.
1012        SchemaPiece::Enum { .. } => 1,
1013        SchemaPiece::Fixed { size } => *size,
1014        // A record's encoding is its fields' encodings concatenated, so its
1015        // floor is the sum of the fields' floors — which can be `0` (the empty
1016        // record, or a record of only `null`/empty-record fields).
1017        SchemaPiece::Record { fields, .. } => fields.iter().fold(0, |acc, field| {
1018            acc.saturating_add(min_encoded_len_or_named(
1019                root,
1020                field.schema.as_ref(),
1021                visited,
1022            ))
1023        }),
1024        // Schema-resolution pieces only arise on the reader/writer-mismatch
1025        // path; we don't try to prove a floor for them.
1026        _ => 0,
1027    }
1028}
1029
1030/// Bounds the object count an object-container-file block declares against the
1031/// payload that is supposed to hold those objects.
1032///
1033/// The count comes straight off the wire, and `util::safe_len` alone caps it at
1034/// `MAX_ALLOCATION_BYTES` — a sensible ceiling for a byte length, an enormous one
1035/// for a count, and in no way related to the block it describes. `payload_len` is
1036/// the block's *decompressed* length.
1037///
1038/// Which bound applies is decided the same way as for an array block, and for the
1039/// same reason (see [`min_encoded_len`]): the byte floor when the object schema has
1040/// a proven positive one, otherwise the node-weighted cap, because a zero-width
1041/// object — an empty record, or a record of only `null`/empty-record fields —
1042/// encodes to no bytes at all, so no payload length can constrain how many of them
1043/// a block may claim.
1044///
1045/// Unlike an array block, the two bounds are *alternatives* rather than both being
1046/// applied. An array materializes all of its elements at once, so its cap is about
1047/// retained memory; a block's objects are yielded and dropped one at a time, so the
1048/// cap here is about work amplified out of a few bytes. Once the byte floor holds,
1049/// the work is linear in the file and needs no further ceiling — and capping nodes
1050/// as well would reject a legitimate large block of small records.
1051///
1052/// Not charged against [`DECODE_NODES`]: that budget is per top-level datum and
1053/// each object in a block is its own datum. This is a standalone check on the
1054/// block header.
1055pub(crate) fn bound_block_object_count(
1056    schema: SchemaNode,
1057    count: usize,
1058    payload_len: usize,
1059) -> Result<(), AvroError> {
1060    let min_bytes = min_encoded_len(schema);
1061    if min_bytes > 0 {
1062        if count.saturating_mul(min_bytes) > payload_len {
1063            return Err(AvroError::Decode(DecodeError::Custom(format!(
1064                "Avro block object count {count} exceeds block payload ({payload_len} bytes)"
1065            ))));
1066        }
1067        return Ok(());
1068    }
1069    let nodes = count.saturating_mul(min_value_nodes(schema));
1070    if nodes > MAX_VALUE_NODES {
1071        return Err(AvroError::Decode(DecodeError::Custom(format!(
1072            "Avro block object count {count} exceeds limit {MAX_VALUE_NODES} decoded values"
1073        ))));
1074    }
1075    Ok(())
1076}
1077
1078/// A *lower* bound on the number of `Value` nodes a single value of `schema`
1079/// materializes into when decoded.
1080///
1081/// Used to weight an array/map element so the cumulative [`MAX_VALUE_NODES`] cap
1082/// bounds decoded *memory*, not just element count. The amplifying case the cap
1083/// exists for — `null` and records of only zero-width fields — is counted
1084/// *exactly* here (a record always materializes every field, and none of these
1085/// types involve a union/array/map whose runtime size we couldn't predict), so
1086/// the bound is tight where it matters most.
1087///
1088/// As with [`min_encoded_len`], only an under-estimate is ever safe (an
1089/// over-estimate would reject valid data), so a nested array/map contributes
1090/// `1` — its empty-collection floor — and its actual contents are charged
1091/// against the shared [`MAX_VALUE_NODES`] budget as they are decoded (so the
1092/// cap still composes through nesting); a union contributes `1` (its count is
1093/// already bounded by the remaining input via its one-byte branch floor); and
1094/// unprovable schema-resolution pieces contribute `1`. Every value is at least
1095/// one node, so the weight is always `>= 1`.
1096fn min_value_nodes(schema: SchemaNode) -> usize {
1097    let mut visited = BTreeSet::new();
1098    min_value_nodes_piece(schema.root, schema.inner, &mut visited)
1099}
1100
1101/// Resolves a (possibly named) schema reference, guarding against named-type
1102/// cycles, then defers to [`min_value_nodes_piece`].
1103fn min_value_nodes_or_named(
1104    root: &Schema,
1105    node: SchemaPieceRefOrNamed,
1106    visited: &mut BTreeSet<usize>,
1107) -> usize {
1108    match node {
1109        SchemaPieceRefOrNamed::Piece(piece) => min_value_nodes_piece(root, piece, visited),
1110        SchemaPieceRefOrNamed::Named(idx) => {
1111            // A named-type cycle can only close through a record field; treat the
1112            // back-edge as a single node so we never over-estimate (and never
1113            // recurse forever).
1114            if !visited.insert(idx) {
1115                return 1;
1116            }
1117            let nodes = min_value_nodes_piece(root, &root.lookup(idx).piece, visited);
1118            visited.remove(&idx);
1119            nodes
1120        }
1121    }
1122}
1123
1124fn min_value_nodes_piece(
1125    root: &Schema,
1126    piece: &SchemaPiece,
1127    visited: &mut BTreeSet<usize>,
1128) -> usize {
1129    match piece {
1130        // A record materializes itself plus every one of its fields. This is the
1131        // only type that can be zero-width on the wire yet still allocate, so
1132        // counting its fields exactly is what makes the cap effective.
1133        SchemaPiece::Record { fields, .. } => fields.iter().fold(1, |acc, field| {
1134            acc.saturating_add(min_value_nodes_or_named(
1135                root,
1136                field.schema.as_ref(),
1137                visited,
1138            ))
1139        }),
1140        // Every other type materializes a single node for the purposes of this
1141        // lower bound: scalars and leaves trivially; an array/map at minimum an
1142        // empty collection (its contents bounded by its own cumulative cap); a
1143        // union its (input-bounded) branch index; and resolution pieces we don't
1144        // try to prove.
1145        _ => 1,
1146    }
1147}
1148
1149impl<'a, R: AvroRead> AvroArrayAccess for SimpleArrayAccess<'a, R> {
1150    fn decode_next<D: AvroDecode>(&mut self, d: D) -> Result<Option<D::Out>, AvroError> {
1151        if self.done {
1152            return Ok(None);
1153        }
1154        if self.remaining == 0 {
1155            // TODO -- we can use len_in_bytes to quickly skip non-demanded arrays
1156            let (len, _len_in_bytes) = match zag_i64(self.r)? {
1157                len if len > 0 => (len as usize, None),
1158                neglen if neglen < 0 => (neglen.unsigned_abs() as usize, Some(decode_len(self.r)?)),
1159                0 => {
1160                    self.done = true;
1161                    return Ok(None);
1162                }
1163                _ => unreachable!(),
1164            };
1165            // Weight the count by the per-element node lower bound so the cap
1166            // bounds decoded memory, not just element count: a block of
1167            // zero-width-but-allocating elements (e.g. a record of `null`s)
1168            // amplifies a few wire bytes into millions of `Value`s otherwise.
1169            let block_nodes = len.saturating_mul(self.element_nodes);
1170            if block_nodes > MAX_VALUE_NODES {
1171                return Err(AvroError::Decode(DecodeError::Custom(format!(
1172                    "Avro array block length {len} exceeds limit {MAX_VALUE_NODES} \
1173                     decoded values"
1174                ))));
1175            }
1176            // Charge against the budget shared by every array/map in the datum,
1177            // so nested collections can't each get a fresh cap (see
1178            // `charge_value_nodes` / `MAX_VALUE_NODES`).
1179            charge_value_nodes("array", block_nodes)?;
1180            // A block of `len` items occupies at least `len * min_elem` bytes,
1181            // so a count needing more than the remaining input can't be honest;
1182            // reject it rather than let it drive an unbounded allocation (see
1183            // `Skip::remaining_input`). Unlike a map entry — which always carries
1184            // at least a one-byte key-length varint — an array item can encode to
1185            // zero bytes (`null`, an empty record), so this bound only applies
1186            // when the element type has a proven positive byte floor. For
1187            // zero-width element types (`min_elem == 0`) we rely on the
1188            // cumulative `MAX_VALUE_NODES` cap; otherwise a valid datum such as a
1189            // ten-element `array<null>` (encoded as `[20, 0]`) would be wrongly
1190            // rejected.
1191            if let Some(remaining) = self.r.remaining_input() {
1192                let min_elem = min_encoded_len(self.schema);
1193                if min_elem > 0 && len.saturating_mul(min_elem) > remaining {
1194                    return Err(AvroError::Decode(DecodeError::Custom(format!(
1195                        "Avro array block length {len} exceeds remaining input ({remaining} bytes)"
1196                    ))));
1197                }
1198            }
1199            self.remaining = len;
1200        }
1201        assert!(self.remaining > 0);
1202        self.remaining -= 1;
1203        let des = GeneralDeserializer {
1204            schema: self.schema,
1205        };
1206        des.deserialize(self.r, d).map(Some)
1207    }
1208}
1209
1210pub trait AvroDecode: Sized {
1211    type Out;
1212    fn record<R: AvroRead, A: AvroRecordAccess<R>>(
1213        self,
1214        _a: &mut A,
1215    ) -> Result<Self::Out, AvroError>;
1216
1217    fn union_branch<'a, R: AvroRead, D: AvroDeserializer>(
1218        self,
1219        _idx: usize,
1220        _n_variants: usize,
1221        _null_variant: Option<usize>,
1222        _deserializer: D,
1223        _reader: &'a mut R,
1224    ) -> Result<Self::Out, AvroError>;
1225
1226    fn array<A: AvroArrayAccess>(self, _a: &mut A) -> Result<Self::Out, AvroError>;
1227
1228    fn map<M: AvroMapAccess>(self, _m: &mut M) -> Result<Self::Out, AvroError>;
1229
1230    fn enum_variant(self, _symbol: &str, _idx: usize) -> Result<Self::Out, AvroError>;
1231
1232    fn scalar(self, _scalar: Scalar) -> Result<Self::Out, AvroError>;
1233
1234    fn decimal<'a, R: AvroRead>(
1235        self,
1236        _precision: usize,
1237        _scale: usize,
1238        _r: ValueOrReader<'a, &'a [u8], R>,
1239    ) -> Result<Self::Out, AvroError>;
1240
1241    fn bytes<'a, R: AvroRead>(
1242        self,
1243        _r: ValueOrReader<'a, &'a [u8], R>,
1244    ) -> Result<Self::Out, AvroError>;
1245    fn string<'a, R: AvroRead>(
1246        self,
1247        _r: ValueOrReader<'a, &'a str, R>,
1248    ) -> Result<Self::Out, AvroError>;
1249    fn json<'a, R: AvroRead>(
1250        self,
1251        _r: ValueOrReader<'a, &'a serde_json::Value, R>,
1252    ) -> Result<Self::Out, AvroError>;
1253    fn uuid<'a, R: AvroRead>(
1254        self,
1255        _r: ValueOrReader<'a, &'a [u8], R>,
1256    ) -> Result<Self::Out, AvroError>;
1257    fn fixed<'a, R: AvroRead>(
1258        self,
1259        _r: ValueOrReader<'a, &'a [u8], R>,
1260    ) -> Result<Self::Out, AvroError>;
1261}
1262
1263pub mod public_decoders {
1264
1265    use std::collections::BTreeMap;
1266
1267    use crate::error::{DecodeError, Error as AvroError};
1268    use crate::types::{DecimalValue, Scalar, Value};
1269    use crate::{
1270        AvroArrayAccess, AvroDecode, AvroDeserializer, AvroRead, AvroRecordAccess, ValueOrReader,
1271    };
1272
1273    use super::AvroMapAccess;
1274
1275    pub struct TrivialDecoder;
1276
1277    impl TrivialDecoder {
1278        fn maybe_skip<'a, V, R: AvroRead>(
1279            self,
1280            r: ValueOrReader<'a, V, R>,
1281        ) -> Result<(), AvroError> {
1282            if let ValueOrReader::Reader { len, r } = r {
1283                Ok(r.skip(len)?)
1284            } else {
1285                Ok(())
1286            }
1287        }
1288    }
1289
1290    impl AvroDecode for TrivialDecoder {
1291        type Out = ();
1292        fn record<R: AvroRead, A: AvroRecordAccess<R>>(self, a: &mut A) -> Result<(), AvroError> {
1293            while let Some((_, _, f)) = a.next_field()? {
1294                f.decode_field(TrivialDecoder)?;
1295            }
1296            Ok(())
1297        }
1298        fn union_branch<'a, R: AvroRead, D: AvroDeserializer>(
1299            self,
1300            _idx: usize,
1301            _n_variants: usize,
1302            _null_variant: Option<usize>,
1303            deserializer: D,
1304            reader: &'a mut R,
1305        ) -> Result<(), AvroError> {
1306            deserializer.deserialize(reader, self)
1307        }
1308
1309        fn enum_variant(self, _symbol: &str, _idx: usize) -> Result<(), AvroError> {
1310            Ok(())
1311        }
1312        fn scalar(self, _scalar: Scalar) -> Result<(), AvroError> {
1313            Ok(())
1314        }
1315        fn decimal<'a, R: AvroRead>(
1316            self,
1317            _precision: usize,
1318            _scale: usize,
1319            r: ValueOrReader<'a, &'a [u8], R>,
1320        ) -> Result<(), AvroError> {
1321            self.maybe_skip(r)
1322        }
1323        fn bytes<'a, R: AvroRead>(
1324            self,
1325            r: ValueOrReader<'a, &'a [u8], R>,
1326        ) -> Result<(), AvroError> {
1327            self.maybe_skip(r)
1328        }
1329        fn string<'a, R: AvroRead>(
1330            self,
1331            r: ValueOrReader<'a, &'a str, R>,
1332        ) -> Result<(), AvroError> {
1333            self.maybe_skip(r)
1334        }
1335        fn json<'a, R: AvroRead>(
1336            self,
1337            r: ValueOrReader<'a, &'a serde_json::Value, R>,
1338        ) -> Result<(), AvroError> {
1339            self.maybe_skip(r)
1340        }
1341        fn uuid<'a, R: AvroRead>(self, r: ValueOrReader<'a, &'a [u8], R>) -> Result<(), AvroError> {
1342            self.maybe_skip(r)
1343        }
1344        fn fixed<'a, R: AvroRead>(
1345            self,
1346            r: ValueOrReader<'a, &'a [u8], R>,
1347        ) -> Result<(), AvroError> {
1348            self.maybe_skip(r)
1349        }
1350        fn array<A: AvroArrayAccess>(self, a: &mut A) -> Result<(), AvroError> {
1351            while a.decode_next(TrivialDecoder)?.is_some() {}
1352            Ok(())
1353        }
1354
1355        fn map<M: AvroMapAccess>(self, m: &mut M) -> Result<(), AvroError> {
1356            while let Some((_n, entry)) = m.next_entry()? {
1357                entry.decode_field(TrivialDecoder)?
1358            }
1359            Ok(())
1360        }
1361    }
1362    pub struct ValueDecoder;
1363    impl AvroDecode for ValueDecoder {
1364        type Out = Value;
1365        fn record<R: AvroRead, A: AvroRecordAccess<R>>(
1366            self,
1367            a: &mut A,
1368        ) -> Result<Value, AvroError> {
1369            let mut fields = vec![];
1370            while let Some((name, idx, f)) = a.next_field()? {
1371                let next = ValueDecoder;
1372                let val = f.decode_field(next)?;
1373                fields.push((idx, (name.to_string(), val)));
1374            }
1375            fields.sort_by_key(|(idx, _)| *idx);
1376
1377            Ok(Value::Record(
1378                fields
1379                    .into_iter()
1380                    .map(|(_idx, (name, val))| (name, val))
1381                    .collect(),
1382            ))
1383        }
1384        fn union_branch<'a, R: AvroRead, D: AvroDeserializer>(
1385            self,
1386            index: usize,
1387            n_variants: usize,
1388            null_variant: Option<usize>,
1389            deserializer: D,
1390            reader: &'a mut R,
1391        ) -> Result<Value, AvroError> {
1392            let next = ValueDecoder;
1393            let inner = Box::new(deserializer.deserialize(reader, next)?);
1394            Ok(Value::Union {
1395                index,
1396                inner,
1397                n_variants,
1398                null_variant,
1399            })
1400        }
1401        fn array<A: AvroArrayAccess>(self, a: &mut A) -> Result<Value, AvroError> {
1402            let mut items = vec![];
1403            loop {
1404                let next = ValueDecoder;
1405
1406                if let Some(value) = a.decode_next(next)? {
1407                    items.push(value)
1408                } else {
1409                    break;
1410                }
1411            }
1412            Ok(Value::Array(items))
1413        }
1414        fn enum_variant(self, symbol: &str, idx: usize) -> Result<Value, AvroError> {
1415            Ok(Value::Enum(idx, symbol.to_string()))
1416        }
1417        fn scalar(self, scalar: Scalar) -> Result<Value, AvroError> {
1418            Ok(scalar.into())
1419        }
1420        fn decimal<'a, R: AvroRead>(
1421            self,
1422            precision: usize,
1423            scale: usize,
1424            r: ValueOrReader<'a, &'a [u8], R>,
1425        ) -> Result<Value, AvroError> {
1426            let unscaled = match r {
1427                ValueOrReader::Value(buf) => buf.to_vec(),
1428                ValueOrReader::Reader { len, r } => {
1429                    let mut buf = vec![];
1430                    buf.resize_with(len, Default::default);
1431                    r.read_exact(&mut buf)?;
1432                    buf
1433                }
1434            };
1435            Ok(Value::Decimal(DecimalValue {
1436                unscaled,
1437                precision,
1438                scale,
1439            }))
1440        }
1441        fn bytes<'a, R: AvroRead>(
1442            self,
1443            r: ValueOrReader<'a, &'a [u8], R>,
1444        ) -> Result<Value, AvroError> {
1445            let buf = match r {
1446                ValueOrReader::Value(buf) => buf.to_vec(),
1447                ValueOrReader::Reader { len, r } => {
1448                    let mut buf = vec![];
1449                    buf.resize_with(len, Default::default);
1450                    r.read_exact(&mut buf)?;
1451                    buf
1452                }
1453            };
1454            Ok(Value::Bytes(buf))
1455        }
1456        fn string<'a, R: AvroRead>(
1457            self,
1458            r: ValueOrReader<'a, &'a str, R>,
1459        ) -> Result<Value, AvroError> {
1460            let s = match r {
1461                ValueOrReader::Value(s) => s.to_string(),
1462                ValueOrReader::Reader { len, r } => {
1463                    let mut buf = vec![];
1464                    buf.resize_with(len, Default::default);
1465                    r.read_exact(&mut buf)?;
1466                    String::from_utf8(buf)
1467                        .map_err(|_e| AvroError::Decode(DecodeError::StringUtf8Error))?
1468                }
1469            };
1470            Ok(Value::String(s))
1471        }
1472        fn json<'a, R: AvroRead>(
1473            self,
1474            r: ValueOrReader<'a, &'a serde_json::Value, R>,
1475        ) -> Result<Value, AvroError> {
1476            let val = match r {
1477                ValueOrReader::Value(val) => val.clone(),
1478                ValueOrReader::Reader { len, r } => {
1479                    let mut buf = vec![];
1480                    buf.resize_with(len, Default::default);
1481                    r.read_exact(&mut buf)?;
1482                    serde_json::from_slice(&buf).map_err(|e| {
1483                        AvroError::Decode(DecodeError::BadJson {
1484                            category: e.classify(),
1485                            bytes: buf.to_owned(),
1486                        })
1487                    })?
1488                }
1489            };
1490            Ok(Value::Json(val))
1491        }
1492        fn uuid<'a, R: AvroRead>(
1493            self,
1494            r: ValueOrReader<'a, &'a [u8], R>,
1495        ) -> Result<Value, AvroError> {
1496            let buf = match r {
1497                ValueOrReader::Value(val) => val.to_vec(),
1498                ValueOrReader::Reader { len, r } => {
1499                    let mut buf = vec![];
1500                    buf.resize_with(len, Default::default);
1501                    r.read_exact(&mut buf)?;
1502                    buf
1503                }
1504            };
1505            let s = std::str::from_utf8(&buf)
1506                .map_err(|_| AvroError::Decode(DecodeError::UuidUtf8Error))?;
1507            let val =
1508                uuid::Uuid::parse_str(s).map_err(|e| AvroError::Decode(DecodeError::BadUuid(e)))?;
1509            Ok(Value::Uuid(val))
1510        }
1511        fn fixed<'a, R: AvroRead>(
1512            self,
1513            r: ValueOrReader<'a, &'a [u8], R>,
1514        ) -> Result<Value, AvroError> {
1515            let buf = match r {
1516                ValueOrReader::Value(buf) => buf.to_vec(),
1517                ValueOrReader::Reader { len, r } => {
1518                    let mut buf = vec![];
1519                    buf.resize_with(len, Default::default);
1520                    r.read_exact(&mut buf)?;
1521                    buf
1522                }
1523            };
1524            Ok(Value::Fixed(buf.len(), buf))
1525        }
1526        fn map<M: AvroMapAccess>(self, m: &mut M) -> Result<Value, AvroError> {
1527            let mut entries = BTreeMap::new();
1528            while let Some((name, a)) = m.next_entry()? {
1529                let d = ValueDecoder;
1530                let val = a.decode_field(d)?;
1531                entries.insert(name, val);
1532            }
1533            Ok(Value::Map(entries))
1534        }
1535    }
1536}
1537
1538impl<'a> AvroDeserializer for &'a Value {
1539    fn deserialize<R: AvroRead, D: AvroDecode>(
1540        self,
1541        _r: &mut R,
1542        d: D,
1543    ) -> Result<D::Out, AvroError> {
1544        give_value(d, self)
1545    }
1546}
1547
1548pub fn give_value<D: AvroDecode>(d: D, v: &Value) -> Result<D::Out, AvroError> {
1549    use ValueOrReader::Value as V;
1550    match v {
1551        Value::Null => d.scalar(Scalar::Null),
1552        Value::Boolean(val) => d.scalar(Scalar::Boolean(*val)),
1553        Value::Int(val) => d.scalar(Scalar::Int(*val)),
1554        Value::Long(val) => d.scalar(Scalar::Long(*val)),
1555        Value::Float(val) => d.scalar(Scalar::Float(*val)),
1556        Value::Double(val) => d.scalar(Scalar::Double(*val)),
1557        Value::Date(val) => d.scalar(Scalar::Date(*val)),
1558        Value::Timestamp(val) => d.scalar(Scalar::Timestamp(*val)),
1559        // The &[u8] parameter here (and elsewhere in this function) is arbitrary, but we have to put in something in order for the function
1560        // to type-check
1561        Value::Decimal(val) => d.decimal::<&[u8]>(val.precision, val.scale, V(&val.unscaled)),
1562        Value::Bytes(val) => d.bytes::<&[u8]>(V(val)),
1563        Value::String(val) => d.string::<&[u8]>(V(val)),
1564        Value::Fixed(_len, val) => d.fixed::<&[u8]>(V(val)),
1565        Value::Enum(idx, symbol) => d.enum_variant(symbol, *idx),
1566        Value::Union {
1567            index,
1568            inner,
1569            n_variants,
1570            null_variant,
1571        } => {
1572            let mut empty_reader: &[u8] = &[];
1573            d.union_branch(
1574                *index,
1575                *n_variants,
1576                *null_variant,
1577                &**inner,
1578                &mut empty_reader,
1579            )
1580        }
1581        Value::Array(val) => {
1582            let mut a = ValueArrayAccess::new(val);
1583            d.array(&mut a)
1584        }
1585        Value::Map(val) => {
1586            let vals: Vec<_> = val.clone().into_iter().collect();
1587            let mut m = ValueMapAccess::new(vals.as_slice());
1588            d.map(&mut m)
1589        }
1590        Value::Record(val) => {
1591            let mut a = ValueRecordAccess::new(val);
1592            d.record(&mut a)
1593        }
1594        Value::Json(val) => d.json::<&[u8]>(V(val)),
1595        Value::Uuid(val) => d.uuid::<&[u8]>(V(val.to_string().as_bytes())),
1596    }
1597}
1598
1599pub trait AvroDeserializer {
1600    fn deserialize<R: AvroRead, D: AvroDecode>(self, r: &mut R, d: D) -> Result<D::Out, AvroError>;
1601}
1602
1603#[derive(Clone, Copy)]
1604pub struct GeneralDeserializer<'a> {
1605    pub schema: SchemaNode<'a>,
1606}
1607
1608/// Cap on recursive `GeneralDeserializer::deserialize` calls. Avro records
1609/// may reference themselves (`{"name":"X","type":"record","fields":[
1610/// {"name":"x","type":"X"}]}`), so a malicious file plus matching wire
1611/// bytes can recurse forever and overflow the stack.
1612const MAX_DECODE_DEPTH: usize = 128;
1613
1614thread_local! {
1615    static DECODE_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1616    /// Cumulative `Value` nodes decoded so far in the current top-level decode,
1617    /// shared by every array and map in the datum and bounded by
1618    /// [`MAX_VALUE_NODES`]. Reset to `0` at each top-level entry (see
1619    /// [`DecodeDepthGuard::enter`]) so the budget composes across nesting
1620    /// instead of resetting per collection. Charged via [`charge_value_nodes`].
1621    static DECODE_NODES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1622}
1623
1624struct DecodeDepthGuard;
1625impl DecodeDepthGuard {
1626    fn enter() -> Result<Self, AvroError> {
1627        DECODE_DEPTH.with(|d| {
1628            let new = d.get() + 1;
1629            if new > MAX_DECODE_DEPTH {
1630                return Err(AvroError::Decode(DecodeError::Custom(format!(
1631                    "Avro decode depth exceeds limit {MAX_DECODE_DEPTH}"
1632                ))));
1633            }
1634            d.set(new);
1635            // The `Value`-node budget is shared across every array/map in one
1636            // datum so nesting can't multiply the cap (see `MAX_VALUE_NODES`).
1637            // This is the top-level entry (depth 0 -> 1), so reset it: each datum
1638            // starts fresh even if a previous decode on this thread errored out
1639            // partway and left the counter non-zero.
1640            if new == 1 {
1641                DECODE_NODES.with(|n| n.set(0));
1642            }
1643            Ok(DecodeDepthGuard)
1644        })
1645    }
1646}
1647impl Drop for DecodeDepthGuard {
1648    fn drop(&mut self) {
1649        DECODE_DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
1650    }
1651}
1652
1653/// Charges `nodes` against the per-datum [`DECODE_NODES`] budget shared by every
1654/// array and map in a single top-level decode, rejecting once the cumulative
1655/// total exceeds [`MAX_VALUE_NODES`]. `kind` (`"array"` / `"map"`) only labels
1656/// the error.
1657///
1658/// The budget is shared — rather than tracked per collection instance — so the
1659/// cap composes across nesting; see [`MAX_VALUE_NODES`] for why a per-collection
1660/// budget would let nested zero-width collections amplify past it.
1661fn charge_value_nodes(kind: &str, nodes: usize) -> Result<(), AvroError> {
1662    DECODE_NODES.with(|n| {
1663        let total = n.get().saturating_add(nodes);
1664        if total > MAX_VALUE_NODES {
1665            return Err(AvroError::Decode(DecodeError::Custom(format!(
1666                "Avro {kind} decode exceeds cumulative limit {MAX_VALUE_NODES} decoded values"
1667            ))));
1668        }
1669        n.set(total);
1670        Ok(())
1671    })
1672}
1673
1674impl<'a> AvroDeserializer for GeneralDeserializer<'a> {
1675    fn deserialize<R: AvroRead, D: AvroDecode>(self, r: &mut R, d: D) -> Result<D::Out, AvroError> {
1676        let _guard = DecodeDepthGuard::enter()?;
1677        use ValueOrReader::Reader;
1678        match self.schema.inner {
1679            SchemaPiece::Null => d.scalar(Scalar::Null),
1680            SchemaPiece::Boolean => {
1681                let mut buf = [0u8; 1];
1682                r.read_exact(&mut buf[..])?;
1683                let val = match buf[0] {
1684                    0u8 => false,
1685                    1u8 => true,
1686                    other => return Err(AvroError::Decode(DecodeError::BadBoolean(other))),
1687                };
1688                d.scalar(Scalar::Boolean(val))
1689            }
1690            SchemaPiece::Int => {
1691                let val = zag_i32(r)?;
1692                d.scalar(Scalar::Int(val))
1693            }
1694            SchemaPiece::Long => {
1695                let val = zag_i64(r)?;
1696                d.scalar(Scalar::Long(val))
1697            }
1698            SchemaPiece::Float => {
1699                let val = decode_float(r)?;
1700                d.scalar(Scalar::Float(val))
1701            }
1702            SchemaPiece::Double => {
1703                let val = decode_double(r)?;
1704                d.scalar(Scalar::Double(val))
1705            }
1706            SchemaPiece::Date => {
1707                let days = zag_i32(r)?;
1708                d.scalar(Scalar::Date(days))
1709            }
1710            SchemaPiece::TimestampMilli => {
1711                let total_millis = zag_i64(r)?;
1712                let scalar = match build_ts_value(total_millis, TsUnit::Millis)? {
1713                    Value::Timestamp(ts) => Scalar::Timestamp(ts),
1714                    _ => unreachable!(),
1715                };
1716                d.scalar(scalar)
1717            }
1718            SchemaPiece::TimestampMicro => {
1719                let total_micros = zag_i64(r)?;
1720                let scalar = match build_ts_value(total_micros, TsUnit::Micros)? {
1721                    Value::Timestamp(ts) => Scalar::Timestamp(ts),
1722                    _ => unreachable!(),
1723                };
1724                d.scalar(scalar)
1725            }
1726            SchemaPiece::Decimal {
1727                precision,
1728                scale,
1729                fixed_size,
1730            } => {
1731                let len = fixed_size.map(Ok).unwrap_or_else(|| decode_len(r))?;
1732                d.decimal(*precision, *scale, Reader { len, r })
1733            }
1734            SchemaPiece::Bytes => {
1735                let len = decode_len(r)?;
1736                d.bytes(Reader { len, r })
1737            }
1738            SchemaPiece::String => {
1739                let len = decode_len(r)?;
1740                d.string(Reader { len, r })
1741            }
1742            SchemaPiece::Json => {
1743                let len = decode_len(r)?;
1744                d.json(Reader { len, r })
1745            }
1746            SchemaPiece::Uuid => {
1747                let len = decode_len(r)?;
1748                d.uuid(Reader { len, r })
1749            }
1750            SchemaPiece::Array(inner) => {
1751                // From the spec:
1752                // Arrays are encoded as a series of blocks. Each block consists of a long count value, followed by that many array items. A block with count zero indicates the end of the array. Each item is encoded per the array's item schema.
1753                // If a block's count is negative, its absolute value is used, and the count is followed immediately by a long block size indicating the number of bytes in the block. This block size permits fast skipping through data, e.g., when projecting a record to a subset of its fields.
1754
1755                let mut a = SimpleArrayAccess::new(r, self.schema.step(inner));
1756                d.array(&mut a)
1757            }
1758            SchemaPiece::Map(inner) => {
1759                // See logic for `SchemaPiece::Array` above. Maps are encoded similarly.
1760                let mut m = SimpleMapAccess::new(self.schema.step(inner), r);
1761                d.map(&mut m)
1762            }
1763            SchemaPiece::Union(inner) => {
1764                let index = decode_long_nonneg(r)? as usize;
1765                let variants = inner.variants();
1766                match variants.get(index) {
1767                    Some(variant) => {
1768                        let n_variants = variants.len();
1769                        let null_variant = variants
1770                            .iter()
1771                            .position(|v| v == &SchemaPieceOrNamed::Piece(SchemaPiece::Null));
1772                        let dsr = GeneralDeserializer {
1773                            schema: self.schema.step(variant),
1774                        };
1775                        d.union_branch(index, n_variants, null_variant, dsr, r)
1776                    }
1777                    None => Err(AvroError::Decode(DecodeError::BadUnionIndex {
1778                        index,
1779                        len: variants.len(),
1780                    })),
1781                }
1782            }
1783            SchemaPiece::ResolveIntLong => {
1784                let val = zag_i32(r)? as i64;
1785                d.scalar(Scalar::Long(val))
1786            }
1787            SchemaPiece::ResolveIntFloat => {
1788                let val = zag_i32(r)? as f32;
1789                d.scalar(Scalar::Float(val))
1790            }
1791            SchemaPiece::ResolveIntDouble => {
1792                let val = zag_i32(r)? as f64;
1793                d.scalar(Scalar::Double(val))
1794            }
1795            SchemaPiece::ResolveLongFloat => {
1796                let val = zag_i64(r)? as f32;
1797                d.scalar(Scalar::Float(val))
1798            }
1799            SchemaPiece::ResolveLongDouble => {
1800                let val = zag_i64(r)? as f64;
1801                d.scalar(Scalar::Double(val))
1802            }
1803            SchemaPiece::ResolveFloatDouble => {
1804                let val = decode_float(r)? as f64;
1805                d.scalar(Scalar::Double(val))
1806            }
1807            SchemaPiece::ResolveConcreteUnion {
1808                index,
1809                inner,
1810                n_reader_variants,
1811                reader_null_variant,
1812            } => {
1813                let dsr = GeneralDeserializer {
1814                    schema: self.schema.step(&**inner),
1815                };
1816                d.union_branch(*index, *n_reader_variants, *reader_null_variant, dsr, r)
1817            }
1818            SchemaPiece::ResolveUnionUnion {
1819                permutation,
1820                n_reader_variants,
1821                reader_null_variant,
1822            } => {
1823                let index = decode_long_nonneg(r)? as usize;
1824                if index >= permutation.len() {
1825                    return Err(AvroError::Decode(DecodeError::BadUnionIndex {
1826                        index,
1827                        len: permutation.len(),
1828                    }));
1829                }
1830                match &permutation[index] {
1831                    Err(e) => Err(e.clone()),
1832                    Ok((index, variant)) => {
1833                        let dsr = GeneralDeserializer {
1834                            schema: self.schema.step(variant),
1835                        };
1836                        d.union_branch(*index, *n_reader_variants, *reader_null_variant, dsr, r)
1837                    }
1838                }
1839            }
1840            SchemaPiece::ResolveUnionConcrete { index, inner } => {
1841                let found_index = decode_long_nonneg(r)? as usize;
1842                if *index != found_index {
1843                    Err(AvroError::Decode(DecodeError::WrongUnionIndex {
1844                        expected: *index,
1845                        actual: found_index,
1846                    }))
1847                } else {
1848                    let dsr = GeneralDeserializer {
1849                        schema: self.schema.step(inner.as_ref()),
1850                    };
1851                    // The reader is not expecting a union here, so don't call `D::union_branch`
1852                    dsr.deserialize(r, d)
1853                }
1854            }
1855            SchemaPiece::Record {
1856                doc: _,
1857                fields,
1858                lookup: _,
1859            } => {
1860                let mut a = SimpleRecordAccess::new(self.schema, r, fields);
1861                d.record(&mut a)
1862            }
1863            SchemaPiece::Enum {
1864                symbols,
1865                doc: _,
1866                default_idx: _,
1867            } => {
1868                let index = decode_int_nonneg(r)? as usize;
1869                match symbols.get(index) {
1870                    None => Err(AvroError::Decode(DecodeError::BadEnumIndex {
1871                        index,
1872                        len: symbols.len(),
1873                    })),
1874                    Some(symbol) => d.enum_variant(symbol, index),
1875                }
1876            }
1877            SchemaPiece::Fixed { size } => d.fixed(Reader { len: *size, r }),
1878            // XXX - This does not deliver fields to the consumer in the same order they were
1879            // declared in the reader schema, which might cause headache for consumers...
1880            // Unfortunately, there isn't a good way to do so without pre-decoding the whole record
1881            // (which would require a lot of allocations)
1882            // and then sorting the fields. So, just let the consumer deal with re-ordering.
1883            SchemaPiece::ResolveRecord {
1884                defaults,
1885                fields,
1886                n_reader_fields: _,
1887            } => {
1888                let mut a = ResolvedRecordAccess::new(defaults, fields, r, self.schema);
1889                d.record(&mut a)
1890            }
1891            SchemaPiece::ResolveEnum {
1892                doc: _,
1893                symbols,
1894                default,
1895            } => {
1896                let index = decode_int_nonneg(r)? as usize;
1897                match symbols.get(index) {
1898                    None => Err(AvroError::Decode(DecodeError::BadEnumIndex {
1899                        index,
1900                        len: symbols.len(),
1901                    })),
1902                    Some(op) => match op {
1903                        Err(missing) => {
1904                            if let Some((reader_index, symbol)) = default.clone() {
1905                                d.enum_variant(&symbol, reader_index)
1906                            } else {
1907                                Err(AvroError::Decode(DecodeError::MissingEnumIndex {
1908                                    index,
1909                                    symbol: missing.clone(),
1910                                }))
1911                            }
1912                        }
1913                        Ok((index, name)) => d.enum_variant(name, *index),
1914                    },
1915                }
1916            }
1917            SchemaPiece::ResolveIntTsMilli => {
1918                let total_millis = zag_i32(r)?;
1919                let scalar = match build_ts_value(total_millis as i64, TsUnit::Millis)? {
1920                    Value::Timestamp(ts) => Scalar::Timestamp(ts),
1921                    _ => unreachable!(),
1922                };
1923                d.scalar(scalar)
1924            }
1925            SchemaPiece::ResolveIntTsMicro => {
1926                let total_micros = zag_i32(r)?;
1927                let scalar = match build_ts_value(total_micros as i64, TsUnit::Micros)? {
1928                    Value::Timestamp(ts) => Scalar::Timestamp(ts),
1929                    _ => unreachable!(),
1930                };
1931                d.scalar(scalar)
1932            }
1933            SchemaPiece::ResolveDateTimestamp => {
1934                let days = zag_i32(r)?;
1935
1936                let date = NaiveDate::from_ymd_opt(1970, 1, 1)
1937                    .expect("naive date known valid")
1938                    .checked_add_signed(
1939                        chrono::Duration::try_days(days.into())
1940                            .ok_or(AvroError::Decode(DecodeError::BadDate(days)))?,
1941                    )
1942                    .ok_or(AvroError::Decode(DecodeError::BadDate(days)))?;
1943                let dt = date.and_hms_opt(0, 0, 0).expect("HMS known valid");
1944                d.scalar(Scalar::Timestamp(dt))
1945            }
1946        }
1947    }
1948}
1949/// Decode a `Value` from avro format given its `Schema`.
1950pub fn decode<'a, R: AvroRead>(
1951    schema: SchemaNode<'a>,
1952    reader: &'a mut R,
1953) -> Result<Value, AvroError> {
1954    let d = ValueDecoder;
1955    let dsr = GeneralDeserializer { schema };
1956    let val = dsr.deserialize(reader, d)?;
1957    Ok(val)
1958}