From d19e2c6884c2d409fcc828c870f1839ee84f38cb Mon Sep 17 00:00:00 2001 From: Luke Shumaker Date: Tue, 14 Feb 2023 11:44:36 -0700 Subject: reencode: Factor into separate modules --- reencode_write.go | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 reencode_write.go (limited to 'reencode_write.go') diff --git a/reencode_write.go b/reencode_write.go new file mode 100644 index 0000000..dffbb21 --- /dev/null +++ b/reencode_write.go @@ -0,0 +1,52 @@ +// Copyright (C) 2022-2023 Luke Shumaker +// +// SPDX-License-Identifier: GPL-2.0-or-later + +package lowmemjson + +import ( + "git.lukeshu.com/go/lowmemjson/internal/fastio" + "git.lukeshu.com/go/lowmemjson/internal/jsonparse" + "git.lukeshu.com/go/lowmemjson/internal/jsonstring" +) + +type reEncodeWrite struct { + out fastio.AllWriter + + // state + last jsonparse.RuneType + lastNonEOF jsonparse.RuneType + wasNumber bool +} + +var _ reEncoderModule = (*reEncodeWrite)(nil) + +func (enc *reEncodeWrite) PopWriteBarrier() { + enc.last = enc.lastNonEOF +} + +func (enc *reEncodeWrite) HandleRune(c rune, t jsonparse.RuneType, escape BackslashEscapeMode, _ int) error { + // emit newlines between top-level values, if nescessary + if enc.last == jsonparse.RuneTypeEOF && enc.wasNumber && t.IsNumber() { + if _, err := enc.out.WriteRune('\n'); err != nil { + return err + } + } + if t == jsonparse.RuneTypeEOF { + enc.wasNumber = enc.last.IsNumber() + } else { + enc.lastNonEOF = t + } + enc.last = t + + // emit the rune + switch t { + case jsonparse.RuneTypeEOF: + return nil + case jsonparse.RuneTypeStringChar: + return jsonstring.WriteStringChar(enc.out, c, escape) + default: + _, err := enc.out.WriteRune(c) + return err + } +} -- cgit v1.2.3-2-g168b