blob: b129da1260e45b30eb4fec0812f0cc6c943f09d3 [file] [log] [blame]
James Kuszmaul8e62b022022-03-22 09:33:25 -07001// Copyright 2021 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
15use crate::reader::Reader;
16use crate::Buffer;
17use crate::{BitWidth::*, FlexBufferType::*};
18use serde::ser;
19use serde::ser::{SerializeMap, SerializeSeq};
20
21impl<B: Buffer> ser::Serialize for &Reader<B> {
22 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
23 where
24 S: ser::Serializer,
25 {
26 #[allow(deprecated)]
27 match (self.flexbuffer_type(), self.bitwidth()) {
28 (Null, _) => serializer.serialize_unit(),
29 (Int, W8) | (IndirectInt, W8) => serializer.serialize_i8(self.as_i8()),
30 (Int, W16) | (IndirectInt, W16) => serializer.serialize_i16(self.as_i16()),
31 (Int, W32) | (IndirectInt, W32) => serializer.serialize_i32(self.as_i32()),
32 (Int, W64) | (IndirectInt, W64) => serializer.serialize_i64(self.as_i64()),
33 (UInt, W8) | (IndirectUInt, W8) => serializer.serialize_u8(self.as_u8()),
34 (UInt, W16) | (IndirectUInt, W16) => serializer.serialize_u16(self.as_u16()),
35 (UInt, W32) | (IndirectUInt, W32) => serializer.serialize_u32(self.as_u32()),
36 (UInt, W64) | (IndirectUInt, W64) => serializer.serialize_u64(self.as_u64()),
37 (Float, W32) | (IndirectFloat, W32) => serializer.serialize_f32(self.as_f32()),
38 (Float, _) | (IndirectFloat, _) => serializer.serialize_f64(self.as_f64()),
39 (Bool, _) => serializer.serialize_bool(self.as_bool()),
40 (Key, _) | (String, _) => serializer.serialize_str(&self.as_str()),
41 (Map, _) => {
42 let m = self.as_map();
43 let mut map_serializer = serializer.serialize_map(Some(m.len()))?;
44 for (k, v) in m.iter_keys().zip(m.iter_values()) {
45 map_serializer.serialize_key(&&k)?;
46 map_serializer.serialize_value(&&v)?;
47 }
48 map_serializer.end()
49 }
50 (Vector, _)
51 | (VectorInt, _)
52 | (VectorUInt, _)
53 | (VectorFloat, _)
54 | (VectorKey, _)
55 | (VectorString, _)
56 | (VectorBool, _)
57 | (VectorInt2, _)
58 | (VectorUInt2, _)
59 | (VectorFloat2, _)
60 | (VectorInt3, _)
61 | (VectorUInt3, _)
62 | (VectorFloat3, _)
63 | (VectorInt4, _)
64 | (VectorUInt4, _)
65 | (VectorFloat4, _) => {
66 let v = self.as_vector();
67 let mut seq_serializer = serializer.serialize_seq(Some(v.len()))?;
68 for x in v.iter() {
69 seq_serializer.serialize_element(&&x)?;
70 }
71 seq_serializer.end()
72 }
73 (Blob, _) => serializer.serialize_bytes(&self.as_blob().0),
74 }
75 }
76}