git.lukeshu.com/go/lowmemjson@v0.3.9-0.20230723050957-72f6d13f6fb2/reencode_write.go (about) 1 // Copyright (C) 2022-2023 Luke Shumaker <lukeshu@lukeshu.com> 2 // 3 // SPDX-License-Identifier: GPL-2.0-or-later 4 5 package lowmemjson 6 7 import ( 8 "git.lukeshu.com/go/lowmemjson/internal/fastio" 9 "git.lukeshu.com/go/lowmemjson/internal/jsonparse" 10 "git.lukeshu.com/go/lowmemjson/internal/jsonstring" 11 ) 12 13 type reEncodeWrite struct { 14 out fastio.AllWriter 15 16 // state 17 last jsonparse.RuneType 18 lastNonEOF jsonparse.RuneType 19 wasNumber bool 20 } 21 22 var _ reEncoderModule = (*reEncodeWrite)(nil) 23 24 func (enc *reEncodeWrite) PopWriteBarrier() { 25 enc.last = enc.lastNonEOF 26 } 27 28 func (enc *reEncodeWrite) HandleRune(c rune, t jsonparse.RuneType, escape BackslashEscapeMode, _ int) error { 29 // emit newlines between top-level values, if nescessary 30 if enc.last == jsonparse.RuneTypeEOF && enc.wasNumber && t.IsNumber() { 31 if _, err := enc.out.WriteRune('\n'); err != nil { 32 return err 33 } 34 } 35 if t == jsonparse.RuneTypeEOF { 36 enc.wasNumber = enc.last.IsNumber() 37 } else { 38 enc.lastNonEOF = t 39 } 40 enc.last = t 41 42 // emit the rune 43 switch t { 44 case jsonparse.RuneTypeEOF: 45 return nil 46 case jsonparse.RuneTypeStringChar: 47 return jsonstring.WriteStringChar(enc.out, c, escape) 48 default: 49 _, err := enc.out.WriteRune(c) 50 return err 51 } 52 }