1 // Copyright 2019 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 use super::{Builder, MapBuilder, Pushable};
16 
17 /// Builds a Flexbuffer vector, returned by a [Builder](struct.Builder.html).
18 ///
19 /// ## Side effect when dropped:
20 /// When this is dropped, or `end_vector` is called, the vector is
21 /// commited to the buffer. If this vector is the root of the flexbuffer, then the
22 /// root is written and the flexbuffer is complete. The FlexBufferType of this vector
23 /// is determined by the pushed values when this is dropped. The most compact vector type is
24 /// automatically chosen.
25 pub struct VectorBuilder<'a> {
26     pub(crate) builder: &'a mut Builder,
27     // If the root is this vector then start == None. Otherwise start is the
28     // number of values in the 'values stack' before adding this vector.
29     pub(crate) start: Option<usize>,
30 }
31 impl<'a> VectorBuilder<'a> {
32     /// Pushes `p` onto the vector.
33     #[inline]
push<P: Pushable>(&mut self, p: P)34     pub fn push<P: Pushable>(&mut self, p: P) {
35         self.builder.push(p);
36     }
37     /// Starts a nested vector that will be pushed onto this vector when it is dropped.
38     #[inline]
start_vector(&mut self) -> VectorBuilder39     pub fn start_vector(&mut self) -> VectorBuilder {
40         let start = Some(self.builder.values.len());
41         VectorBuilder {
42             builder: &mut self.builder,
43             start,
44         }
45     }
46     /// Starts a nested map that will be pushed onto this vector when it is dropped.
47     #[inline]
start_map(&mut self) -> MapBuilder48     pub fn start_map(&mut self) -> MapBuilder {
49         let start = Some(self.builder.values.len());
50         MapBuilder {
51             builder: &mut self.builder,
52             start,
53         }
54     }
55     /// `end_vector` determines the type of the vector and writes it to the buffer.
56     /// This will happen automatically if the VectorBuilder is dropped.
57     #[inline]
end_vector(self)58     pub fn end_vector(self) {}
59 }
60 impl<'a> Drop for VectorBuilder<'a> {
61     #[inline]
drop(&mut self)62     fn drop(&mut self) {
63         self.builder.end_map_or_vector(false, self.start);
64     }
65 }
66