Implement Serialize on generated rust types (#7022)

* fix for rust build

* Rust: Implement Serialize on generated types

For debugging convenience it is really handy to be able to dump out
types as another format (ie: json). For example, if we are logging a
type to a structured logging system, or even printing it out in a
structured way to the console.

Right now we handle this by shelling out to `flatc` which is not ideal;
by implementing Serialize on the generated types we can use any of the
Serializer-implementing packages for our structured debug output.

* clang-format

* Make the flatbuffers Rust crate only have an optional dependency on the `serde` packages.

* fix warning

* fix rust test build

* Oh yeah this needs to be initialized

* fix toml syntax

* code review feedback

* rebuild test data
This commit is contained in:
Max Burke
2022-01-30 16:29:18 -08:00
committed by GitHub
parent dd8fccfb1b
commit 1d294a31b8
67 changed files with 5455 additions and 1 deletions

View File

@@ -14,10 +14,12 @@ rust = "1.51"
[features]
default = ["thiserror"]
no_std = ["core2", "thiserror_core2"]
serialize = ["serde"]
[dependencies]
smallvec = "1.6.1"
bitflags = "1.2.1"
serde = { version = "1.0", optional = true }
thiserror = { version = "1.0.23", optional = true }
core2 = { version = "0.3.3", optional = true }
thiserror_core2 = { git = "https://github.com/antmicro/thiserror-core2.git", branch = "remaining-errors", optional = true }

View File

@@ -133,3 +133,22 @@ where
array.assume_init()
}
}
#[cfg(feature="serialize")]
impl<'a, T: 'a, const N: usize> serde::ser::Serialize for Array<'a, T, N>
where
T: 'a + Follow<'a>,
<T as Follow<'a>>::Inner: serde::ser::Serialize,
{
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: serde::ser::Serializer,
{
use serde::ser::SerializeSeq;
let mut seq = serializer.serialize_seq(Some(self.len()))?;
for element in self.iter() {
seq.serialize_element(&element)?;
}
seq.end()
}
}

View File

@@ -308,3 +308,22 @@ impl<'a, 'b, T: Follow<'a> + 'a> IntoIterator for &'b Vector<'a, T> {
self.iter()
}
}
#[cfg(feature="serialize")]
impl<'a, T> serde::ser::Serialize for Vector<'a, T>
where
T: 'a + Follow<'a>,
<T as Follow<'a>>::Inner: serde::ser::Serialize,
{
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: serde::ser::Serializer,
{
use serde::ser::SerializeSeq;
let mut seq = serializer.serialize_seq(Some(self.len()))?;
for element in self {
seq.serialize_element(&element)?;
}
seq.end()
}
}