summaryrefslogtreecommitdiff
path: root/reencode_write.go
blob: dffbb21ac6fbaeca3186245599e6e74ef13cdb36 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Copyright (C) 2022-2023  Luke Shumaker <lukeshu@lukeshu.com>
//
// 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
	}
}