Serializer: implement Root
#![allow(unused)] fn main() { use std::fmt::Write as _; struct Serializer<S> { // [...] indent: usize, buffer: String, state: S, } struct Root; struct Struct<S>(S); impl Serializer<Root> { fn new() -> Self { // [...] Self { indent: 0, buffer: String::new(), state: Root } } fn serialize_struct(mut self, name: &str) -> Serializer<Struct<Root>> { // [...] writeln!(self.buffer, "{name} {{").unwrap(); Serializer { indent: self.indent + 1, buffer: self.buffer, state: Struct(self.state), } } fn finish(self) -> String { // [...] self.buffer } } }
Referring back to our original diagram of valid transitions, we can visualize the beginning of our implementation as follows:
-
At the “root” of our
Serializer
, the only construct allowed is aStruct
. -
The
Serializer
can only be finalized into aString
from this root level.