Skip to content

Instantly share code, notes, and snippets.

@agocke
Last active May 8, 2023 17:06
Show Gist options
  • Save agocke/fac182279eb8f84a7fb77e204499e9bb to your computer and use it in GitHub Desktop.
Save agocke/fac182279eb8f84a7fb77e204499e9bb to your computer and use it in GitHub Desktop.
public ref struct JsonSerializer
{
private Span<byte> _buffer;
private int _loc; // increments as we write
...
public void WriteToBuffer(string s) => ...; // moves _loc
public Seq SerializeEnumerable(int? count) => new Seq(ref this);
public ref struct Seq
{
private ref JsonSerializer _serializer; // must be ref to preserve mutations
private bool _start = true;
public Seq(ref JsonSerializer serializer)
{
_serializer = serializer;
serializer.WriteToBuffer("{");
}
public void WriteItem<T>(T item)
{
if (!_start) _serializer.WriteToBuffer(",");
_serializer.WriteToBuffer(item.ToString());
_start = false;
}
public void End() => _serializer.WriteToBuffer("}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment