Serializer: implement Struct

#![allow(unused)]
fn main() {
use std::fmt::Write as _;
struct Serializer<S> {
    // [...]
    indent: usize,
    buffer: String,
    state: S,
}

struct Struct<S>(S);
struct Property<S>(S);

impl<S> Serializer<Struct<S>> {
    fn serialize_property(mut self, name: &str) -> Serializer<Property<Struct<S>>> {
        // [...]
        write!(self.buffer, "{}{name}: ", " ".repeat(self.indent * 2)).unwrap();
        Serializer {
            indent: self.indent,
            buffer: self.buffer,
            state: Property(self.state),
        }
    }

    fn finish_struct(mut self) -> Serializer<S> {
        // [...]
        self.indent -= 1;
        writeln!(self.buffer, "{}}}", " ".repeat(self.indent * 2)).unwrap();
        Serializer { indent: self.indent, buffer: self.buffer, state: self.state.0 }
    }
}
}

The diagram can now be expanded as follows:

Serializer[Root]Serializer[Struct[S]]Serializer[Property[Struct[S]]]Stringfinishstructserializestructfinishstructserializepropertyfinish
  • A Struct can only contain a Property;

  • Finishing a Struct returns control back to its parent, which in our previous slide was assumed the Root, but in reality however it can be also something else such as Struct in case of nested “structs”.