Serializer: implement Root
// Copyright 2025 Google LLC
// SPDX-License-Identifier: Apache-2.0
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
Serializercan only be finalized into aStringfrom this root level.