mz_repr/adt/
jsonb.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! JSON representation.
11//!
12//! This module provides a [`serde_json`]-like API that is backed by the native
13//! Materialize data format, i.e., [`Row`] and [`Datum`]. It supports
14//! efficiently parsing and serializing JSON strings and byte slices with
15//! minimal allocations. It also provides seamless interop with APIs that
16//! require [`serde_json::Value`], though at a small performance cost.
17//!
18//! There are two core types in the module:
19//!
20//!   * [`Jsonb`] represents owned JSON data. This type houses the
21//!     deserialization functions.
22//!
23//!   * [`JsonbRef`] is a borrowed view of JSON data. This type houses the
24//!     serialization functions.
25//!
26//! The name "jsonb" is based on the PostgreSQL data type of the same name.
27//! Various sources claim this stands for "JSON better", as compared to the
28//! less-efficient `json` data type in PostgreSQL.
29//!
30//! ## Constructing JSON objects
31//!
32//! To parse JSON from a string, use the [`FromStr`] implementation. Once
33//! parsed, the underlying [`Row`] can be extracted with [`Jsonb::into_row`].
34//!
35//! ```
36//! # use mz_repr::adt::jsonb::Jsonb;
37//! let jsonb: Jsonb = r#"{"a": 1, "b": 2}"#.parse()?;
38//! let row = jsonb.into_row();
39//! # Ok::<(), Box<dyn std::error::Error>>(())
40//! ```
41//!
42//! If the source JSON is in bytes, use [`Jsonb::from_slice`] instead:
43//!
44//! ```
45//! # use mz_repr::adt::jsonb::Jsonb;
46//! let jsonb = Jsonb::from_slice(br#"{"a": 1, "b": 2}"#);
47//! # Ok::<(), Box<dyn std::error::Error>>(())
48//! ```
49//!
50//! ## Serializing JSON objects
51//!
52//! To write a JSON object to a string, use the [`fmt::Display`] implementation.
53//! The alternate format produces pretty output.
54//!
55//! ```
56//! # use mz_repr::adt::jsonb::Jsonb;
57//! # let jsonb: Jsonb = "null".parse().unwrap();
58//! format!("compressed: {}", jsonb);
59//! format!("pretty: {:#}", jsonb);
60//! ```
61//!
62//! ## Direct JSON deserialization
63//!
64//! You can skip [`Jsonb`] entirely and deserialize JSON directly into an
65//! existing [`Row`] with [`JsonbPacker`]. This saves an allocation and a
66//! copy.
67//!
68//! ```rust
69//! # use mz_repr::adt::jsonb::JsonbPacker;
70//! # use mz_repr::{Datum, Row};
71//! let mut row = Row::default();
72//! let mut packer = row.packer();
73//! packer.push(Datum::Int32(42));
74//! JsonbPacker::new(&mut packer).pack_str("[1, 2]")?;
75//! # Ok::<(), Box<dyn std::error::Error>>(())
76//! ```
77
78use std::borrow::Cow;
79use std::str::{self, FromStr};
80use std::{fmt, io};
81
82use dec::OrderedDecimal;
83use serde::de::{self, DeserializeSeed, Deserializer, MapAccess, SeqAccess, Visitor};
84use serde::ser::{Serialize, SerializeMap, SerializeSeq, SerializeStruct, Serializer};
85
86use crate::adt::jsonb::vec_stack::VecStack;
87use crate::adt::numeric::Numeric;
88use crate::{Datum, Row, RowPacker, SharedRow, strconv};
89
90/// An owned JSON value backed by a [`Row`].
91///
92/// Similar to [`serde_json::Value`], but the conversion to [`Row`] is free.
93///
94/// All numbers are represented as [`f64`]s. It is not possible to construct a
95/// `Jsonb` from a JSON object that contains integers that cannot be represented
96/// exactly as `f64`s.
97#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
98pub struct Jsonb {
99    row: Row,
100}
101
102impl Jsonb {
103    /// Constructs a new `Jsonb` from a [`serde_json::Value`].
104    pub fn from_serde_json(val: serde_json::Value) -> Result<Self, anyhow::Error> {
105        let mut row = Row::default();
106        JsonbPacker::new(&mut row.packer()).pack_serde_json(val)?;
107        Ok(Jsonb { row })
108    }
109
110    /// Parses a `Jsonb` from a byte slice `buf`.
111    ///
112    /// Errors if the slice is not valid JSON.
113    pub fn from_slice(buf: &[u8]) -> Result<Jsonb, anyhow::Error> {
114        let mut row_builder = SharedRow::get();
115        let mut packer = row_builder.packer();
116        JsonbPacker::new(&mut packer).pack_slice(buf)?;
117        Ok(Jsonb {
118            row: row_builder.clone(),
119        })
120    }
121
122    /// Constructs a [`JsonbRef`] that references the JSON in this `Jsonb`.
123    pub fn as_ref(&self) -> JsonbRef {
124        JsonbRef {
125            datum: self.row.unpack_first(),
126        }
127    }
128
129    /// Constructs a `Jsonb` from a [`Row`] containing a single [`Datum`].
130    ///
131    /// Note that `row` is not checked for validity. Not all `Datum`s are
132    /// valid JSON.
133    pub fn from_row(row: Row) -> Jsonb {
134        Jsonb { row }
135    }
136
137    /// Consumes this `Jsonb` and returns the underlying [`Row`].
138    pub fn into_row(self) -> Row {
139        self.row
140    }
141
142    /// Returns a reference to the underlying [`Row`].
143    pub fn row(&self) -> &Row {
144        &self.row
145    }
146}
147
148impl FromStr for Jsonb {
149    type Err = anyhow::Error;
150
151    fn from_str(s: &str) -> Result<Self, Self::Err> {
152        let mut row = Row::default();
153        JsonbPacker::new(&mut row.packer()).pack_str(s)?;
154        Ok(Jsonb { row })
155    }
156}
157
158impl fmt::Display for Jsonb {
159    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
160        self.as_ref().fmt(f)
161    }
162}
163
164/// A borrowed JSON value.
165///
166/// `JsonbRef` is to [`Jsonb`] as [`&str`](prim@str) is to [`String`].
167#[derive(Debug, Copy, Clone)]
168pub struct JsonbRef<'a> {
169    datum: Datum<'a>,
170}
171
172impl<'a> JsonbRef<'a> {
173    /// Constructs a `JsonbRef` from a [`Datum`].
174    ///
175    /// Note that `datum` is not checked for validity. Not all `Datum`s are
176    /// valid JSON.
177    pub fn from_datum(datum: Datum) -> JsonbRef {
178        JsonbRef { datum }
179    }
180
181    /// Unwraps a `JsonbRef` and returns the inner [`Datum`].
182    pub fn into_datum(self) -> Datum<'a> {
183        self.datum
184    }
185
186    /// Constructs an owned [`Jsonb`] from this `JsonbRef`.
187    pub fn to_owned(&self) -> Jsonb {
188        Jsonb {
189            row: Row::pack_slice(&[self.datum]),
190        }
191    }
192
193    /// Serializes the JSON value into the given IO stream.
194    ///
195    /// # Panics
196    ///
197    /// Panics if this `JsonbRef` was constructed with a [`Datum`] that is not
198    /// representable as JSON.
199    pub fn to_writer<W>(&self, writer: W) -> Result<(), anyhow::Error>
200    where
201        W: io::Write,
202    {
203        serde_json::to_writer(writer, &JsonbDatum(self.datum))?;
204        Ok(())
205    }
206
207    /// Constructs an owned [`serde_json::Value`] from this `JsonbRef`.
208    ///
209    /// # Panics
210    ///
211    /// Panics if this `JsonbRef` was constructed with a [`Datum`] that is not
212    /// representable as JSON.
213    pub fn to_serde_json(&self) -> serde_json::Value {
214        serde_json::to_value(JsonbDatum(self.datum))
215            .expect("conversion to serde_json::Value known to be valid")
216    }
217}
218
219impl fmt::Display for JsonbRef<'_> {
220    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
221        let alternate = f.alternate();
222        let mut w = WriterFormatter { inner: f };
223        if alternate {
224            serde_json::to_writer_pretty(&mut w, &JsonbDatum(self.datum)).map_err(|_| fmt::Error)
225        } else {
226            serde_json::to_writer(&mut w, &JsonbDatum(self.datum)).map_err(|_| fmt::Error)
227        }
228    }
229}
230
231/// A JSON deserializer that decodes directly into an existing [`RowPacker`].
232#[derive(Debug)]
233pub struct JsonbPacker<'a, 'row> {
234    packer: &'a mut RowPacker<'row>,
235}
236
237impl<'a, 'row> JsonbPacker<'a, 'row> {
238    /// Constructs a new `JsonbPacker` that will pack into `row`.
239    pub fn new(packer: &'a mut RowPacker<'row>) -> JsonbPacker<'a, 'row> {
240        JsonbPacker { packer }
241    }
242
243    /// Packs a [`serde_json::Value`].
244    pub fn pack_serde_json(self, val: serde_json::Value) -> Result<(), serde_json::Error> {
245        let mut commands = vec![];
246        Collector(&mut commands).deserialize(val)?;
247        pack(self.packer, &commands);
248        Ok(())
249    }
250
251    /// Parses and packs a JSON-formatted byte slice.
252    ///
253    /// Errors if the slice is not valid JSON.
254    pub fn pack_slice(self, buf: &[u8]) -> Result<(), serde_json::Error> {
255        let mut commands = vec![];
256        let mut deserializer = serde_json::Deserializer::from_slice(buf);
257        Collector(&mut commands).deserialize(&mut deserializer)?;
258        deserializer.end()?;
259        pack(self.packer, &commands);
260        Ok(())
261    }
262
263    /// Parses and packs a JSON-formatted string.
264    ///
265    /// Errors if the string is not valid JSON.
266    pub fn pack_str(self, s: &str) -> Result<(), serde_json::Error> {
267        let mut commands = vec![];
268        let mut deserializer = serde_json::Deserializer::from_str(s);
269        Collector(&mut commands).deserialize(&mut deserializer)?;
270        deserializer.end()?;
271        pack(self.packer, &commands);
272        Ok(())
273    }
274}
275
276// The magic internal key name that serde_json uses to indicate that an
277// arbitrary-precision number should be serialized or deserialized. Yes, this is
278// technically private API, but there's no other way to hook into this machinery
279// that doesn't involve all the allocations that come with `serde_json::Value`.
280// See the comments in `JsonbDatum::Serialize` and `Collector::visit_map` for
281// details.
282const SERDE_JSON_NUMBER_TOKEN: &str = "$serde_json::private::Number";
283
284// To support arbitrary-precision numbers, serde_json pretends the JSON
285// contained a map like the following:
286//
287//     {"$serde_json::private::Number": "NUMBER AS STRING"}
288//
289// The code here sniffs out that special map and emits just the numeric
290// value.
291
292#[derive(Debug)]
293pub(crate) enum KeyClass<'de> {
294    Number,
295    MapKey(Cow<'de, str>),
296}
297
298pub(crate) struct KeyClassifier;
299
300impl<'de> DeserializeSeed<'de> for KeyClassifier {
301    type Value = KeyClass<'de>;
302
303    fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
304    where
305        D: serde::Deserializer<'de>,
306    {
307        deserializer.deserialize_str(self)
308    }
309}
310
311impl<'de> Visitor<'de> for KeyClassifier {
312    type Value = KeyClass<'de>;
313
314    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
315        formatter.write_str("a string key")
316    }
317
318    #[inline]
319    fn visit_borrowed_str<E>(self, key: &'de str) -> Result<Self::Value, E> {
320        match key {
321            SERDE_JSON_NUMBER_TOKEN => Ok(KeyClass::Number),
322            _ => Ok(KeyClass::MapKey(Cow::Borrowed(key))),
323        }
324    }
325
326    #[inline]
327    fn visit_str<E>(self, key: &str) -> Result<Self::Value, E> {
328        match key {
329            SERDE_JSON_NUMBER_TOKEN => Ok(KeyClass::Number),
330            _ => Ok(KeyClass::MapKey(Cow::Owned(key.to_owned()))),
331        }
332    }
333}
334
335pub(crate) struct NumberParser;
336
337impl<'de> DeserializeSeed<'de> for NumberParser {
338    type Value = OrderedDecimal<Numeric>;
339
340    fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
341    where
342        D: serde::Deserializer<'de>,
343    {
344        deserializer.deserialize_str(self)
345    }
346}
347
348impl<'de> Visitor<'de> for NumberParser {
349    type Value = OrderedDecimal<Numeric>;
350
351    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
352        formatter.write_str("a valid number")
353    }
354
355    #[inline]
356    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
357    where
358        E: de::Error,
359    {
360        strconv::parse_numeric(value).map_err(de::Error::custom)
361    }
362}
363
364#[derive(Debug)]
365enum Command<'de> {
366    Null,
367    Bool(bool),
368    Numeric(OrderedDecimal<Numeric>),
369    String(Cow<'de, str>),
370    Array(usize), // further commands
371    Map(usize),   // further commands
372}
373
374struct Collector<'a, 'de>(&'a mut Vec<Command<'de>>);
375
376impl<'a, 'de> DeserializeSeed<'de> for Collector<'a, 'de> {
377    type Value = ();
378
379    fn deserialize<D>(self, deserializer: D) -> Result<(), D::Error>
380    where
381        D: Deserializer<'de>,
382    {
383        deserializer.deserialize_any(self)
384    }
385}
386
387impl<'a, 'de> Visitor<'de> for Collector<'a, 'de> {
388    type Value = ();
389
390    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
391        formatter.write_str("a valid JSON datum")
392    }
393
394    #[inline]
395    fn visit_unit<E>(self) -> Result<(), E> {
396        self.0.push(Command::Null);
397        Ok(())
398    }
399
400    #[inline]
401    fn visit_bool<E>(self, value: bool) -> Result<(), E> {
402        self.0.push(Command::Bool(value));
403        Ok(())
404    }
405
406    #[inline]
407    fn visit_i64<E>(self, value: i64) -> Result<(), E>
408    where
409        E: de::Error,
410    {
411        self.0.push(Command::Numeric(OrderedDecimal(value.into())));
412        Ok(())
413    }
414
415    #[inline]
416    fn visit_u64<E>(self, value: u64) -> Result<(), E>
417    where
418        E: de::Error,
419    {
420        self.0.push(Command::Numeric(OrderedDecimal(value.into())));
421        Ok(())
422    }
423
424    #[inline]
425    fn visit_f64<E>(self, value: f64) -> Result<(), E> {
426        self.0.push(Command::Numeric(OrderedDecimal(value.into())));
427        Ok(())
428    }
429
430    #[inline]
431    fn visit_str<E>(self, value: &str) -> Result<(), E> {
432        self.0.push(Command::String(Cow::Owned(value.to_owned())));
433        Ok(())
434    }
435
436    #[inline]
437    fn visit_borrowed_str<E>(self, value: &'de str) -> Result<(), E> {
438        self.0.push(Command::String(Cow::Borrowed(value)));
439        Ok(())
440    }
441
442    #[inline]
443    fn visit_seq<V>(self, mut visitor: V) -> Result<(), V::Error>
444    where
445        V: SeqAccess<'de>,
446    {
447        self.0.push(Command::Array(0));
448        let start = self.0.len();
449        while visitor.next_element_seed(Collector(self.0))?.is_some() {}
450        self.0[start - 1] = Command::Array(self.0.len() - start);
451        Ok(())
452    }
453
454    #[inline]
455    fn visit_map<V>(self, mut visitor: V) -> Result<(), V::Error>
456    where
457        V: MapAccess<'de>,
458    {
459        match visitor.next_key_seed(KeyClassifier)? {
460            Some(KeyClass::Number) => {
461                let n = visitor.next_value_seed(NumberParser)?;
462                self.0.push(Command::Numeric(n));
463            }
464            Some(KeyClass::MapKey(key)) => {
465                self.0.push(Command::Map(0));
466                let start = self.0.len();
467                self.0.push(Command::String(key));
468                visitor.next_value_seed(Collector(self.0))?;
469                while visitor.next_key_seed(Collector(self.0))?.is_some() {
470                    visitor.next_value_seed(Collector(self.0))?;
471                }
472                self.0[start - 1] = Command::Map(self.0.len() - start);
473            }
474            None => self.0.push(Command::Map(0)),
475        }
476
477        Ok(())
478    }
479}
480
481struct DictEntry<'a> {
482    key: &'a str,
483    val: &'a [Command<'a>],
484}
485
486fn pack(packer: &mut RowPacker, value: &[Command]) {
487    let mut buf = vec![];
488    pack_value(packer, VecStack::new(&mut buf), value);
489}
490
491#[inline]
492fn pack_value<'a, 'scratch>(
493    packer: &mut RowPacker,
494    scratch: VecStack<'scratch, DictEntry<'a>>,
495    value: &'a [Command<'a>],
496) {
497    match &value[0] {
498        Command::Null => packer.push(Datum::JsonNull),
499        Command::Bool(b) => packer.push(if *b { Datum::True } else { Datum::False }),
500        Command::Numeric(n) => packer.push(Datum::Numeric(*n)),
501        Command::String(s) => packer.push(Datum::String(s)),
502        Command::Array(further) => {
503            let range = &value[1..][..*further];
504            pack_list(packer, scratch, range);
505        }
506        Command::Map(further) => {
507            let range = &value[1..][..*further];
508            pack_dict(packer, scratch, range);
509        }
510    }
511}
512
513/// Packs a sequence of values as an ordered list.
514fn pack_list<'a, 'scratch>(
515    packer: &mut RowPacker,
516    mut scratch: VecStack<'scratch, DictEntry<'a>>,
517    mut values: &'a [Command<'a>],
518) {
519    packer.push_list_with(|packer| {
520        while !values.is_empty() {
521            let value = extract_value(&mut values);
522            pack_value(packer, scratch.fresh(), value);
523        }
524    })
525}
526
527/// Packs a sequence of (key, val) pairs as an ordered dictionary.
528///
529/// The keys are required to be `Command::String` variants, and
530/// the entries in the dictionary are sorted by these strings.
531/// Multiple values for the same key are detected and only
532/// the last value is kept.
533fn pack_dict<'a, 'scratch>(
534    packer: &mut RowPacker,
535    mut scratch: VecStack<'scratch, DictEntry<'a>>,
536    mut entries: &'a [Command<'a>],
537) {
538    while !entries.is_empty() {
539        if let Command::String(key) = &entries[0] {
540            entries = &entries[1..];
541            let val = extract_value(&mut entries);
542            scratch.push(DictEntry { key, val });
543        } else {
544            unreachable!("JSON decoding produced invalid command sequence");
545        }
546    }
547
548    // Keys must be written in ascending order, per the requirements of our
549    // `Row` representation. If keys are duplicated, we must keep only the last
550    // value for the key, as ordered by appearance in the source JSON, per
551    // PostgreSQL's implementation.
552    scratch.sort_by_key(|entry| entry.key);
553    packer.push_dict_with(|packer| {
554        for i in 0..scratch.len() {
555            if i == scratch.len() - 1 || scratch[i].key != scratch[i + 1].key {
556                let DictEntry { key, val } = scratch[i];
557                packer.push(Datum::String(key));
558                pack_value(packer, scratch.fresh(), val);
559            }
560        }
561    });
562}
563
564/// Extracts a self-contained slice of commands for the next parse node.
565fn extract_value<'a>(values: &mut &'a [Command<'a>]) -> &'a [Command<'a>] {
566    let result = match values[0] {
567        Command::Array(further) => &values[..further + 1],
568        Command::Map(further) => &values[..further + 1],
569        _ => &values[0..1],
570    };
571    *values = &values[result.len()..];
572    result
573}
574
575/// A wrapper for [`Datum`] that implements [`Serialize`].
576///
577/// This is a separate type from `JsonbRef` because the `Serialize`
578/// implementation is only valid for use with serde_json. If we implemented it
579/// on `JsonbRef` directly, it would be possible to serialize a `JsonbRef` into
580/// any serde format, like YAML, but that transformation would not be tested
581/// and would likely be invalid.
582struct JsonbDatum<'a>(Datum<'a>);
583
584impl Serialize for JsonbDatum<'_> {
585    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
586    where
587        S: Serializer,
588    {
589        match self.0 {
590            Datum::JsonNull => serializer.serialize_none(),
591            Datum::True => serializer.serialize_bool(true),
592            Datum::False => serializer.serialize_bool(false),
593            Datum::Numeric(n) => {
594                // To serialize an arbitrary-precision number, we present
595                // serde_json with the following magic struct:
596                //
597                //     struct $serde_json::private::Number {
598                //          $serde_json::private::Number: <NUMBER VALUE>,
599                //     }
600                //
601                let mut s = serializer.serialize_struct(SERDE_JSON_NUMBER_TOKEN, 1)?;
602                s.serialize_field(
603                    SERDE_JSON_NUMBER_TOKEN,
604                    &n.into_inner().to_standard_notation_string(),
605                )?;
606                s.end()
607            }
608            Datum::String(s) => serializer.serialize_str(s),
609            Datum::List(list) => {
610                let mut seq = serializer.serialize_seq(None)?;
611                for e in list.iter() {
612                    seq.serialize_element(&JsonbDatum(e))?;
613                }
614                seq.end()
615            }
616            Datum::Map(dict) => {
617                let mut map = serializer.serialize_map(None)?;
618                for (k, v) in dict.iter() {
619                    map.serialize_entry(k, &JsonbDatum(v))?;
620                }
621                map.end()
622            }
623            d => unreachable!("not a json-compatible datum: {:?}", d),
624        }
625    }
626}
627
628/// Implements `io::Write` for `fmt::Formatter`.
629struct WriterFormatter<'a, 'b: 'a> {
630    inner: &'a mut fmt::Formatter<'b>,
631}
632
633impl<'a, 'b> io::Write for WriterFormatter<'a, 'b> {
634    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
635        fn io_error<E>(_: E) -> io::Error {
636            // Error value is dropped by `fmt::Display` implementations above.
637            io::Error::new(io::ErrorKind::Other, "fmt error")
638        }
639        let s = str::from_utf8(buf).map_err(io_error)?;
640        self.inner.write_str(s).map_err(io_error)?;
641        Ok(buf.len())
642    }
643
644    fn flush(&mut self) -> io::Result<()> {
645        Ok(())
646    }
647}
648
649mod vec_stack {
650    use std::ops::Index;
651
652    /// A `VecStack` presents as a stack of [`Vec`]s where only the vector at
653    /// the top of the stack is accessible. It is backed by a single [`Vec`]
654    /// whose allocation is reused as elements are added to and dropped from the
655    /// stack, and so it can be more efficient than allocating individual
656    /// vectors.
657    pub struct VecStack<'a, T> {
658        buf: &'a mut Vec<T>,
659        i: usize,
660    }
661
662    impl<'a, T> VecStack<'a, T> {
663        /// Creates a new `VecStack` backed by `buf`.
664        ///
665        /// The stack starts with a single psuedo-vector.
666        pub fn new(buf: &'a mut Vec<T>) -> VecStack<'a, T> {
667            VecStack { buf, i: 0 }
668        }
669
670        /// Adds a new element to the psuedo-vector at the top of the stack.
671        pub fn push(&mut self, t: T) {
672            self.buf.push(t)
673        }
674
675        /// Sorts the psuedo-vector at the top of the stack by the key
676        /// identified by `f`.
677        pub fn sort_by_key<F, K>(&mut self, f: F)
678        where
679            F: FnMut(&T) -> K,
680            K: Ord,
681        {
682            self.buf[self.i..].sort_by_key(f)
683        }
684
685        /// Returns the length of the psuedo-vector at the top of the stack.
686        pub fn len(&self) -> usize {
687            self.buf.len() - self.i
688        }
689
690        /// Push a fresh vector onto the stack.
691        ///
692        /// The returned `VecStack` is a handle to this vector. The
693        /// psuedo-vector beneath the new vector is inaccessible until the new
694        /// handle is dropped.
695        pub fn fresh<'b>(&'b mut self) -> VecStack<'b, T> {
696            let i = self.buf.len();
697            VecStack { buf: self.buf, i }
698        }
699    }
700
701    impl<'a, T> Index<usize> for VecStack<'a, T> {
702        type Output = T;
703
704        fn index(&self, i: usize) -> &Self::Output {
705            &self.buf[self.i + i]
706        }
707    }
708
709    impl<'a, T> Drop for VecStack<'a, T> {
710        fn drop(&mut self) {
711            self.buf.truncate(self.i)
712        }
713    }
714}