Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Playground

buffer.gno

package json

import (
	"errors"
	"io"

	"gno.land/p/nt/ufmt/v0"
)

type buffer struct {
	data   []byte
	length int
	index  int

	last  States
	state States
	class Classes
}

// newBuffer creates a new buffer with the given data
func newBuffer(data []byte) *buffer {
	return &buffer{
		data:   data,
		length: len(data),
		last:   GO,
		state:  GO,
	}
}

// first retrieves the first non-whitespace (or other escaped) character in the buffer.
func (b *buffer) first() (byte, error) {
	for ; b.index < b.length; b.index++ {
		c := b.data[b.index]

		if !(c == whiteSpace || c == carriageReturn || c == newLine || c == tab) {
			return c, nil
		}
	}

	return 0, io.EOF
}

// current returns the byte of the current index.
func (b *buffer) current() (byte, error) {
	if b.index >= b.length {
		return 0, io.EOF
	}

	return b.data[b.index], nil
}

// next moves to the next byte and returns it.
func (b *buffer) next() (byte, error) {
	b.index++
	return b.current()
}

// step just moves to the next position.
func (b *buffer) step() error {
	_, err := b.next()
	return err
}

// move moves the index by the given position.
func (b *buffer) move(pos int) error {
	newIndex := b.index + pos

	if newIndex > b.length {
		return io.EOF
	}

	b.index = newIndex

	return nil
}

// slice returns the slice from the current index to the given position.
func (b *buffer) slice(pos int) ([]byte, error) {
	end := b.index + pos

	if end > b.length {
		return nil, io.EOF
	}

	return b.data[b.index:end], nil
}

// sliceFromIndices returns a slice of the buffer's data starting from 'start' up to (but not including) 'stop'.
func (b *buffer) sliceFromIndices(start, stop int) []byte {
	if start > b.length {
		start = b.length
	}

	if stop > b.length {
		stop = b.length
	}

	return b.data[start:stop]
}

// skip moves the index to skip the given byte.
func (b *buffer) skip(bs byte) error {
	for b.index < b.length {
		if b.data[b.index] == bs && !b.backslash() {
			return nil
		}

		b.index++
	}

	return io.EOF
}

// skipAndReturnIndex moves the buffer index forward by one and returns the new index.
func (b *buffer) skipAndReturnIndex() (int, error) {
	err := b.step()
	if err != nil {
		return 0, err
	}

	return b.index, nil
}

// skipUntil moves the buffer index forward until it encounters a byte contained in the endTokens set.
func (b *buffer) skipUntil(endTokens map[byte]bool) (int, error) {
	for b.index < b.length {
		currentByte, err := b.current()
		if err != nil {
			return b.index, err
		}

		// Check if the current byte is in the set of end tokens.
		if _, exists := endTokens[currentByte]; exists {
			return b.index, nil
		}

		b.index++
	}

	return b.index, io.EOF
}

// significantTokens is a map where the keys are the significant characters in a JSON path.
// The values in the map are all true, which allows us to use the map as a set for quick lookups.
var significantTokens = [256]bool{
	dot:          true, // access properties of an object
	dollarSign:   true, // root object
	atSign:       true, // current object
	bracketOpen:  true, // start of an array index or filter expression
	bracketClose: true, // end of an array index or filter expression
}

// filterTokens stores the filter expression tokens.
var filterTokens = [256]bool{
	aesterisk: true, // wildcard
	andSign:   true,
	orSign:    true,
}

// skipToNextSignificantToken advances the buffer index to the next significant character.
// Significant characters are defined based on the JSON path syntax.
func (b *buffer) skipToNextSignificantToken() {
	for b.index < b.length {
		current := b.data[b.index]

		if significantTokens[current] {
			break
		}

		b.index++
	}
}

// backslash checks to see if the number of backslashes before the current index is odd.
//
// This is used to check if the current character is escaped. However, unlike the "unescape" function,
// "backslash" only serves to check the number of backslashes.
func (b *buffer) backslash() bool {
	if b.index == 0 {
		return false
	}

	count := 0
	for i := b.index - 1; ; i-- {
		if b.data[i] != backSlash {
			break
		}

		count++

		if i == 0 {
			break
		}
	}

	return count%2 != 0
}

// numIndex holds a map of valid numeric characters
var numIndex = [256]bool{
	'0': true,
	'1': true,
	'2': true,
	'3': true,
	'4': true,
	'5': true,
	'6': true,
	'7': true,
	'8': true,
	'9': true,
	'.': true,
	'e': true,
	'E': true,
}

// pathToken checks if the current token is a valid JSON path token.
func (b *buffer) pathToken() error {
	var stack []byte

	inToken := false
	inNumber := false
	first := b.index

	for b.index < b.length {
		c := b.data[b.index]

		switch {
		case c == doubleQuote || c == singleQuote:
			inToken = true
			if err := b.step(); err != nil {
				return errors.New("error stepping through buffer")
			}

			if err := b.skip(c); err != nil {
				return errUnmatchedQuotePath
			}

			if b.index >= b.length {
				return errUnmatchedQuotePath
			}

		case c == bracketOpen || c == parenOpen:
			inToken = true
			stack = append(stack, c)

		case c == bracketClose || c == parenClose:
			inToken = true
			if len(stack) == 0 || (c == bracketClose && stack[len(stack)-1] != bracketOpen) || (c == parenClose && stack[len(stack)-1] != parenOpen) {
				return errUnmatchedParenthesis
			}

			stack = stack[:len(stack)-1]

		case pathStateContainsValidPathToken(c):
			inToken = true

		case c == plus || c == minus:
			if inNumber || (b.index > 0 && numIndex[b.data[b.index-1]]) {
				inToken = true
			} else if !inToken && (b.index+1 < b.length && numIndex[b.data[b.index+1]]) {
				inToken = true
				inNumber = true
			} else if !inToken {
				return errInvalidToken
			}

		default:
			if len(stack) != 0 || inToken {
				inToken = true
			} else {
				goto end
			}
		}

		b.index++
	}

end:
	if len(stack) != 0 {
		return errUnmatchedParenthesis
	}

	if first == b.index {
		return errors.New("no token found")
	}

	if inNumber && !numIndex[b.data[b.index-1]] {
		inNumber = false
	}

	return nil
}

func pathStateContainsValidPathToken(c byte) bool {
	if significantTokens[c] {
		return true
	}

	if filterTokens[c] {
		return true
	}

	if numIndex[c] {
		return true
	}

	if 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' {
		return true
	}

	return false
}

func (b *buffer) numeric(token bool) error {
	if token {
		b.last = GO
	}

	for ; b.index < b.length; b.index++ {
		b.class = b.getClasses(doubleQuote)
		if b.class == __ {
			return errInvalidToken
		}

		b.state = StateTransitionTable[b.last][b.class]
		if b.state == __ {
			if token {
				break
			}

			return errInvalidToken
		}

		if b.state < __ {
			return nil
		}

		if b.state < MI || b.state > E3 {
			return nil
		}

		b.last = b.state
	}

	if b.last != ZE && b.last != IN && b.last != FR && b.last != E3 {
		return errInvalidToken
	}

	return nil
}

func (b *buffer) getClasses(c byte) Classes {
	if b.data[b.index] >= 128 {
		return C_ETC
	}

	if c == singleQuote {
		return QuoteAsciiClasses[b.data[b.index]]
	}

	return AsciiClasses[b.data[b.index]]
}

func (b *buffer) getState() States {
	b.last = b.state

	b.class = b.getClasses(doubleQuote)
	if b.class == __ {
		return __
	}

	b.state = StateTransitionTable[b.last][b.class]

	return b.state
}

// string parses a string token from the buffer.
func (b *buffer) string(search byte, token bool) error {
	if token {
		b.last = GO
	}

	for ; b.index < b.length; b.index++ {
		b.class = b.getClasses(search)

		if b.class == __ {
			return errInvalidToken
		}

		b.state = StateTransitionTable[b.last][b.class]
		if b.state == __ {
			return errInvalidToken
		}

		if b.state < __ {
			break
		}

		b.last = b.state
	}

	return nil
}

func (b *buffer) word(bs []byte) error {
	var c byte

	max := len(bs)
	index := 0

	for ; b.index < b.length && index < max; b.index++ {
		c = b.data[b.index]

		if c != bs[index] {
			return errInvalidToken
		}

		index++
		if index >= max {
			break
		}
	}

	if index != max {
		return errInvalidToken
	}

	return nil
}

func numberKind2f64(value any) (result float64, err error) {
	switch typed := value.(type) {
	case float64:
		result = typed
	case float32:
		result = float64(typed)
	case int:
		result = float64(typed)
	case int8:
		result = float64(typed)
	case int16:
		result = float64(typed)
	case int32:
		result = float64(typed)
	case int64:
		result = float64(typed)
	case uint:
		result = float64(typed)
	case uint8:
		result = float64(typed)
	case uint16:
		result = float64(typed)
	case uint32:
		result = float64(typed)
	case uint64:
		result = float64(typed)
	default:
		err = ufmt.Errorf("invalid number type: %T", value)
	}

	return
}

buffer_test.gno

package json

import (
	"testing"
)

func TestBufferCurrent(t *testing.T) {
	tests := []struct {
		name     string
		buffer   *buffer
		expected byte
		wantErr  bool
	}{
		{
			name: "Valid current byte",
			buffer: &buffer{
				data:   []byte("test"),
				length: 4,
				index:  1,
			},
			expected: 'e',
			wantErr:  false,
		},
		{
			name: "EOF",
			buffer: &buffer{
				data:   []byte("test"),
				length: 4,
				index:  4,
			},
			expected: 0,
			wantErr:  true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := tt.buffer.current()
			if (err != nil) != tt.wantErr {
				t.Errorf("buffer.current() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if got != tt.expected {
				t.Errorf("buffer.current() = %v, want %v", got, tt.expected)
			}
		})
	}
}

func TestBufferStep(t *testing.T) {
	tests := []struct {
		name    string
		buffer  *buffer
		wantErr bool
	}{
		{
			name:    "Valid step",
			buffer:  &buffer{data: []byte("test"), length: 4, index: 0},
			wantErr: false,
		},
		{
			name:    "EOF error",
			buffer:  &buffer{data: []byte("test"), length: 4, index: 3},
			wantErr: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			err := tt.buffer.step()
			if (err != nil) != tt.wantErr {
				t.Errorf("buffer.step() error = %v, wantErr %v", err, tt.wantErr)
			}
		})
	}
}

func TestBufferNext(t *testing.T) {
	tests := []struct {
		name    string
		buffer  *buffer
		want    byte
		wantErr bool
	}{
		{
			name:    "Valid next byte",
			buffer:  &buffer{data: []byte("test"), length: 4, index: 0},
			want:    'e',
			wantErr: false,
		},
		{
			name:    "EOF error",
			buffer:  &buffer{data: []byte("test"), length: 4, index: 3},
			want:    0,
			wantErr: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := tt.buffer.next()
			if (err != nil) != tt.wantErr {
				t.Errorf("buffer.next() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if got != tt.want {
				t.Errorf("buffer.next() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestBufferSlice(t *testing.T) {
	tests := []struct {
		name    string
		buffer  *buffer
		pos     int
		want    []byte
		wantErr bool
	}{
		{
			name:    "Valid slice -- 0 characters",
			buffer:  &buffer{data: []byte("test"), length: 4, index: 0},
			pos:     0,
			want:    nil,
			wantErr: false,
		},
		{
			name:    "Valid slice -- 1 character",
			buffer:  &buffer{data: []byte("test"), length: 4, index: 0},
			pos:     1,
			want:    []byte("t"),
			wantErr: false,
		},
		{
			name:    "Valid slice -- 2 characters",
			buffer:  &buffer{data: []byte("test"), length: 4, index: 1},
			pos:     2,
			want:    []byte("es"),
			wantErr: false,
		},
		{
			name:    "Valid slice -- 3 characters",
			buffer:  &buffer{data: []byte("test"), length: 4, index: 0},
			pos:     3,
			want:    []byte("tes"),
			wantErr: false,
		},
		{
			name:    "Valid slice -- 4 characters",
			buffer:  &buffer{data: []byte("test"), length: 4, index: 0},
			pos:     4,
			want:    []byte("test"),
			wantErr: false,
		},
		{
			name:    "EOF error",
			buffer:  &buffer{data: []byte("test"), length: 4, index: 3},
			pos:     2,
			want:    nil,
			wantErr: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := tt.buffer.slice(tt.pos)
			if (err != nil) != tt.wantErr {
				t.Errorf("buffer.slice() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if string(got) != string(tt.want) {
				t.Errorf("buffer.slice() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestBufferMove(t *testing.T) {
	tests := []struct {
		name    string
		buffer  *buffer
		pos     int
		wantErr bool
		wantIdx int
	}{
		{
			name:    "Valid move",
			buffer:  &buffer{data: []byte("test"), length: 4, index: 1},
			pos:     2,
			wantErr: false,
			wantIdx: 3,
		},
		{
			name:    "Move beyond length",
			buffer:  &buffer{data: []byte("test"), length: 4, index: 1},
			pos:     4,
			wantErr: true,
			wantIdx: 1,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			err := tt.buffer.move(tt.pos)
			if (err != nil) != tt.wantErr {
				t.Errorf("buffer.move() error = %v, wantErr %v", err, tt.wantErr)
			}
			if tt.buffer.index != tt.wantIdx {
				t.Errorf("buffer.move() index = %v, want %v", tt.buffer.index, tt.wantIdx)
			}
		})
	}
}

func TestBufferSkip(t *testing.T) {
	tests := []struct {
		name    string
		buffer  *buffer
		b       byte
		wantErr bool
	}{
		{
			name:    "Skip byte",
			buffer:  &buffer{data: []byte("test"), length: 4, index: 0},
			b:       'e',
			wantErr: false,
		},
		{
			name:    "Skip to EOF",
			buffer:  &buffer{data: []byte("test"), length: 4, index: 0},
			b:       'x',
			wantErr: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			err := tt.buffer.skip(tt.b)
			if (err != nil) != tt.wantErr {
				t.Errorf("buffer.skip() error = %v, wantErr %v", err, tt.wantErr)
			}
		})
	}
}

func TestSkipToNextSignificantToken(t *testing.T) {
	tests := []struct {
		name     string
		input    []byte
		expected int
	}{
		{"No significant chars", []byte("abc"), 3},
		{"One significant char at start", []byte(".abc"), 0},
		{"Significant char in middle", []byte("ab.c"), 2},
		{"Multiple significant chars", []byte("a$.c"), 1},
		{"Significant char at end", []byte("abc$"), 3},
		{"Only significant chars", []byte("$."), 0},
		{"Empty string", []byte(""), 0},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			b := newBuffer(tt.input)
			b.skipToNextSignificantToken()
			if b.index != tt.expected {
				t.Errorf("after skipToNextSignificantToken(), got index = %v, want %v", b.index, tt.expected)
			}
		})
	}
}

func mockBuffer(s string) *buffer {
	return newBuffer([]byte(s))
}

func TestSkipAndReturnIndex(t *testing.T) {
	tests := []struct {
		name     string
		input    string
		expected int
	}{
		{"StartOfString", "", 0},
		{"MiddleOfString", "abcdef", 1},
		{"EndOfString", "abc", 1},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			buf := mockBuffer(tt.input)
			got, err := buf.skipAndReturnIndex()
			if err != nil && tt.input != "" { // Expect no error unless input is empty
				t.Errorf("skipAndReturnIndex() error = %v", err)
			}
			if got != tt.expected {
				t.Errorf("skipAndReturnIndex() = %v, want %v", got, tt.expected)
			}
		})
	}
}

func TestSkipUntil(t *testing.T) {
	tests := []struct {
		name     string
		input    string
		tokens   map[byte]bool
		expected int
	}{
		{"SkipToToken", "abcdefg", map[byte]bool{'c': true}, 2},
		{"SkipToEnd", "abcdefg", map[byte]bool{'h': true}, 7},
		{"SkipNone", "abcdefg", map[byte]bool{'a': true}, 0},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			buf := mockBuffer(tt.input)
			got, err := buf.skipUntil(tt.tokens)
			if err != nil && got != len(tt.input) { // Expect error only if reached end without finding token
				t.Errorf("skipUntil() error = %v", err)
			}
			if got != tt.expected {
				t.Errorf("skipUntil() = %v, want %v", got, tt.expected)
			}
		})
	}
}

func TestSliceFromIndices(t *testing.T) {
	tests := []struct {
		name     string
		input    string
		start    int
		end      int
		expected string
	}{
		{"FullString", "abcdefg", 0, 7, "abcdefg"},
		{"Substring", "abcdefg", 2, 5, "cde"},
		{"OutOfBounds", "abcdefg", 5, 10, "fg"},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			buf := mockBuffer(tt.input)
			got := buf.sliceFromIndices(tt.start, tt.end)
			if string(got) != tt.expected {
				t.Errorf("sliceFromIndices() = %v, want %v", string(got), tt.expected)
			}
		})
	}
}

func TestBufferToken(t *testing.T) {
	tests := []struct {
		name  string
		path  string
		index int
		isErr bool
	}{
		{
			name:  "Simple valid path",
			path:  "@.length",
			index: 8,
			isErr: false,
		},
		{
			name:  "Path with array expr",
			path:  "@['foo'].0.bar",
			index: 14,
			isErr: false,
		},
		{
			name:  "Path with array expr and simple fomula",
			path:  "@['foo'].[(@.length - 1)].*",
			index: 27,
			isErr: false,
		},
		{
			name:  "Path with filter expr",
			path:  "@['foo'].[?(@.bar == 1 & @.baz < @.length)].*",
			index: 45,
			isErr: false,
		},
		{
			name:  "addition of foo and bar",
			path:  "@.foo+@.bar",
			index: 11,
			isErr: false,
		},
		{
			name:  "logical AND of foo and bar",
			path:  "@.foo && @.bar",
			index: 14,
			isErr: false,
		},
		{
			name:  "logical OR of foo and bar",
			path:  "@.foo || @.bar",
			index: 14,
			isErr: false,
		},
		{
			name:  "accessing third element of foo",
			path:  "@.foo,3",
			index: 7,
			isErr: false,
		},
		{
			name:  "accessing last element of array",
			path:  "@.length-1",
			index: 10,
			isErr: false,
		},
		{
			name:  "number 1",
			path:  "1",
			index: 1,
			isErr: false,
		},
		{
			name:  "float",
			path:  "3.1e4",
			index: 5,
			isErr: false,
		},
		{
			name:  "float with minus",
			path:  "3.1e-4",
			index: 6,
			isErr: false,
		},
		{
			name:  "float with plus",
			path:  "3.1e+4",
			index: 6,
			isErr: false,
		},
		{
			name:  "negative number",
			path:  "-12345",
			index: 6,
			isErr: false,
		},
		{
			name:  "negative float",
			path:  "-3.1e4",
			index: 6,
			isErr: false,
		},
		{
			name:  "negative float with minus",
			path:  "-3.1e-4",
			index: 7,
			isErr: false,
		},
		{
			name:  "negative float with plus",
			path:  "-3.1e+4",
			index: 7,
			isErr: false,
		},
		{
			name:  "string number",
			path:  "'12345'",
			index: 7,
			isErr: false,
		},
		{
			name:  "string with backslash",
			path:  "'foo \\'bar '",
			index: 12,
			isErr: false,
		},
		{
			name:  "string with inner double quotes",
			path:  "'foo \"bar \"'",
			index: 12,
			isErr: false,
		},
		{
			name:  "parenthesis 1",
			path:  "(@abc)",
			index: 6,
			isErr: false,
		},
		{
			name:  "parenthesis 2",
			path:  "[()]",
			index: 4,
			isErr: false,
		},
		{
			name:  "parenthesis mismatch",
			path:  "[(])",
			index: 2,
			isErr: true,
		},
		{
			name:  "parenthesis mismatch 2",
			path:  "(",
			index: 1,
			isErr: true,
		},
		{
			name:  "parenthesis mismatch 3",
			path:  "())]",
			index: 2,
			isErr: true,
		},
		{
			name:  "bracket mismatch",
			path:  "[()",
			index: 3,
			isErr: true,
		},
		{
			name:  "bracket mismatch 2",
			path:  "()]",
			index: 2,
			isErr: true,
		},
		{
			name:  "path does not close bracket",
			path:  "@.foo[)",
			index: 6,
			isErr: false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			buf := newBuffer([]byte(tt.path))

			err := buf.pathToken()
			if tt.isErr {
				if err == nil {
					t.Errorf("Expected an error for path `%s`, but got none", tt.path)
				}
			}

			if err == nil && tt.isErr {
				t.Errorf("Expected an error for path `%s`, but got none", tt.path)
			}

			if buf.index != tt.index {
				t.Errorf("Expected final index %d, got %d (token: `%s`) for path `%s`", tt.index, buf.index, string(buf.data[buf.index]), tt.path)
			}
		})
	}
}

func TestBufferFirst(t *testing.T) {
	tests := []struct {
		name     string
		data     []byte
		expected byte
	}{
		{
			name:     "Valid first byte",
			data:     []byte("test"),
			expected: 't',
		},
		{
			name:     "Empty buffer",
			data:     []byte(""),
			expected: 0,
		},
		{
			name:     "Whitespace buffer",
			data:     []byte("   "),
			expected: 0,
		},
		{
			name:     "whitespace in middle",
			data:     []byte("hello world"),
			expected: 'h',
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			b := newBuffer(tt.data)

			got, err := b.first()
			if err != nil && tt.expected != 0 {
				t.Errorf("Unexpected error: %v", err)
			}

			if got != tt.expected {
				t.Errorf("Expected first byte to be %q, got %q", tt.expected, got)
			}
		})
	}
}

builder.gno

package json

type NodeBuilder struct {
	node *Node
}

func Builder() *NodeBuilder {
	return &NodeBuilder{node: ObjectNode("", nil)}
}

func (b *NodeBuilder) WriteString(key, value string) *NodeBuilder {
	b.node.AppendObject(key, StringNode("", value))
	return b
}

func (b *NodeBuilder) WriteNumber(key string, value float64) *NodeBuilder {
	b.node.AppendObject(key, NumberNode("", value))
	return b
}

func (b *NodeBuilder) WriteBool(key string, value bool) *NodeBuilder {
	b.node.AppendObject(key, BoolNode("", value))
	return b
}

func (b *NodeBuilder) WriteNull(key string) *NodeBuilder {
	b.node.AppendObject(key, NullNode(""))
	return b
}

func (b *NodeBuilder) WriteObject(key string, fn func(*NodeBuilder)) *NodeBuilder {
	nestedBuilder := &NodeBuilder{node: ObjectNode("", nil)}
	fn(nestedBuilder)
	b.node.AppendObject(key, nestedBuilder.node)
	return b
}

func (b *NodeBuilder) WriteArray(key string, fn func(*ArrayBuilder)) *NodeBuilder {
	arrayBuilder := &ArrayBuilder{nodes: []*Node{}}
	fn(arrayBuilder)
	b.node.AppendObject(key, ArrayNode("", arrayBuilder.nodes))
	return b
}

func (b *NodeBuilder) Node() *Node {
	return b.node
}

type ArrayBuilder struct {
	nodes []*Node
}

func (ab *ArrayBuilder) WriteString(value string) *ArrayBuilder {
	ab.nodes = append(ab.nodes, StringNode("", value))
	return ab
}

func (ab *ArrayBuilder) WriteNumber(value float64) *ArrayBuilder {
	ab.nodes = append(ab.nodes, NumberNode("", value))
	return ab
}

func (ab *ArrayBuilder) WriteInt(value int) *ArrayBuilder {
	return ab.WriteNumber(float64(value))
}

func (ab *ArrayBuilder) WriteBool(value bool) *ArrayBuilder {
	ab.nodes = append(ab.nodes, BoolNode("", value))
	return ab
}

func (ab *ArrayBuilder) WriteNull() *ArrayBuilder {
	ab.nodes = append(ab.nodes, NullNode(""))
	return ab
}

func (ab *ArrayBuilder) WriteObject(fn func(*NodeBuilder)) *ArrayBuilder {
	nestedBuilder := &NodeBuilder{node: ObjectNode("", nil)}
	fn(nestedBuilder)
	ab.nodes = append(ab.nodes, nestedBuilder.node)
	return ab
}

func (ab *ArrayBuilder) WriteArray(fn func(*ArrayBuilder)) *ArrayBuilder {
	nestedArrayBuilder := &ArrayBuilder{nodes: []*Node{}}
	fn(nestedArrayBuilder)
	ab.nodes = append(ab.nodes, ArrayNode("", nestedArrayBuilder.nodes))
	return ab
}

builder_test.gno

package json

import (
	"testing"
)

func TestNodeBuilder(t *testing.T) {
	tests := []struct {
		name     string
		build    func() *Node
		expected string
	}{
		{
			name: "plain object",
			build: func() *Node {
				return Builder().
					WriteString("name", "Alice").
					WriteNumber("age", 30).
					WriteBool("is_student", false).
					Node()
			},
			expected: `{"name":"Alice","age":30,"is_student":false}`,
		},
		{
			name: "nested object",
			build: func() *Node {
				return Builder().
					WriteString("name", "Alice").
					WriteObject("address", func(b *NodeBuilder) {
						b.WriteString("city", "New York").
							WriteNumber("zipcode", 10001)
					}).
					Node()
			},
			expected: `{"name":"Alice","address":{"city":"New York","zipcode":10001}}`,
		},
		{
			name: "null node",
			build: func() *Node {
				return Builder().WriteNull("foo").Node()
			},
			expected: `{"foo":null}`,
		},
		{
			name: "array node",
			build: func() *Node {
				return Builder().
					WriteArray("items", func(ab *ArrayBuilder) {
						ab.WriteString("item1").
							WriteString("item2").
							WriteString("item3")
					}).
					Node()
			},
			expected: `{"items":["item1","item2","item3"]}`,
		},
		{
			name: "array with objects",
			build: func() *Node {
				return Builder().
					WriteArray("users", func(ab *ArrayBuilder) {
						ab.WriteObject(func(b *NodeBuilder) {
							b.WriteString("name", "Bob").
								WriteNumber("age", 25)
						}).
							WriteObject(func(b *NodeBuilder) {
								b.WriteString("name", "Carol").
									WriteNumber("age", 27)
							})
					}).
					Node()
			},
			expected: `{"users":[{"name":"Bob","age":25},{"name":"Carol","age":27}]}`,
		},
		{
			name: "array with various types",
			build: func() *Node {
				return Builder().
					WriteArray("values", func(ab *ArrayBuilder) {
						ab.WriteString("item1").
							WriteNumber(123).
							WriteBool(true).
							WriteNull()
					}).
					Node()
			},
			expected: `{"values":["item1",123,true,null]}`,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			node := tt.build()
			value, err := Marshal(node)
			if err != nil {
				t.Errorf("unexpected error: %s", err)
			}
			if string(value) != tt.expected {
				t.Errorf("expected %s, got %s", tt.expected, string(value))
			}
		})
	}
}

decode.gno

// ref: https://github.com/spyzhov/ajson/blob/master/decode.go

package json

import (
	"errors"
	"io"

	"gno.land/p/nt/ufmt/v0"
)

// This limits the max nesting depth to prevent stack overflow.
// This is permitted by https://tools.ietf.org/html/rfc7159#section-9
const maxNestingDepth = 10000

// Unmarshal parses the JSON-encoded data and returns a Node.
// The data must be a valid JSON-encoded value.
//
// Usage:
//
//	node, err := json.Unmarshal([]byte(`{"key": "value"}`))
//	if err != nil {
//		ufmt.Println(err)
//	}
//	println(node) // {"key": "value"}
func Unmarshal(data []byte) (*Node, error) {
	buf := newBuffer(data)

	var (
		state   States
		key     *string
		current *Node
		nesting int
		useKey  = func() **string {
			tmp := cptrs(key)
			key = nil
			return &tmp
		}
		err error
	)

	if _, err = buf.first(); err != nil {
		return nil, io.EOF
	}

	for {
		state = buf.getState()
		if state == __ {
			return nil, unexpectedTokenError(buf.data, buf.index)
		}

		// region state machine
		if state >= GO {
			switch buf.state {
			case ST: // string
				if current != nil && current.IsObject() && key == nil {
					// key detected
					if key, err = getString(buf); err != nil {
						return nil, err
					}

					buf.state = CO
				} else {
					current, nesting, err = createNestedNode(current, buf, String, nesting, useKey())
					if err != nil {
						return nil, err
					}

					err = buf.string(doubleQuote, false)
					if err != nil {
						return nil, err
					}

					current, nesting = updateNode(current, buf, nesting, true)
					buf.state = OK
				}

			case MI, ZE, IN: // number
				current, err = processNumericNode(current, buf, useKey())
				if err != nil {
					return nil, err
				}

			case T1, F1: // boolean
				literal := falseLiteral
				if buf.state == T1 {
					literal = trueLiteral
				}

				current, nesting, err = processLiteralNode(current, buf, Boolean, literal, useKey(), nesting)
				if err != nil {
					return nil, err
				}

			case N1: // null
				current, nesting, err = processLiteralNode(current, buf, Null, nullLiteral, useKey(), nesting)
				if err != nil {
					return nil, err
				}
			}
		} else {
			// region action
			switch state {
			case ec, cc: // <empty> }
				if key != nil {
					return nil, unexpectedTokenError(buf.data, buf.index)
				}

				current, nesting, err = updateNodeAndSetBufferState(current, buf, nesting, Object)
				if err != nil {
					return nil, err
				}

			case bc: // ]
				current, nesting, err = updateNodeAndSetBufferState(current, buf, nesting, Array)
				if err != nil {
					return nil, err
				}

			case co, bo: // { [
				valTyp, bState := Object, OB
				if state == bo {
					valTyp, bState = Array, AR
				}

				current, nesting, err = createNestedNode(current, buf, valTyp, nesting, useKey())
				if err != nil {
					return nil, err
				}

				buf.state = bState

			case cm: // ,
				if current == nil {
					return nil, unexpectedTokenError(buf.data, buf.index)
				}

				if !current.isContainer() {
					return nil, unexpectedTokenError(buf.data, buf.index)
				}

				if current.IsObject() {
					buf.state = KE // key expected
				} else {
					buf.state = VA // value expected
				}

			case cl: // :
				if current == nil || !current.IsObject() || key == nil {
					return nil, unexpectedTokenError(buf.data, buf.index)
				}

				buf.state = VA

			default:
				return nil, unexpectedTokenError(buf.data, buf.index)
			}
		}

		if buf.step() != nil {
			break
		}

		if _, err = buf.first(); err != nil {
			err = nil
			break
		}
	}

	if current == nil || buf.state != OK {
		return nil, io.EOF
	}

	root := current.root()
	if !root.ready() {
		return nil, io.EOF
	}

	return root, err
}

// UnmarshalSafe parses the JSON-encoded data and returns a Node.
func UnmarshalSafe(data []byte) (*Node, error) {
	var safe []byte
	safe = append(safe, data...)
	return Unmarshal(safe)
}

// processNumericNode creates a new node, processes a numeric value,
// sets the node's borders, and moves to the previous node.
func processNumericNode(current *Node, buf *buffer, key **string) (*Node, error) {
	var err error
	current, err = createNode(current, buf, Number, key)
	if err != nil {
		return nil, err
	}

	if err = buf.numeric(false); err != nil {
		return nil, err
	}

	current.borders[1] = buf.index
	if current.prev != nil {
		current = current.prev
	}

	buf.index -= 1
	buf.state = OK

	return current, nil
}

// processLiteralNode creates a new node, processes a literal value,
// sets the node's borders, and moves to the previous node.
func processLiteralNode(
	current *Node,
	buf *buffer,
	literalType ValueType,
	literalValue []byte,
	useKey **string,
	nesting int,
) (*Node, int, error) {
	var err error
	current, nesting, err = createLiteralNode(current, buf, literalType, literalValue, useKey, nesting)
	if err != nil {
		return nil, nesting, err
	}
	return current, nesting, nil
}

// isValidContainerType checks if the current node is a valid container (object or array).
// The container must satisfy the following conditions:
//  1. The current node must not be nil.
//  2. The current node must be an object or array.
//  3. The current node must not be ready.
func isValidContainerType(current *Node, nodeType ValueType) bool {
	switch nodeType {
	case Object:
		return current != nil && current.IsObject() && !current.ready()
	case Array:
		return current != nil && current.IsArray() && !current.ready()
	default:
		return false
	}
}

// getString extracts a string from the buffer and advances the buffer index past the string.
func getString(b *buffer) (*string, error) {
	start := b.index
	if err := b.string(doubleQuote, false); err != nil {
		return nil, err
	}

	value, ok := Unquote(b.data[start:b.index+1], doubleQuote)
	if !ok {
		return nil, unexpectedTokenError(b.data, start)
	}

	return &value, nil
}

// createNode creates a new node and sets the key if it is not nil.
func createNode(
	current *Node,
	buf *buffer,
	nodeType ValueType,
	key **string,
) (*Node, error) {
	var err error
	current, err = NewNode(current, buf, nodeType, key)
	if err != nil {
		return nil, err
	}

	return current, nil
}

// createNestedNode creates a new nested node (array or object) and sets the key if it is not nil.
func createNestedNode(
	current *Node,
	buf *buffer,
	nodeType ValueType,
	nesting int,
	key **string,
) (*Node, int, error) {
	var err error
	if nesting, err = checkNestingDepth(nesting); err != nil {
		return nil, nesting, err
	}

	if current, err = createNode(current, buf, nodeType, key); err != nil {
		return nil, nesting, err
	}

	return current, nesting, nil
}

// createLiteralNode creates a new literal node and sets the key if it is not nil.
// The literal is a byte slice that represents a boolean or null value.
func createLiteralNode(
	current *Node,
	buf *buffer,
	literalType ValueType,
	literal []byte,
	useKey **string,
	nesting int,
) (*Node, int, error) {
	var err error
	if current, err = createNode(current, buf, literalType, useKey); err != nil {
		return nil, 0, err
	}

	if err = buf.word(literal); err != nil {
		return nil, 0, err
	}

	current, nesting = updateNode(current, buf, nesting, false)
	buf.state = OK

	return current, nesting, nil
}

// updateNode updates the current node and returns the previous node.
func updateNode(
	current *Node, buf *buffer, nesting int, decreaseLevel bool,
) (*Node, int) {
	current.borders[1] = buf.index + 1

	prev := current.prev
	if prev == nil {
		return current, nesting
	}

	current = prev
	if decreaseLevel {
		nesting--
	}

	return current, nesting
}

// updateNodeAndSetBufferState updates the current node and sets the buffer state to OK.
func updateNodeAndSetBufferState(
	current *Node,
	buf *buffer,
	nesting int,
	typ ValueType,
) (*Node, int, error) {
	if !isValidContainerType(current, typ) {
		return nil, nesting, unexpectedTokenError(buf.data, buf.index)
	}

	current, nesting = updateNode(current, buf, nesting, true)
	buf.state = OK

	return current, nesting, nil
}

// checkNestingDepth checks if the nesting depth is within the maximum allowed depth.
func checkNestingDepth(nesting int) (int, error) {
	if nesting >= maxNestingDepth {
		return nesting, errors.New("maximum nesting depth exceeded")
	}

	return nesting + 1, nil
}

func unexpectedTokenError(data []byte, index int) error {
	return ufmt.Errorf("unexpected token at index %d. data %b", index, data)
}

decode_test.gno

package json

import (
	"bytes"
	"testing"
)

type testNode struct {
	name  string
	input []byte
	value []byte
	_type ValueType
}

func simpleValid(test *testNode, t *testing.T) {
	root, err := Unmarshal(test.input)
	if err != nil {
		t.Errorf("Error on Unmarshal(%s): %s", test.input, err.Error())
	} else if root == nil {
		t.Errorf("Error on Unmarshal(%s): root is nil", test.name)
	} else if root.nodeType != test._type {
		t.Errorf("Error on Unmarshal(%s): wrong type", test.name)
	} else if !bytes.Equal(root.source(), test.value) {
		t.Errorf("Error on Unmarshal(%s): %s != %s", test.name, root.source(), test.value)
	}
}

func simpleInvalid(test *testNode, t *testing.T) {
	root, err := Unmarshal(test.input)
	if err == nil {
		t.Errorf("Error on Unmarshal(%s): error expected, got '%s'", test.name, root.source())
	} else if root != nil {
		t.Errorf("Error on Unmarshal(%s): root is not nil", test.name)
	}
}

func simpleCorrupted(name string) *testNode {
	return &testNode{name: name, input: []byte(name)}
}

func TestUnmarshal_StringSimpleSuccess(t *testing.T) {
	tests := []*testNode{
		{name: "blank", input: []byte("\"\""), _type: String, value: []byte("\"\"")},
		{name: "char", input: []byte("\"c\""), _type: String, value: []byte("\"c\"")},
		{name: "word", input: []byte("\"cat\""), _type: String, value: []byte("\"cat\"")},
		{name: "spaces", input: []byte("  \"good cat or dog\"\r\n "), _type: String, value: []byte("\"good cat or dog\"")},
		{name: "backslash", input: []byte("\"good \\\"cat\\\"\""), _type: String, value: []byte("\"good \\\"cat\\\"\"")},
		{name: "backslash 2", input: []byte("\"good \\\\\\\"cat\\\"\""), _type: String, value: []byte("\"good \\\\\\\"cat\\\"\"")},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			simpleValid(test, t)
		})
	}
}

func TestUnmarshal_NumericSimpleSuccess(t *testing.T) {
	tests := []*testNode{
		{name: "1", input: []byte("1"), _type: Number, value: []byte("1")},
		{name: "-1", input: []byte("-1"), _type: Number, value: []byte("-1")},

		{name: "1234567890", input: []byte("1234567890"), _type: Number, value: []byte("1234567890")},
		{name: "-123", input: []byte("-123"), _type: Number, value: []byte("-123")},

		{name: "123.456", input: []byte("123.456"), _type: Number, value: []byte("123.456")},
		{name: "-123.456", input: []byte("-123.456"), _type: Number, value: []byte("-123.456")},

		{name: "1e3", input: []byte("1e3"), _type: Number, value: []byte("1e3")},
		{name: "1e+3", input: []byte("1e+3"), _type: Number, value: []byte("1e+3")},
		{name: "1e-3", input: []byte("1e-3"), _type: Number, value: []byte("1e-3")},
		{name: "-1e3", input: []byte("-1e3"), _type: Number, value: []byte("-1e3")},
		{name: "-1e-3", input: []byte("-1e-3"), _type: Number, value: []byte("-1e-3")},

		{name: "1.123e3456", input: []byte("1.123e3456"), _type: Number, value: []byte("1.123e3456")},
		{name: "1.123e-3456", input: []byte("1.123e-3456"), _type: Number, value: []byte("1.123e-3456")},
		{name: "-1.123e3456", input: []byte("-1.123e3456"), _type: Number, value: []byte("-1.123e3456")},
		{name: "-1.123e-3456", input: []byte("-1.123e-3456"), _type: Number, value: []byte("-1.123e-3456")},

		{name: "1E3", input: []byte("1E3"), _type: Number, value: []byte("1E3")},
		{name: "1E-3", input: []byte("1E-3"), _type: Number, value: []byte("1E-3")},
		{name: "-1E3", input: []byte("-1E3"), _type: Number, value: []byte("-1E3")},
		{name: "-1E-3", input: []byte("-1E-3"), _type: Number, value: []byte("-1E-3")},

		{name: "1.123E3456", input: []byte("1.123E3456"), _type: Number, value: []byte("1.123E3456")},
		{name: "1.123E-3456", input: []byte("1.123E-3456"), _type: Number, value: []byte("1.123E-3456")},
		{name: "-1.123E3456", input: []byte("-1.123E3456"), _type: Number, value: []byte("-1.123E3456")},
		{name: "-1.123E-3456", input: []byte("-1.123E-3456"), _type: Number, value: []byte("-1.123E-3456")},

		{name: "-1.123E-3456 with spaces", input: []byte(" \r -1.123E-3456 \t\n"), _type: Number, value: []byte("-1.123E-3456")},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			root, err := Unmarshal(test.input)
			if err != nil {
				t.Errorf("Error on Unmarshal(%s): %s", test.name, err.Error())
			} else if root == nil {
				t.Errorf("Error on Unmarshal(%s): root is nil", test.name)
			} else if root.nodeType != test._type {
				t.Errorf("Error on Unmarshal(%s): wrong type", test.name)
			} else if !bytes.Equal(root.source(), test.value) {
				t.Errorf("Error on Unmarshal(%s): %s != %s", test.name, root.source(), test.value)
			}
		})
	}
}

func TestUnmarshal_StringSimpleCorrupted(t *testing.T) {
	tests := []*testNode{
		{name: "white NL", input: []byte("\"foo\nbar\"")},
		{name: "white R", input: []byte("\"foo\rbar\"")},
		{name: "white Tab", input: []byte("\"foo\tbar\"")},
		{name: "wrong quotes", input: []byte("'cat'")},
		{name: "double string", input: []byte("\"Hello\" \"World\"")},
		{name: "quotes in quotes", input: []byte("\"good \"cat\"\"")},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			simpleInvalid(test, t)
		})
	}
}

func TestUnmarshal_ObjectSimpleSuccess(t *testing.T) {
	tests := []*testNode{
		{name: "{}", input: []byte("{}"), _type: Object, value: []byte("{}")},
		{name: `{ \r\n }`, input: []byte("{ \r\n }"), _type: Object, value: []byte("{ \r\n }")},
		{name: `{"key":1}`, input: []byte(`{"key":1}`), _type: Object, value: []byte(`{"key":1}`)},
		{name: `{"key":true}`, input: []byte(`{"key":true}`), _type: Object, value: []byte(`{"key":true}`)},
		{name: `{"key":"value"}`, input: []byte(`{"key":"value"}`), _type: Object, value: []byte(`{"key":"value"}`)},
		{name: `{"foo":"bar","baz":"foo"}`, input: []byte(`{"foo":"bar", "baz":"foo"}`), _type: Object, value: []byte(`{"foo":"bar", "baz":"foo"}`)},
		{name: "spaces", input: []byte(`  {  "foo"  :  "bar"  , "baz"   :   "foo"   }    `), _type: Object, value: []byte(`{  "foo"  :  "bar"  , "baz"   :   "foo"   }`)},
		{name: "nested", input: []byte(`{"foo":{"bar":{"baz":{}}}}`), _type: Object, value: []byte(`{"foo":{"bar":{"baz":{}}}}`)},
		{name: "array", input: []byte(`{"array":[{},{},{"foo":[{"bar":["baz"]}]}]}`), _type: Object, value: []byte(`{"array":[{},{},{"foo":[{"bar":["baz"]}]}]}`)},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			simpleValid(test, t)
		})
	}
}

func TestUnmarshal_ObjectSimpleCorrupted(t *testing.T) {
	tests := []*testNode{
		simpleCorrupted("{{{\"key\": \"foo\"{{{{"),
		simpleCorrupted("}"),
		simpleCorrupted("{ }}}}}}}"),
		simpleCorrupted(" }"),
		simpleCorrupted("{,}"),
		simpleCorrupted("{:}"),
		simpleCorrupted("{100000}"),
		simpleCorrupted("{1:1}"),
		simpleCorrupted("{'1:2,3:4'}"),
		simpleCorrupted(`{"d"}`),
		simpleCorrupted(`{"foo"}`),
		simpleCorrupted(`{"foo":}`),
		simpleCorrupted(`{:"foo"}`),
		simpleCorrupted(`{"foo":bar}`),
		simpleCorrupted(`{"foo":"bar",}`),
		simpleCorrupted(`{}{}`),
		simpleCorrupted(`{},{}`),
		simpleCorrupted(`{[},{]}`),
		simpleCorrupted(`{[,]}`),
		simpleCorrupted(`{[]}`),
		simpleCorrupted(`{}1`),
		simpleCorrupted(`1{}`),
		simpleCorrupted(`{"x"::1}`),
		simpleCorrupted(`{null:null}`),
		simpleCorrupted(`{"foo:"bar"}`),
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			simpleInvalid(test, t)
		})
	}
}

func TestUnmarshal_NullSimpleCorrupted(t *testing.T) {
	tests := []*testNode{
		{name: "nul", input: []byte("nul")},
		{name: "nil", input: []byte("nil")},
		{name: "nill", input: []byte("nill")},
		{name: "NILL", input: []byte("NILL")},
		{name: "Null", input: []byte("Null")},
		{name: "NULL", input: []byte("NULL")},
		{name: "spaces", input: []byte("Nu ll")},
		{name: "null1", input: []byte("null1")},
		{name: "double", input: []byte("null null")},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			simpleInvalid(test, t)
		})
	}
}

func TestUnmarshal_BoolSimpleSuccess(t *testing.T) {
	tests := []*testNode{
		{name: "lower true", input: []byte("true"), _type: Boolean, value: []byte("true")},
		{name: "lower false", input: []byte("false"), _type: Boolean, value: []byte("false")},
		{name: "spaces true", input: []byte("  true\r\n "), _type: Boolean, value: []byte("true")},
		{name: "spaces false", input: []byte("  false\r\n "), _type: Boolean, value: []byte("false")},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			simpleValid(test, t)
		})
	}
}

func TestUnmarshal_BoolSimpleCorrupted(t *testing.T) {
	tests := []*testNode{
		simpleCorrupted("tru"),
		simpleCorrupted("fals"),
		simpleCorrupted("tre"),
		simpleCorrupted("fal se"),
		simpleCorrupted("true false"),
		simpleCorrupted("True"),
		simpleCorrupted("TRUE"),
		simpleCorrupted("False"),
		simpleCorrupted("FALSE"),
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			simpleInvalid(test, t)
		})
	}
}

func TestUnmarshal_ArraySimpleSuccess(t *testing.T) {
	tests := []*testNode{
		{name: "[]", input: []byte("[]"), _type: Array, value: []byte("[]")},
		{name: "[1]", input: []byte("[1]"), _type: Array, value: []byte("[1]")},
		{name: "[1,2,3]", input: []byte("[1,2,3]"), _type: Array, value: []byte("[1,2,3]")},
		{name: "[1, 2, 3]", input: []byte("[1, 2, 3]"), _type: Array, value: []byte("[1, 2, 3]")},
		{name: "[1,[2],3]", input: []byte("[1,[2],3]"), _type: Array, value: []byte("[1,[2],3]")},
		{name: "[[],[],[]]", input: []byte("[[],[],[]]"), _type: Array, value: []byte("[[],[],[]]")},
		{name: "[[[[[]]]]]", input: []byte("[[[[[]]]]]"), _type: Array, value: []byte("[[[[[]]]]]")},
		{name: "[true,null,1,\"foo\",[]]", input: []byte("[true,null,1,\"foo\",[]]"), _type: Array, value: []byte("[true,null,1,\"foo\",[]]")},
		{name: "spaces", input: []byte("\n\r [\n1\n ]\r\n"), _type: Array, value: []byte("[\n1\n ]")},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			simpleValid(test, t)
		})
	}
}

func TestUnmarshal_ArraySimpleCorrupted(t *testing.T) {
	tests := []*testNode{
		simpleCorrupted("[,]"),
		simpleCorrupted("[]\\"),
		simpleCorrupted("[1,]"),
		simpleCorrupted("[[]"),
		simpleCorrupted("[]]"),
		simpleCorrupted("1[]"),
		simpleCorrupted("[]1"),
		simpleCorrupted("[[]1]"),
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			simpleInvalid(test, t)
		})
	}
}

// Examples from https://json.org/example.html
func TestUnmarshal(t *testing.T) {
	tests := []struct {
		name  string
		value string
	}{
		{
			name: "glossary",
			value: `{
				"glossary": {
					"title": "example glossary",
					"GlossDiv": {
						"title": "S",
						"GlossList": {
							"GlossEntry": {
								"ID": "SGML",
								"SortAs": "SGML",
								"GlossTerm": "Standard Generalized Markup Language",
								"Acronym": "SGML",
								"Abbrev": "ISO 8879:1986",
								"GlossDef": {
									"para": "A meta-markup language, used to create markup languages such as DocBook.",
									"GlossSeeAlso": ["GML", "XML"]
								},
								"GlossSee": "markup"
							}
						}
					}
				}
			}`,
		},
		{
			name: "menu",
			value: `{"menu": {
				"id": "file",
				"value": "File",
				"popup": {
				  "menuitem": [
					{"value": "New", "onclick": "CreateNewDoc()"},
					{"value": "Open", "onclick": "OpenDoc()"},
					{"value": "Close", "onclick": "CloseDoc()"}
				  ]
				}
			}}`,
		},
		{
			name: "widget",
			value: `{"widget": {
				"debug": "on",
				"window": {
					"title": "Sample Konfabulator Widget",
					"name": "main_window",
					"width": 500,
					"height": 500
				},
				"image": { 
					"src": "Images/Sun.png",
					"name": "sun1",
					"hOffset": 250,
					"vOffset": 250,
					"alignment": "center"
				},
				"text": {
					"data": "Click Here",
					"size": 36,
					"style": "bold",
					"name": "text1",
					"hOffset": 250,
					"vOffset": 100,
					"alignment": "center",
					"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
				}
			}}    `,
		},
		{
			name: "web-app",
			value: `{"web-app": {
				"servlet": [   
				  {
					"servlet-name": "cofaxCDS",
					"servlet-class": "org.cofax.cds.CDSServlet",
					"init-param": {
					  "configGlossary:installationAt": "Philadelphia, PA",
					  "configGlossary:adminEmail": "[email protected]",
					  "configGlossary:poweredBy": "Cofax",
					  "configGlossary:poweredByIcon": "/images/cofax.gif",
					  "configGlossary:staticPath": "/content/static",
					  "templateProcessorClass": "org.cofax.WysiwygTemplate",
					  "templateLoaderClass": "org.cofax.FilesTemplateLoader",
					  "templatePath": "templates",
					  "templateOverridePath": "",
					  "defaultListTemplate": "listTemplate.htm",
					  "defaultFileTemplate": "articleTemplate.htm",
					  "useJSP": false,
					  "jspListTemplate": "listTemplate.jsp",
					  "jspFileTemplate": "articleTemplate.jsp",
					  "cachePackageTagsTrack": 200,
					  "cachePackageTagsStore": 200,
					  "cachePackageTagsRefresh": 60,
					  "cacheTemplatesTrack": 100,
					  "cacheTemplatesStore": 50,
					  "cacheTemplatesRefresh": 15,
					  "cachePagesTrack": 200,
					  "cachePagesStore": 100,
					  "cachePagesRefresh": 10,
					  "cachePagesDirtyRead": 10,
					  "searchEngineListTemplate": "forSearchEnginesList.htm",
					  "searchEngineFileTemplate": "forSearchEngines.htm",
					  "searchEngineRobotsDb": "WEB-INF/robots.db",
					  "useDataStore": true,
					  "dataStoreClass": "org.cofax.SqlDataStore",
					  "redirectionClass": "org.cofax.SqlRedirection",
					  "dataStoreName": "cofax",
					  "dataStoreDriver": "com.microsoft.jdbc.sqlserver.SQLServerDriver",
					  "dataStoreUrl": "jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon",
					  "dataStoreUser": "sa",
					  "dataStorePassword": "dataStoreTestQuery",
					  "dataStoreTestQuery": "SET NOCOUNT ON;select test='test';",
					  "dataStoreLogFile": "/usr/local/tomcat/logs/datastore.log",
					  "dataStoreInitConns": 10,
					  "dataStoreMaxConns": 100,
					  "dataStoreConnUsageLimit": 100,
					  "dataStoreLogLevel": "debug",
					  "maxUrlLength": 500}},
				  {
					"servlet-name": "cofaxEmail",
					"servlet-class": "org.cofax.cds.EmailServlet",
					"init-param": {
					"mailHost": "mail1",
					"mailHostOverride": "mail2"}},
				  {
					"servlet-name": "cofaxAdmin",
					"servlet-class": "org.cofax.cds.AdminServlet"},
			   
				  {
					"servlet-name": "fileServlet",
					"servlet-class": "org.cofax.cds.FileServlet"},
				  {
					"servlet-name": "cofaxTools",
					"servlet-class": "org.cofax.cms.CofaxToolsServlet",
					"init-param": {
					  "templatePath": "toolstemplates/",
					  "log": 1,
					  "logLocation": "/usr/local/tomcat/logs/CofaxTools.log",
					  "logMaxSize": "",
					  "dataLog": 1,
					  "dataLogLocation": "/usr/local/tomcat/logs/dataLog.log",
					  "dataLogMaxSize": "",
					  "removePageCache": "/content/admin/remove?cache=pages&id=",
					  "removeTemplateCache": "/content/admin/remove?cache=templates&id=",
					  "fileTransferFolder": "/usr/local/tomcat/webapps/content/fileTransferFolder",
					  "lookInContext": 1,
					  "adminGroupID": 4,
					  "betaServer": true}}],
				"servlet-mapping": {
				  "cofaxCDS": "/",
				  "cofaxEmail": "/cofaxutil/aemail/*",
				  "cofaxAdmin": "/admin/*",
				  "fileServlet": "/static/*",
				  "cofaxTools": "/tools/*"},
			   
				"taglib": {
				  "taglib-uri": "cofax.tld",
				  "taglib-location": "/WEB-INF/tlds/cofax.tld"}}}`,
		},
		{
			name: "SVG Viewer",
			value: `{"menu": {
				"header": "SVG Viewer",
				"items": [
					{"id": "Open"},
					{"id": "OpenNew", "label": "Open New"},
					null,
					{"id": "ZoomIn", "label": "Zoom In"},
					{"id": "ZoomOut", "label": "Zoom Out"},
					{"id": "OriginalView", "label": "Original View"},
					null,
					{"id": "Quality"},
					{"id": "Pause"},
					{"id": "Mute"},
					null,
					{"id": "Find", "label": "Find..."},
					{"id": "FindAgain", "label": "Find Again"},
					{"id": "Copy"},
					{"id": "CopyAgain", "label": "Copy Again"},
					{"id": "CopySVG", "label": "Copy SVG"},
					{"id": "ViewSVG", "label": "View SVG"},
					{"id": "ViewSource", "label": "View Source"},
					{"id": "SaveAs", "label": "Save As"},
					null,
					{"id": "Help"},
					{"id": "About", "label": "About Adobe CVG Viewer..."}
				]
			}}`,
		},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			_, err := Unmarshal([]byte(test.value))
			if err != nil {
				t.Errorf("Error on Unmarshal: %s", err.Error())
			}
		})
	}
}

func TestUnmarshalSafe(t *testing.T) {
	json := []byte(`{ "store": {
		"book": [ 
		  { "category": "reference",
			"author": "Nigel Rees",
			"title": "Sayings of the Century",
			"price": 8.95
		  },
		  { "category": "fiction",
			"author": "Evelyn Waugh",
			"title": "Sword of Honour",
			"price": 12.99
		  },
		  { "category": "fiction",
			"author": "Herman Melville",
			"title": "Moby Dick",
			"isbn": "0-553-21311-3",
			"price": 8.99
		  },
		  { "category": "fiction",
			"author": "J. R. R. Tolkien",
			"title": "The Lord of the Rings",
			"isbn": "0-395-19395-8",
			"price": 22.99
		  }
		],
		"bicycle": {
		  "color": "red",
		  "price": 19.95
		}
	  }
	}`)
	safe, err := UnmarshalSafe(json)
	if err != nil {
		t.Errorf("Error on Unmarshal: %s", err.Error())
	} else if safe == nil {
		t.Errorf("Error on Unmarshal: safe is nil")
	} else {
		root, err := Unmarshal(json)
		if err != nil {
			t.Errorf("Error on Unmarshal: %s", err.Error())
		} else if root == nil {
			t.Errorf("Error on Unmarshal: root is nil")
		} else if !bytes.Equal(root.source(), safe.source()) {
			t.Errorf("Error on UnmarshalSafe: values not same")
		}
	}
}

// BenchmarkGoStdUnmarshal-8   	   61698	     19350 ns/op	     288 B/op	       6 allocs/op
// BenchmarkUnmarshal-8        	   45620	     26165 ns/op	   21889 B/op	     367 allocs/op
//
// type bench struct {
// 	Name  string `json:"name"`
// 	Value int    `json:"value"`
// }

// func BenchmarkGoStdUnmarshal(b *testing.B) {
// 	data := []byte(webApp)
// 	for i := 0; i < b.N; i++ {
// 		err := json.Unmarshal(data, &bench{})
// 		if err != nil {
// 			b.Fatal(err)
// 		}
// 	}
// }

// func BenchmarkUnmarshal(b *testing.B) {
// 	data := []byte(webApp)
// 	for i := 0; i < b.N; i++ {
// 		_, err := Unmarshal(data)
// 		if err != nil {
// 			b.Fatal(err)
// 		}
// 	}
// }

encode.gno

package json

import (
	"bytes"
	"errors"
	"strconv"

	"gno.land/p/nt/ufmt/v0"
)

// Marshal returns the JSON encoding of a Node.
func Marshal(node *Node) ([]byte, error) {
	var (
		buf  bytes.Buffer
		sVal string
		bVal bool
		nVal float64
		oVal []byte
		err  error
	)

	if node == nil {
		return nil, errors.New("node is nil")
	}

	if !node.modified && !node.ready() {
		return nil, errors.New("node is not ready")
	}

	if !node.modified && node.ready() {
		buf.Write(node.source())
	}

	if node.modified {
		switch node.nodeType {
		case Null:
			buf.Write(nullLiteral)

		case Number:
			nVal, err = node.GetNumeric()
			if err != nil {
				return nil, err
			}

			num := strconv.FormatFloat(nVal, 'f', -1, 64)
			buf.WriteString(num)

		case String:
			sVal, err = node.GetString()
			if err != nil {
				return nil, err
			}

			quoted := ufmt.Sprintf("%s", strconv.Quote(sVal))
			buf.WriteString(quoted)

		case Boolean:
			bVal, err = node.GetBool()
			if err != nil {
				return nil, err
			}

			bStr := ufmt.Sprintf("%t", bVal)
			buf.WriteString(bStr)

		case Array:
			buf.WriteByte(bracketOpen)

			for i := 0; i < len(node.next); i++ {
				if i != 0 {
					buf.WriteByte(comma)
				}

				elem, ok := node.next[strconv.Itoa(i)]
				if !ok {
					return nil, ufmt.Errorf("array element %d is not found", i)
				}

				oVal, err = Marshal(elem)
				if err != nil {
					return nil, err
				}

				buf.Write(oVal)
			}

			buf.WriteByte(bracketClose)

		case Object:
			buf.WriteByte(curlyOpen)

			bVal = false
			for k, v := range node.next {
				if bVal {
					buf.WriteByte(comma)
				} else {
					bVal = true
				}

				key := ufmt.Sprintf("%s", strconv.Quote(k))
				buf.WriteString(key)
				buf.WriteByte(colon)

				oVal, err = Marshal(v)
				if err != nil {
					return nil, err
				}

				buf.Write(oVal)
			}

			buf.WriteByte(curlyClose)
		}
	}

	return buf.Bytes(), nil
}

encode_test.gno

package json

import "testing"

func TestMarshal_Primitive(t *testing.T) {
	tests := []struct {
		name string
		node *Node
	}{
		{
			name: "null",
			node: NullNode(""),
		},
		{
			name: "true",
			node: BoolNode("", true),
		},
		{
			name: "false",
			node: BoolNode("", false),
		},
		{
			name: `"string"`,
			node: StringNode("", "string"),
		},
		{
			name: `"one \"encoded\" string"`,
			node: StringNode("", `one "encoded" string`),
		},
		{
			name: `{"foo":"bar"}`,
			node: ObjectNode("", map[string]*Node{
				"foo": StringNode("foo", "bar"),
			}),
		},
		{
			name: "42",
			node: NumberNode("", 42),
		},
		{
			name: "3.14",
			node: NumberNode("", 3.14),
		},
		{
			name: `[1,2,3]`,
			node: ArrayNode("", []*Node{
				NumberNode("0", 1),
				NumberNode("2", 2),
				NumberNode("3", 3),
			}),
		},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			value, err := Marshal(test.node)
			if err != nil {
				t.Errorf("unexpected error: %s", err)
			} else if string(value) != test.name {
				t.Errorf("wrong result: '%s', expected '%s'", value, test.name)
			}
		})
	}
}

func TestMarshal_Object(t *testing.T) {
	node := ObjectNode("", map[string]*Node{
		"foo": StringNode("foo", "bar"),
		"baz": NumberNode("baz", 100500),
		"qux": NullNode("qux"),
	})

	mustKey := []string{"foo", "baz", "qux"}

	value, err := Marshal(node)
	if err != nil {
		t.Errorf("unexpected error: %s", err)
	}

	// the order of keys in the map is not guaranteed
	// so we need to unmarshal the result and check the keys
	decoded, err := Unmarshal(value)
	if err != nil {
		t.Errorf("unexpected error: %s", err)
	}

	for _, key := range mustKey {
		if node, err := decoded.GetKey(key); err != nil {
			t.Errorf("unexpected error: %s", err)
		} else {
			if node == nil {
				t.Errorf("node is nil")
			} else if node.key == nil {
				t.Errorf("key is nil")
			} else if *node.key != key {
				t.Errorf("wrong key: '%s', expected '%s'", *node.key, key)
			}
		}
	}
}

func valueNode(prev *Node, key string, typ ValueType, val any) *Node {
	curr := &Node{
		prev:     prev,
		data:     nil,
		key:      &key,
		borders:  [2]int{0, 0},
		value:    val,
		modified: true,
	}

	if val != nil {
		curr.nodeType = typ
	}

	return curr
}

func TestMarshal_Errors(t *testing.T) {
	tests := []struct {
		name string
		node func() (node *Node)
	}{
		{
			name: "nil",
			node: func() (node *Node) {
				return
			},
		},
		{
			name: "broken",
			node: func() (node *Node) {
				node = Must(Unmarshal([]byte(`{}`)))
				node.borders[1] = 0
				return
			},
		},
		{
			name: "Numeric",
			node: func() (node *Node) {
				return valueNode(nil, "", Number, false)
			},
		},
		{
			name: "String",
			node: func() (node *Node) {
				return valueNode(nil, "", String, false)
			},
		},
		{
			name: "Bool",
			node: func() (node *Node) {
				return valueNode(nil, "", Boolean, 1)
			},
		},
		{
			name: "Array_1",
			node: func() (node *Node) {
				node = ArrayNode("", nil)
				node.next["1"] = NullNode("1")
				return
			},
		},
		{
			name: "Array_2",
			node: func() (node *Node) {
				return ArrayNode("", []*Node{valueNode(nil, "", Boolean, 1)})
			},
		},
		{
			name: "Object",
			node: func() (node *Node) {
				return ObjectNode("", map[string]*Node{"key": valueNode(nil, "key", Boolean, 1)})
			},
		},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			value, err := Marshal(test.node())
			if err == nil {
				t.Errorf("expected error")
			} else if len(value) != 0 {
				t.Errorf("wrong result")
			}
		})
	}
}

func TestMarshal_Nil(t *testing.T) {
	_, err := Marshal(nil)
	if err == nil {
		t.Error("Expected error for nil node, but got nil")
	}
}

func TestMarshal_NotModified(t *testing.T) {
	node := &Node{}
	_, err := Marshal(node)
	if err == nil {
		t.Error("Expected error for not modified node, but got nil")
	}
}

func TestMarshalCycleReference(t *testing.T) {
	node1 := &Node{
		key:      stringPtr("node1"),
		nodeType: String,
		next: map[string]*Node{
			"next": nil,
		},
	}

	node2 := &Node{
		key:      stringPtr("node2"),
		nodeType: String,
		prev:     node1,
	}

	node1.next["next"] = node2

	_, err := Marshal(node1)
	if err == nil {
		t.Error("Expected error for cycle reference, but got nil")
	}
}

func TestMarshalNoCycleReference(t *testing.T) {
	node1 := &Node{
		key:      stringPtr("node1"),
		nodeType: String,
		value:    "value1",
		modified: true,
	}

	node2 := &Node{
		key:      stringPtr("node2"),
		nodeType: String,
		value:    "value2",
		modified: true,
	}

	_, err := Marshal(node1)
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}

	_, err = Marshal(node2)
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}
}

func stringPtr(s string) *string {
	return &s
}

errors.gno

package json

import "errors"

var (
	errNilNode               = errors.New("node is nil")
	errNotArrayNode          = errors.New("node is not array")
	errNotBoolNode           = errors.New("node is not boolean")
	errNotNullNode           = errors.New("node is not null")
	errNotNumberNode         = errors.New("node is not number")
	errNotObjectNode         = errors.New("node is not object")
	errNotStringNode         = errors.New("node is not string")
	errInvalidToken          = errors.New("invalid token")
	errIndexNotFound         = errors.New("index not found")
	errInvalidAppend         = errors.New("can't append value to non-appendable node")
	errInvalidAppendCycle    = errors.New("appending value to itself or its children or parents will cause a cycle")
	errInvalidEscapeSequence = errors.New("invalid escape sequence")
	errInvalidStringValue    = errors.New("invalid string value")
	errEmptyBooleanNode      = errors.New("boolean node is empty")
	errEmptyStringNode       = errors.New("string node is empty")
	errKeyRequired           = errors.New("key is required for object")
	errUnmatchedParenthesis  = errors.New("mismatched bracket or parenthesis")
	errUnmatchedQuotePath    = errors.New("unmatched quote in path")
)

var (
	errInvalidStringInput    = errors.New("invalid string input")
	errMalformedBooleanValue = errors.New("malformed boolean value")
	errEmptyByteSlice        = errors.New("empty byte slice")
	errInvalidExponentValue  = errors.New("invalid exponent value")
	errNonDigitCharacters    = errors.New("non-digit characters found")
	errNumericRangeExceeded  = errors.New("numeric value exceeds the range limit")
	errMultipleDecimalPoints = errors.New("multiple decimal points found")
)

escape.gno

package json

import (
	"unicode/utf8"
)

const (
	supplementalPlanesOffset     = 0x10000
	highSurrogateOffset          = 0xD800
	lowSurrogateOffset           = 0xDC00
	surrogateEnd                 = 0xDFFF
	basicMultilingualPlaneOffset = 0xFFFF
	badHex                       = -1

	singleUnicodeEscapeLen = 6
	surrogatePairLen       = 12
)

var hexLookupTable = [256]int{
	'0': 0x0, '1': 0x1, '2': 0x2, '3': 0x3, '4': 0x4,
	'5': 0x5, '6': 0x6, '7': 0x7, '8': 0x8, '9': 0x9,
	'A': 0xA, 'B': 0xB, 'C': 0xC, 'D': 0xD, 'E': 0xE, 'F': 0xF,
	'a': 0xA, 'b': 0xB, 'c': 0xC, 'd': 0xD, 'e': 0xE, 'f': 0xF,
	// Fill unspecified index-value pairs with key and value of -1
	'G': -1, 'H': -1, 'I': -1, 'J': -1,
	'K': -1, 'L': -1, 'M': -1, 'N': -1,
	'O': -1, 'P': -1, 'Q': -1, 'R': -1,
	'S': -1, 'T': -1, 'U': -1, 'V': -1,
	'W': -1, 'X': -1, 'Y': -1, 'Z': -1,
	'g': -1, 'h': -1, 'i': -1, 'j': -1,
	'k': -1, 'l': -1, 'm': -1, 'n': -1,
	'o': -1, 'p': -1, 'q': -1, 'r': -1,
	's': -1, 't': -1, 'u': -1, 'v': -1,
	'w': -1, 'x': -1, 'y': -1, 'z': -1,
}

func h2i(c byte) int {
	return hexLookupTable[c]
}

// Unescape takes an input byte slice, processes it to Unescape certain characters,
// and writes the result into an output byte slice.
//
// it returns the processed slice and any error encountered during the Unescape operation.
func Unescape(input, output []byte) ([]byte, error) {
	// ensure the output slice has enough capacity to hold the input slice.
	inputLen := len(input)
	if cap(output) < inputLen {
		output = make([]byte, inputLen)
	}

	inPos, outPos := 0, 0

	for inPos < len(input) {
		c := input[inPos]
		if c != backSlash {
			output[outPos] = c
			inPos++
			outPos++
		} else {
			// process escape sequence
			inLen, outLen, err := processEscapedUTF8(input[inPos:], output[outPos:])
			if err != nil {
				return nil, err
			}
			inPos += inLen
			outPos += outLen
		}
	}

	return output[:outPos], nil
}

// isSurrogatePair returns true if the rune is a surrogate pair.
//
// A surrogate pairs are used in UTF-16 encoding to encode characters
// outside the Basic Multilingual Plane (BMP).
func isSurrogatePair(r rune) bool {
	return highSurrogateOffset <= r && r <= surrogateEnd
}

// isHighSurrogate checks if the rune is a high surrogate (U+D800 to U+DBFF).
func isHighSurrogate(r rune) bool {
	return r >= highSurrogateOffset && r <= 0xDBFF
}

// isLowSurrogate checks if the rune is a low surrogate (U+DC00 to U+DFFF).
func isLowSurrogate(r rune) bool {
	return r >= lowSurrogateOffset && r <= surrogateEnd
}

// combineSurrogates reconstruct the original unicode code points in the
// supplemental plane by combinin the high and low surrogate.
//
// The hight surrogate in the range from U+D800 to U+DBFF,
// and the low surrogate in the range from U+DC00 to U+DFFF.
//
// The formula to combine the surrogates is:
// (high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000
func combineSurrogates(high, low rune) rune {
	return ((high - highSurrogateOffset) << 10) + (low - lowSurrogateOffset) + supplementalPlanesOffset
}

// deocdeSingleUnicodeEscape decodes a unicode escape sequence (e.g., \uXXXX) into a rune.
func decodeSingleUnicodeEscape(b []byte) (rune, bool) {
	if len(b) < 6 {
		return utf8.RuneError, false
	}

	// convert hex to decimal
	h1, h2, h3, h4 := h2i(b[2]), h2i(b[3]), h2i(b[4]), h2i(b[5])
	if h1 == badHex || h2 == badHex || h3 == badHex || h4 == badHex {
		return utf8.RuneError, false
	}

	return rune(h1<<12 + h2<<8 + h3<<4 + h4), true
}

// decodeUnicodeEscape decodes a Unicode escape sequence from a byte slice.
// It handles both single Unicode escape sequences and surrogate pairs.
func decodeUnicodeEscape(b []byte) (rune, int) {
	// decode the first Unicode escape sequence.
	r, ok := decodeSingleUnicodeEscape(b)
	if !ok {
		return utf8.RuneError, -1
	}

	// if the rune is within the BMP and not a surrogate, return it
	if r <= basicMultilingualPlaneOffset && !isSurrogatePair(r) {
		return r, 6
	}

	if !isHighSurrogate(r) {
		// invalid surrogate pair.
		return utf8.RuneError, -1
	}

	// if the rune is a high surrogate, need to decode the next escape sequence.

	// ensure there are enough bytes for the next escape sequence.
	if len(b) < surrogatePairLen {
		return utf8.RuneError, -1
	}
	// decode the second Unicode escape sequence.
	r2, ok := decodeSingleUnicodeEscape(b[singleUnicodeEscapeLen:])
	if !ok {
		return utf8.RuneError, -1
	}
	// check if the second rune is a low surrogate.
	if isLowSurrogate(r2) {
		combined := combineSurrogates(r, r2)
		return combined, surrogatePairLen
	}
	return utf8.RuneError, -1
}

var escapeByteSet = [256]byte{
	'"':  doubleQuote,
	'\\': backSlash,
	'/':  slash,
	'b':  backSpace,
	'f':  formFeed,
	'n':  newLine,
	'r':  carriageReturn,
	't':  tab,
}

// Unquote takes a byte slice and unquotes it by removing
// the surrounding quotes and unescaping the contents.
func Unquote(s []byte, border byte) (string, bool) {
	s, ok := unquoteBytes(s, border)
	return string(s), ok
}

// unquoteBytes takes a byte slice and unquotes it by removing
func unquoteBytes(s []byte, border byte) ([]byte, bool) {
	if len(s) < 2 || s[0] != border || s[len(s)-1] != border {
		return nil, false
	}

	s = s[1 : len(s)-1]

	r := 0
	for r < len(s) {
		c := s[r]

		if c == backSlash || c == border || c < 0x20 {
			break
		}

		if c < utf8.RuneSelf {
			r++
			continue
		}

		rr, size := utf8.DecodeRune(s[r:])
		if rr == utf8.RuneError && size == 1 {
			break
		}

		r += size
	}

	if r == len(s) {
		return s, true
	}

	utfDoubleMax := utf8.UTFMax * 2
	b := make([]byte, len(s)+utfDoubleMax)
	w := copy(b, s[0:r])

	for r < len(s) {
		if w >= len(b)-utf8.UTFMax {
			nb := make([]byte, utfDoubleMax+(2*len(b)))
			copy(nb, b)
			b = nb
		}

		c := s[r]
		if c == backSlash {
			r++
			if r >= len(s) {
				return nil, false
			}

			if s[r] == 'u' {
				rr, res := decodeUnicodeEscape(s[r-1:])
				if res < 0 {
					return nil, false
				}

				w += utf8.EncodeRune(b[w:], rr)
				r += 5
			} else {
				decode := escapeByteSet[s[r]]
				if decode == 0 {
					return nil, false
				}

				if decode == doubleQuote || decode == backSlash || decode == slash {
					decode = s[r]
				}

				b[w] = decode
				r++
				w++
			}
		} else if c == border || c < 0x20 {
			return nil, false
		} else if c < utf8.RuneSelf {
			b[w] = c
			r++
			w++
		} else {
			rr, size := utf8.DecodeRune(s[r:])

			if rr == utf8.RuneError && size == 1 {
				return nil, false
			}

			r += size
			w += utf8.EncodeRune(b[w:], rr)
		}
	}

	return b[:w], true
}

// processEscapedUTF8 converts escape sequences to UTF-8 characters.
// It decodes Unicode escape sequences (\uXXXX) to UTF-8 and
// converts standard escape sequences (e.g., \n) to their corresponding special characters.
func processEscapedUTF8(in, out []byte) (int, int, error) {
	if len(in) < 2 || in[0] != backSlash {
		return -1, -1, errInvalidEscapeSequence
	}

	escapeSeqLen := 2
	escapeChar := in[1]

	if escapeChar != 'u' {
		val := escapeByteSet[escapeChar]
		if val == 0 {
			return -1, -1, errInvalidEscapeSequence
		}

		out[0] = val
		return escapeSeqLen, 1, nil
	}

	r, size := decodeUnicodeEscape(in)
	if size == -1 {
		return -1, -1, errInvalidEscapeSequence
	}

	outLen := utf8.EncodeRune(out, r)

	return size, outLen, nil
}

escape_test.gno

package json

import (
	"bytes"
	"testing"
	"unicode/utf8"
)

func TestHexToInt(t *testing.T) {
	tests := []struct {
		name string
		c    byte
		want int
	}{
		{"Digit 0", '0', 0},
		{"Digit 9", '9', 9},
		{"Uppercase A", 'A', 10},
		{"Uppercase F", 'F', 15},
		{"Lowercase a", 'a', 10},
		{"Lowercase f", 'f', 15},
		{"Invalid character1", 'g', badHex},
		{"Invalid character2", 'G', badHex},
		{"Invalid character3", 'z', badHex},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := h2i(tt.c); got != tt.want {
				t.Errorf("h2i() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestIsSurrogatePair(t *testing.T) {
	testCases := []struct {
		name     string
		r        rune
		expected bool
	}{
		{"high surrogate start", 0xD800, true},
		{"high surrogate end", 0xDBFF, true},
		{"low surrogate start", 0xDC00, true},
		{"low surrogate end", 0xDFFF, true},
		{"Non-surrogate", 0x0000, false},
		{"Non-surrogate 2", 0xE000, false},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			if got := isSurrogatePair(tc.r); got != tc.expected {
				t.Errorf("isSurrogate() = %v, want %v", got, tc.expected)
			}
		})
	}
}

func TestCombineSurrogates(t *testing.T) {
	testCases := []struct {
		high, low rune
		expected  rune
	}{
		{0xD83D, 0xDC36, 0x1F436}, // 🐶 U+1F436 DOG FACE
		{0xD83D, 0xDE00, 0x1F600}, // 😀 U+1F600 GRINNING FACE
		{0xD83C, 0xDF03, 0x1F303}, // 🌃 U+1F303 NIGHT WITH STARS
	}

	for _, tc := range testCases {
		result := combineSurrogates(tc.high, tc.low)
		if result != tc.expected {
			t.Errorf("combineSurrogates(%U, %U) = %U; want %U", tc.high, tc.low, result, tc.expected)
		}
	}
}

func TestDecodeSingleUnicodeEscape(t *testing.T) {
	testCases := []struct {
		input    []byte
		expected rune
		isValid  bool
	}{
		// valid unicode escape sequences
		{[]byte(`\u0041`), 'A', true},
		{[]byte(`\u03B1`), 'α', true},
		{[]byte(`\u00E9`), 'é', true}, // valid non-English character
		{[]byte(`\u0021`), '!', true}, // valid special character
		{[]byte(`\uFF11`), '1', true},
		{[]byte(`\uD83D`), 0xD83D, true},
		{[]byte(`\uDE03`), 0xDE03, true},

		// invalid unicode escape sequences
		{[]byte(`\u004`), utf8.RuneError, false},  // too short
		{[]byte(`\uXYZW`), utf8.RuneError, false}, // invalid hex
		{[]byte(`\u00G1`), utf8.RuneError, false}, // non-hex character
	}

	for _, tc := range testCases {
		result, isValid := decodeSingleUnicodeEscape(tc.input)
		if result != tc.expected || isValid != tc.isValid {
			t.Errorf("decodeSingleUnicodeEscape(%s) = (%U, %v); want (%U, %v)", tc.input, result, isValid, tc.expected, tc.isValid)
		}
	}
}

func TestDecodeUnicodeEscape(t *testing.T) {
	tests := []struct {
		input    []byte
		expected rune
		size     int
	}{
		{[]byte(`\u0041`), 'A', 6},
		{[]byte(`\uD83D\uDE00`), 0x1F600, 12}, // 😀
		{[]byte(`\uD834\uDD1E`), 0x1D11E, 12}, // 𝄞
		{[]byte(`\uFFFF`), '\uFFFF', 6},
		{[]byte(`\uXYZW`), utf8.RuneError, -1},
		{[]byte(`\uD800`), utf8.RuneError, -1},       // single high surrogate
		{[]byte(`\uDC00`), utf8.RuneError, -1},       // single low surrogate
		{[]byte(`\uD800\uDC00`), 0x10000, 12},        // First code point above U+FFFF
		{[]byte(`\uDBFF\uDFFF`), 0x10FFFF, 12},       // Maximum code point
		{[]byte(`\uD83D\u0041`), utf8.RuneError, -1}, // invalid surrogate pair
	}

	for _, tc := range tests {
		r, size := decodeUnicodeEscape(tc.input)
		if r != tc.expected || size != tc.size {
			t.Errorf("decodeUnicodeEscape(%q) = (%U, %d); want (%U, %d)", tc.input, r, size, tc.expected, tc.size)
		}
	}
}

func TestUnescapeToUTF8(t *testing.T) {
	tests := []struct {
		input       []byte
		expectedIn  int
		expectedOut int
		isError     bool
	}{
		// valid escape sequences
		{[]byte(`\n`), 2, 1, false},
		{[]byte(`\t`), 2, 1, false},
		{[]byte(`\u0041`), 6, 1, false},
		{[]byte(`\u03B1`), 6, 2, false},
		{[]byte(`\uD830\uDE03`), 12, 4, false},

		// invalid escape sequences
		{[]byte(`\`), -1, -1, true},            // incomplete escape sequence
		{[]byte(`\x`), -1, -1, true},           // invalid escape character
		{[]byte(`\u`), -1, -1, true},           // incomplete unicode escape sequence
		{[]byte(`\u004`), -1, -1, true},        // invalid unicode escape sequence
		{[]byte(`\uXYZW`), -1, -1, true},       // invalid unicode escape sequence
		{[]byte(`\uD83D\u0041`), -1, -1, true}, // invalid unicode escape sequence
	}

	for _, tc := range tests {
		input := make([]byte, len(tc.input))
		copy(input, tc.input)
		output := make([]byte, utf8.UTFMax)
		inLen, outLen, err := processEscapedUTF8(input, output)
		if (err != nil) != tc.isError {
			t.Errorf("processEscapedUTF8(%q) = %v; want %v", tc.input, err, tc.isError)
		}

		if inLen != tc.expectedIn || outLen != tc.expectedOut {
			t.Errorf("processEscapedUTF8(%q) = (%d, %d); want (%d, %d)", tc.input, inLen, outLen, tc.expectedIn, tc.expectedOut)
		}
	}
}

func TestUnescape(t *testing.T) {
	tests := []struct {
		name     string
		input    []byte
		expected []byte
		isError  bool
	}{
		{"NoEscape", []byte("hello world"), []byte("hello world"), false},
		{"SingleEscape", []byte("hello\\nworld"), []byte("hello\nworld"), false},
		{"MultipleEscapes", []byte("line1\\nline2\\r\\nline3"), []byte("line1\nline2\r\nline3"), false},
		{"UnicodeEscape", []byte("snowman:\\u2603"), []byte("snowman:\u2603"), false},
		{"SurrogatePair", []byte("emoji:\\uD83D\\uDE00"), []byte("emoji:😀"), false},
		{"InvalidEscape", []byte("hello\\xworld"), nil, true},
		{"IncompleteUnicode", []byte("incomplete:\\u123"), nil, true},
		{"InvalidSurrogatePair", []byte("invalid:\\uD83D\\u0041"), nil, true},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			output := make([]byte, len(tc.input)*2) // Allocate extra space for possible expansion
			result, err := Unescape(tc.input, output)
			if (err != nil) != tc.isError {
				t.Errorf("Unescape(%q) error = %v; want error = %v", tc.input, err, tc.isError)
			}

			if !tc.isError && !bytes.Equal(result, tc.expected) {
				t.Errorf("Unescape(%q) = %q; want %q", tc.input, result, tc.expected)
			}
		})
	}
}

func TestUnquoteBytes(t *testing.T) {
	tests := []struct {
		input    []byte
		border   byte
		expected []byte
		ok       bool
	}{
		{[]byte("\"hello\""), '"', []byte("hello"), true},
		{[]byte("'hello'"), '\'', []byte("hello"), true},
		{[]byte("\"hello"), '"', nil, false},
		{[]byte("hello\""), '"', nil, false},
		{[]byte("\"he\\\"llo\""), '"', []byte("he\"llo"), true},
		{[]byte("\"he\\nllo\""), '"', []byte("he\nllo"), true},
		{[]byte("\"\""), '"', []byte(""), true},
		{[]byte("''"), '\'', []byte(""), true},
		{[]byte("\"\\u0041\""), '"', []byte("A"), true},
		{[]byte(`"Hello, 世界"`), '"', []byte("Hello, 世界"), true},
		{[]byte(`"Hello, \x80"`), '"', nil, false},
		{[]byte(`"invalid surrogate: \uD83D\u0041"`), '"', nil, false},
	}

	for _, tc := range tests {
		result, pass := unquoteBytes(tc.input, tc.border)

		if pass != tc.ok {
			t.Errorf("unquoteBytes(%q) = %v; want %v", tc.input, pass, tc.ok)
		}

		if !bytes.Equal(result, tc.expected) {
			t.Errorf("unquoteBytes(%q) = %q; want %q", tc.input, result, tc.expected)
		}
	}
}

gnomod.toml

module = "gno.land/p/onbloc/json/v0"
gno = "0.9"

[addpkg]
  creator = "g1edq4dugw0sgat4zxcw9xardvuydqf6cgleuc8p"

indent.gno

package json

import (
	"bytes"
	"strings"
)

// indentGrowthFactor specifies the growth factor of indenting JSON input.
// A factor no higher than 2 ensures that wasted space never exceeds 50%.
const indentGrowthFactor = 2

// IndentJSON formats the JSON data with the specified indentation.
func Indent(data []byte, indent string) ([]byte, error) {
	var (
		out        bytes.Buffer
		level      int
		inArray    bool
		arrayDepth int
	)

	for i := 0; i < len(data); i++ {
		c := data[i] // current character

		switch c {
		case bracketOpen:
			arrayDepth++
			if arrayDepth > 1 {
				level++ // increase the level if it's nested array
				inArray = true

				if err := out.WriteByte(c); err != nil {
					return nil, err
				}

				if err := writeNewlineAndIndent(&out, level, indent); err != nil {
					return nil, err
				}
			} else {
				// case of the top-level array
				inArray = true
				if err := out.WriteByte(c); err != nil {
					return nil, err
				}
			}

		case bracketClose:
			if inArray && arrayDepth > 1 { // nested array
				level--
				if err := writeNewlineAndIndent(&out, level, indent); err != nil {
					return nil, err
				}
			}

			arrayDepth--
			if arrayDepth == 0 {
				inArray = false
			}

			if err := out.WriteByte(c); err != nil {
				return nil, err
			}

		case curlyOpen:
			// check if the empty object or array
			// we don't need to apply the indent when it's empty containers.
			if i+1 < len(data) && data[i+1] == curlyClose {
				if err := out.WriteByte(c); err != nil {
					return nil, err
				}

				i++ // skip next character
				if err := out.WriteByte(data[i]); err != nil {
					return nil, err
				}
			} else {
				if err := out.WriteByte(c); err != nil {
					return nil, err
				}

				level++
				if err := writeNewlineAndIndent(&out, level, indent); err != nil {
					return nil, err
				}
			}

		case curlyClose:
			level--
			if err := writeNewlineAndIndent(&out, level, indent); err != nil {
				return nil, err
			}
			if err := out.WriteByte(c); err != nil {
				return nil, err
			}

		case comma, colon:
			if err := out.WriteByte(c); err != nil {
				return nil, err
			}
			if inArray && arrayDepth > 1 { // nested array
				if err := writeNewlineAndIndent(&out, level, indent); err != nil {
					return nil, err
				}
			} else if c == colon {
				if err := out.WriteByte(' '); err != nil {
					return nil, err
				}
			}

		default:
			if err := out.WriteByte(c); err != nil {
				return nil, err
			}
		}
	}

	return out.Bytes(), nil
}

func writeNewlineAndIndent(out *bytes.Buffer, level int, indent string) error {
	if err := out.WriteByte('\n'); err != nil {
		return err
	}

	idt := strings.Repeat(indent, level*indentGrowthFactor)
	if _, err := out.WriteString(idt); err != nil {
		return err
	}

	return nil
}

indent_test.gno

package json

import (
	"bytes"
	"testing"
)

func TestIndentJSON(t *testing.T) {
	tests := []struct {
		name     string
		input    []byte
		indent   string
		expected []byte
	}{
		{
			name:     "empty object",
			input:    []byte(`{}`),
			indent:   "  ",
			expected: []byte(`{}`),
		},
		{
			name:     "empty array",
			input:    []byte(`[]`),
			indent:   "  ",
			expected: []byte(`[]`),
		},
		{
			name:     "nested object",
			input:    []byte(`{{}}`),
			indent:   "\t",
			expected: []byte("{\n\t\t{}\n}"),
		},
		{
			name:     "nested array",
			input:    []byte(`[[[]]]`),
			indent:   "\t",
			expected: []byte("[[\n\t\t[\n\t\t\t\t\n\t\t]\n]]"),
		},
		{
			name:     "top-level array",
			input:    []byte(`["apple","banana","cherry"]`),
			indent:   "\t",
			expected: []byte(`["apple","banana","cherry"]`),
		},
		{
			name:     "array of arrays",
			input:    []byte(`["apple",["banana","cherry"],"date"]`),
			indent:   "  ",
			expected: []byte("[\"apple\",[\n    \"banana\",\n    \"cherry\"\n],\"date\"]"),
		},

		{
			name:     "nested array in object",
			input:    []byte(`{"fruits":["apple",["banana","cherry"],"date"]}`),
			indent:   "  ",
			expected: []byte("{\n    \"fruits\": [\"apple\",[\n        \"banana\",\n        \"cherry\"\n    ],\"date\"]\n}"),
		},
		{
			name:     "complex nested structure",
			input:    []byte(`{"data":{"array":[1,2,3],"bool":true,"nestedArray":[["a","b"],"c"]}}`),
			indent:   "  ",
			expected: []byte("{\n    \"data\": {\n        \"array\": [1,2,3],\"bool\": true,\"nestedArray\": [[\n            \"a\",\n            \"b\"\n        ],\"c\"]\n    }\n}"),
		},
		{
			name:     "custom ident character",
			input:    []byte(`{"fruits":["apple",["banana","cherry"],"date"]}`),
			indent:   "*",
			expected: []byte("{\n**\"fruits\": [\"apple\",[\n****\"banana\",\n****\"cherry\"\n**],\"date\"]\n}"),
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			actual, err := Indent(tt.input, tt.indent)
			if err != nil {
				t.Errorf("IndentJSON() error = %v", err)
				return
			}
			if !bytes.Equal(actual, tt.expected) {
				t.Errorf("IndentJSON() = %q, want %q", actual, tt.expected)
			}
		})
	}
}

internal.gno

package json

// Reference: https://github.com/freddierice/php_source/blob/467ed5d6edff72219afd3e644516f131118ef48e/ext/json/JSON_parser.c
// Copyright (c) 2005 JSON.org

// Go implementation is taken from: https://github.com/spyzhov/ajson/blob/master/internal/state.go

type (
	States  int8 // possible states of the parser
	Classes int8 // JSON string character types
)

const __ = -1

// enum classes
const (
	C_SPACE Classes = iota /* space */
	C_WHITE                /* other whitespace */
	C_LCURB                /* {  */
	C_RCURB                /* } */
	C_LSQRB                /* [ */
	C_RSQRB                /* ] */
	C_COLON                /* : */
	C_COMMA                /* , */
	C_QUOTE                /* " */
	C_BACKS                /* \ */
	C_SLASH                /* / */
	C_PLUS                 /* + */
	C_MINUS                /* - */
	C_POINT                /* . */
	C_ZERO                 /* 0 */
	C_DIGIT                /* 123456789 */
	C_LOW_A                /* a */
	C_LOW_B                /* b */
	C_LOW_C                /* c */
	C_LOW_D                /* d */
	C_LOW_E                /* e */
	C_LOW_F                /* f */
	C_LOW_L                /* l */
	C_LOW_N                /* n */
	C_LOW_R                /* r */
	C_LOW_S                /* s */
	C_LOW_T                /* t */
	C_LOW_U                /* u */
	C_ABCDF                /* ABCDF */
	C_E                    /* E */
	C_ETC                  /* everything else */
)

// AsciiClasses array maps the 128 ASCII characters into character classes.
var AsciiClasses = [128]Classes{
	/*
	   This array maps the 128 ASCII characters into character classes.
	   The remaining Unicode characters should be mapped to C_ETC.
	   Non-whitespace control characters are errors.
	*/
	__, __, __, __, __, __, __, __,
	__, C_WHITE, C_WHITE, __, __, C_WHITE, __, __,
	__, __, __, __, __, __, __, __,
	__, __, __, __, __, __, __, __,

	C_SPACE, C_ETC, C_QUOTE, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,
	C_ETC, C_ETC, C_ETC, C_PLUS, C_COMMA, C_MINUS, C_POINT, C_SLASH,
	C_ZERO, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT,
	C_DIGIT, C_DIGIT, C_COLON, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,

	C_ETC, C_ABCDF, C_ABCDF, C_ABCDF, C_ABCDF, C_E, C_ABCDF, C_ETC,
	C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,
	C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,
	C_ETC, C_ETC, C_ETC, C_LSQRB, C_BACKS, C_RSQRB, C_ETC, C_ETC,

	C_ETC, C_LOW_A, C_LOW_B, C_LOW_C, C_LOW_D, C_LOW_E, C_LOW_F, C_ETC,
	C_ETC, C_ETC, C_ETC, C_ETC, C_LOW_L, C_ETC, C_LOW_N, C_ETC,
	C_ETC, C_ETC, C_LOW_R, C_LOW_S, C_LOW_T, C_LOW_U, C_ETC, C_ETC,
	C_ETC, C_ETC, C_ETC, C_LCURB, C_ETC, C_RCURB, C_ETC, C_ETC,
}

// QuoteAsciiClasses is a HACK for single quote from AsciiClasses
var QuoteAsciiClasses = [128]Classes{
	/*
	   This array maps the 128 ASCII characters into character classes.
	   The remaining Unicode characters should be mapped to C_ETC.
	   Non-whitespace control characters are errors.
	*/
	__, __, __, __, __, __, __, __,
	__, C_WHITE, C_WHITE, __, __, C_WHITE, __, __,
	__, __, __, __, __, __, __, __,
	__, __, __, __, __, __, __, __,

	C_SPACE, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_QUOTE,
	C_ETC, C_ETC, C_ETC, C_PLUS, C_COMMA, C_MINUS, C_POINT, C_SLASH,
	C_ZERO, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT,
	C_DIGIT, C_DIGIT, C_COLON, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,

	C_ETC, C_ABCDF, C_ABCDF, C_ABCDF, C_ABCDF, C_E, C_ABCDF, C_ETC,
	C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,
	C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,
	C_ETC, C_ETC, C_ETC, C_LSQRB, C_BACKS, C_RSQRB, C_ETC, C_ETC,

	C_ETC, C_LOW_A, C_LOW_B, C_LOW_C, C_LOW_D, C_LOW_E, C_LOW_F, C_ETC,
	C_ETC, C_ETC, C_ETC, C_ETC, C_LOW_L, C_ETC, C_LOW_N, C_ETC,
	C_ETC, C_ETC, C_LOW_R, C_LOW_S, C_LOW_T, C_LOW_U, C_ETC, C_ETC,
	C_ETC, C_ETC, C_ETC, C_LCURB, C_ETC, C_RCURB, C_ETC, C_ETC,
}

/*
The state codes.
*/
const (
	GO States = iota /* start    */
	OK               /* ok       */
	OB               /* object   */
	KE               /* key      */
	CO               /* colon    */
	VA               /* value    */
	AR               /* array    */
	ST               /* string   */
	ES               /* escape   */
	U1               /* u1       */
	U2               /* u2       */
	U3               /* u3       */
	U4               /* u4       */
	MI               /* minus    */
	ZE               /* zero     */
	IN               /* integer  */
	DT               /* dot      */
	FR               /* fraction */
	E1               /* e        */
	E2               /* ex       */
	E3               /* exp      */
	T1               /* tr       */
	T2               /* tru      */
	T3               /* true     */
	F1               /* fa       */
	F2               /* fal      */
	F3               /* fals     */
	F4               /* false    */
	N1               /* nu       */
	N2               /* nul      */
	N3               /* null     */
)

// List of action codes.
// these constants are defining an action that should be performed under certain conditions.
const (
	cl States = -2 /* colon           */
	cm States = -3 /* comma           */
	qt States = -4 /* quote           */
	bo States = -5 /* bracket open    */
	co States = -6 /* curly bracket open  */
	bc States = -7 /* bracket close   */
	cc States = -8 /* curly bracket close */
	ec States = -9 /* curly bracket empty */
)

// StateTransitionTable is the state transition table takes the current state and the current symbol, and returns either
// a new state or an action. An action is represented as a negative number. A JSON text is accepted if at the end of the
// text the state is OK and if the mode is DONE.
var StateTransitionTable = [31][31]States{
	/*
	   The state transition table takes the current state and the current symbol,
	   and returns either a new state or an action. An action is represented as a
	   negative number. A JSON text is accepted if at the end of the text the
	   state is OK and if the mode is DONE.
	                  white                                                    1-9                                                ABCDF   etc
	            space   |   {   }   [   ]   :   ,   "   \   /   +   -   .   0   |   a   b   c   d   e   f   l   n   r   s   t   u   |   E   |*/
	/*start  GO*/ {GO, GO, co, __, bo, __, __, __, ST, __, __, __, MI, __, ZE, IN, __, __, __, __, __, F1, __, N1, __, __, T1, __, __, __, __},
	/*ok     OK*/ {OK, OK, __, cc, __, bc, __, cm, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},
	/*object OB*/ {OB, OB, __, ec, __, __, __, __, ST, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},
	/*key    KE*/ {KE, KE, __, __, __, __, __, __, ST, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},
	/*colon  CO*/ {CO, CO, __, __, __, __, cl, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},
	/*value  VA*/ {VA, VA, co, __, bo, __, __, __, ST, __, __, __, MI, __, ZE, IN, __, __, __, __, __, F1, __, N1, __, __, T1, __, __, __, __},
	/*array  AR*/ {AR, AR, co, __, bo, bc, __, __, ST, __, __, __, MI, __, ZE, IN, __, __, __, __, __, F1, __, N1, __, __, T1, __, __, __, __},
	/*string ST*/ {ST, __, ST, ST, ST, ST, ST, ST, qt, ES, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST},
	/*escape ES*/ {__, __, __, __, __, __, __, __, ST, ST, ST, __, __, __, __, __, __, ST, __, __, __, ST, __, ST, ST, __, ST, U1, __, __, __},
	/*u1     U1*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, U2, U2, U2, U2, U2, U2, U2, U2, __, __, __, __, __, __, U2, U2, __},
	/*u2     U2*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, U3, U3, U3, U3, U3, U3, U3, U3, __, __, __, __, __, __, U3, U3, __},
	/*u3     U3*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, U4, U4, U4, U4, U4, U4, U4, U4, __, __, __, __, __, __, U4, U4, __},
	/*u4     U4*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, ST, ST, ST, ST, ST, ST, ST, ST, __, __, __, __, __, __, ST, ST, __},
	/*minus  MI*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, ZE, IN, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},
	/*zero   ZE*/ {OK, OK, __, cc, __, bc, __, cm, __, __, __, __, __, DT, __, __, __, __, __, __, E1, __, __, __, __, __, __, __, __, E1, __},
	/*int    IN*/ {OK, OK, __, cc, __, bc, __, cm, __, __, __, __, __, DT, IN, IN, __, __, __, __, E1, __, __, __, __, __, __, __, __, E1, __},
	/*dot    DT*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, FR, FR, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},
	/*frac   FR*/ {OK, OK, __, cc, __, bc, __, cm, __, __, __, __, __, __, FR, FR, __, __, __, __, E1, __, __, __, __, __, __, __, __, E1, __},
	/*e      E1*/ {__, __, __, __, __, __, __, __, __, __, __, E2, E2, __, E3, E3, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},
	/*ex     E2*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, E3, E3, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},
	/*exp    E3*/ {OK, OK, __, cc, __, bc, __, cm, __, __, __, __, __, __, E3, E3, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},
	/*tr     T1*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, T2, __, __, __, __, __, __},
	/*tru    T2*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, T3, __, __, __},
	/*true   T3*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, OK, __, __, __, __, __, __, __, __, __, __},
	/*fa     F1*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, F2, __, __, __, __, __, __, __, __, __, __, __, __, __, __},
	/*fal    F2*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, F3, __, __, __, __, __, __, __, __},
	/*fals   F3*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, F4, __, __, __, __, __},
	/*false  F4*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, OK, __, __, __, __, __, __, __, __, __, __},
	/*nu     N1*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, N2, __, __, __},
	/*nul    N2*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, N3, __, __, __, __, __, __, __, __},
	/*null   N3*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, OK, __, __, __, __, __, __, __, __},
}

node.gno

package json

import (
	"errors"
	"strconv"
	"strings"

	"gno.land/p/nt/ufmt/v0"
)

// Node represents a JSON node.
type Node struct {
	prev     *Node            // prev is the parent node of the current node.
	next     map[string]*Node // next is the child nodes of the current node.
	key      *string          // key holds the key of the current node in the parent node.
	data     []byte           // byte slice of JSON data
	value    any              // value holds the value of the current node.
	nodeType ValueType        // NodeType holds the type of the current node. (Object, Array, String, Number, Boolean, Null)
	index    *int             // index holds the index of the current node in the parent array node.
	borders  [2]int           // borders stores the start and end index of the current node in the data.
	modified bool             // modified indicates the current node is changed or not.
}

// NewNode creates a new node instance with the given parent node, buffer, type, and key.
func NewNode(prev *Node, b *buffer, typ ValueType, key **string) (*Node, error) {
	curr := &Node{
		prev:     prev,
		data:     b.data,
		borders:  [2]int{b.index, 0},
		key:      *key,
		nodeType: typ,
		modified: false,
	}

	if typ == Object || typ == Array {
		curr.next = make(map[string]*Node)
	}

	if prev != nil {
		if prev.IsArray() {
			size := len(prev.next)
			curr.index = &size

			prev.next[strconv.Itoa(size)] = curr
		} else if prev.IsObject() {
			if key == nil {
				return nil, errKeyRequired
			}

			prev.next[**key] = curr
		} else {
			return nil, errors.New("invalid parent type")
		}
	}

	return curr, nil
}

// load retrieves the value of the current node.
func (n *Node) load() any {
	return n.value
}

// Changed checks the current node is changed or not.
func (n *Node) Changed() bool {
	return n.modified
}

// Key returns the key of the current node.
func (n *Node) Key() string {
	if n == nil || n.key == nil {
		return ""
	}

	return *n.key
}

// HasKey checks the current node has the given key or not.
func (n *Node) HasKey(key string) bool {
	if n == nil {
		return false
	}

	_, ok := n.next[key]
	return ok
}

// GetKey returns the value of the given key from the current object node.
func (n *Node) GetKey(key string) (*Node, error) {
	if n == nil {
		return nil, errNilNode
	}

	if n.Type() != Object {
		return nil, ufmt.Errorf("target node is not object type. got: %s", n.Type().String())
	}

	value, ok := n.next[key]
	if !ok {
		return nil, ufmt.Errorf("key not found: %s", key)
	}

	return value, nil
}

// MustKey returns the value of the given key from the current object node.
func (n *Node) MustKey(key string) *Node {
	val, err := n.GetKey(key)
	if err != nil {
		panic(err)
	}

	return val
}

// UniqueKeyLists traverses the current JSON nodes and collects all the unique keys.
func (n *Node) UniqueKeyLists() []string {
	var collectKeys func(*Node) []string
	collectKeys = func(node *Node) []string {
		if node == nil || !node.IsObject() {
			return nil
		}

		result := make(map[string]bool)
		for key, childNode := range node.next {
			result[key] = true
			childKeys := collectKeys(childNode)
			for _, childKey := range childKeys {
				result[childKey] = true
			}
		}

		keys := make([]string, 0, len(result))
		for key := range result {
			keys = append(keys, key)
		}
		return keys
	}

	return collectKeys(n)
}

// Empty returns true if the current node is empty.
func (n *Node) Empty() bool {
	if n == nil {
		return false
	}

	return len(n.next) == 0
}

// Type returns the type (ValueType) of the current node.
func (n *Node) Type() ValueType {
	return n.nodeType
}

// Value returns the value of the current node.
//
// Usage:
//
//	root := Unmarshal([]byte(`{"key": "value"}`))
//	val, err := root.MustKey("key").Value()
//	if err != nil {
//		t.Errorf("Value returns error: %v", err)
//	}
//
//	result: "value"
func (n *Node) Value() (value any, err error) {
	value = n.load()

	if value == nil {
		switch n.nodeType {
		case Null:
			return nil, nil

		case Number:
			value, err = strconv.ParseFloat(string(n.source()), 64)
			if err != nil {
				return nil, err
			}

			n.value = value

		case String:
			var ok bool
			value, ok = Unquote(n.source(), doubleQuote)
			if !ok {
				return "", errInvalidStringValue
			}

			n.value = value

		case Boolean:
			if len(n.source()) == 0 {
				return nil, errEmptyBooleanNode
			}

			b := n.source()[0]
			value = b == 't' || b == 'T'
			n.value = value

		case Array:
			elems := make([]*Node, len(n.next))

			for _, e := range n.next {
				elems[*e.index] = e
			}

			value = elems
			n.value = value

		case Object:
			obj := make(map[string]*Node, len(n.next))

			for k, v := range n.next {
				obj[k] = v
			}

			value = obj
			n.value = value
		}
	}

	return value, nil
}

// Delete removes the current node from the parent node.
//
// Usage:
//
//	root := Unmarshal([]byte(`{"key": "value"}`))
//	if err := root.MustKey("key").Delete(); err != nil {
//		t.Errorf("Delete returns error: %v", err)
//	}
//
//	result: {} (empty object)
func (n *Node) Delete() error {
	if n == nil {
		return errors.New("can't delete nil node")
	}

	if n.prev == nil {
		return nil
	}

	return n.prev.remove(n)
}

// Size returns the size (length) of the current array node.
//
// Usage:
//
//	root := ArrayNode("", []*Node{StringNode("", "foo"), NumberNode("", 1)})
//	if root == nil {
//		t.Errorf("ArrayNode returns nil")
//	}
//
//	if root.Size() != 2 {
//		t.Errorf("ArrayNode returns wrong size: %d", root.Size())
//	}
func (n *Node) Size() int {
	if n == nil {
		return 0
	}

	return len(n.next)
}

// Index returns the index of the current node in the parent array node.
//
// Usage:
//
//	root := ArrayNode("", []*Node{StringNode("", "foo"), NumberNode("", 1)})
//	if root == nil {
//		t.Errorf("ArrayNode returns nil")
//	}
//
//	if root.MustIndex(1).Index() != 1 {
//		t.Errorf("Index returns wrong index: %d", root.MustIndex(1).Index())
//	}
//
// We can also use the index to the byte slice of the JSON data directly.
//
// Example:
//
//	root := Unmarshal([]byte(`["foo", 1]`))
//	if root == nil {
//		t.Errorf("Unmarshal returns nil")
//	}
//
//	if string(root.MustIndex(1).source()) != "1" {
//		t.Errorf("source returns wrong result: %s", root.MustIndex(1).source())
//	}
func (n *Node) Index() int {
	if n == nil || n.index == nil {
		return -1
	}

	return *n.index
}

// MustIndex returns the array element at the given index.
//
// If the index is negative, it returns the index is from the end of the array.
// Also, it panics if the index is not found.
//
// check the Index method for detailed usage.
func (n *Node) MustIndex(expectIdx int) *Node {
	val, err := n.GetIndex(expectIdx)
	if err != nil {
		panic(err)
	}

	return val
}

// GetIndex returns the array element at the given index.
//
// if the index is negative, it returns the index is from the end of the array.
func (n *Node) GetIndex(idx int) (*Node, error) {
	if n == nil {
		return nil, errNilNode
	}

	if !n.IsArray() {
		return nil, errNotArrayNode
	}

	if idx > n.Size() {
		return nil, errors.New("input index exceeds the array size")
	}

	if idx < 0 {
		idx += len(n.next)
	}

	child, ok := n.next[strconv.Itoa(idx)]
	if !ok {
		return nil, errIndexNotFound
	}

	return child, nil
}

// DeleteIndex removes the array element at the given index.
func (n *Node) DeleteIndex(idx int) error {
	node, err := n.GetIndex(idx)
	if err != nil {
		return err
	}

	return n.remove(node)
}

// NullNode creates a new null type node.
//
// Usage:
//
//	_ := NullNode("")
func NullNode(key string) *Node {
	return &Node{
		key:      &key,
		value:    nil,
		nodeType: Null,
		modified: true,
	}
}

// NumberNode creates a new number type node.
//
// Usage:
//
//	root := NumberNode("", 1)
//	if root == nil {
//		t.Errorf("NumberNode returns nil")
//	}
func NumberNode(key string, value float64) *Node {
	return &Node{
		key:      &key,
		value:    value,
		nodeType: Number,
		modified: true,
	}
}

// StringNode creates a new string type node.
//
// Usage:
//
//	root := StringNode("", "foo")
//	if root == nil {
//		t.Errorf("StringNode returns nil")
//	}
func StringNode(key string, value string) *Node {
	return &Node{
		key:      &key,
		value:    value,
		nodeType: String,
		modified: true,
	}
}

// BoolNode creates a new given boolean value node.
//
// Usage:
//
//	root := BoolNode("", true)
//	if root == nil {
//		t.Errorf("BoolNode returns nil")
//	}
func BoolNode(key string, value bool) *Node {
	return &Node{
		key:      &key,
		value:    value,
		nodeType: Boolean,
		modified: true,
	}
}

// ArrayNode creates a new array type node.
//
// If the given value is nil, it creates an empty array node.
//
// Usage:
//
//	root := ArrayNode("", []*Node{StringNode("", "foo"), NumberNode("", 1)})
//	if root == nil {
//		t.Errorf("ArrayNode returns nil")
//	}
func ArrayNode(key string, value []*Node) *Node {
	curr := &Node{
		key:      &key,
		nodeType: Array,
		modified: true,
	}

	curr.next = make(map[string]*Node, len(value))
	if value != nil {
		curr.value = value

		for i, v := range value {
			idx := i
			curr.next[strconv.Itoa(i)] = v

			v.prev = curr
			v.index = &idx
		}
	}

	return curr
}

// ObjectNode creates a new object type node.
//
// If the given value is nil, it creates an empty object node.
//
// next is a map of key and value pairs of the object.
func ObjectNode(key string, value map[string]*Node) *Node {
	curr := &Node{
		nodeType: Object,
		key:      &key,
		next:     value,
		modified: true,
	}

	if value != nil {
		curr.value = value

		for key, val := range value {
			vkey := key
			val.prev = curr
			val.key = &vkey
		}
	} else {
		curr.next = make(map[string]*Node)
	}

	return curr
}

// IsArray returns true if the current node is array type.
func (n *Node) IsArray() bool {
	return n.nodeType == Array
}

// IsObject returns true if the current node is object type.
func (n *Node) IsObject() bool {
	return n.nodeType == Object
}

// IsNull returns true if the current node is null type.
func (n *Node) IsNull() bool {
	return n.nodeType == Null
}

// IsBool returns true if the current node is boolean type.
func (n *Node) IsBool() bool {
	return n.nodeType == Boolean
}

// IsString returns true if the current node is string type.
func (n *Node) IsString() bool {
	return n.nodeType == String
}

// IsNumber returns true if the current node is number type.
func (n *Node) IsNumber() bool {
	return n.nodeType == Number
}

// ready checks the current node is ready or not.
//
// the meaning of ready is the current node is parsed and has a valid value.
func (n *Node) ready() bool {
	return n.borders[1] != 0
}

// source returns the source of the current node.
func (n *Node) source() []byte {
	if n == nil {
		return nil
	}

	if n.ready() && !n.modified && n.data != nil {
		return (n.data)[n.borders[0]:n.borders[1]]
	}

	return nil
}

// root returns the root node of the current node.
func (n *Node) root() *Node {
	if n == nil {
		return nil
	}

	curr := n
	for curr.prev != nil {
		curr = curr.prev
	}

	return curr
}

// GetNull returns the null value if current node is null type.
//
// Usage:
//
//	root := Unmarshal([]byte("null"))
//	val, err := root.GetNull()
//	if err != nil {
//		t.Errorf("GetNull returns error: %v", err)
//	}
//	if val != nil {
//		t.Errorf("GetNull returns wrong result: %v", val)
//	}
func (n *Node) GetNull() (any, error) {
	if n == nil {
		return nil, errNilNode
	}

	if !n.IsNull() {
		return nil, errNotNullNode
	}

	return nil, nil
}

// MustNull returns the null value if current node is null type.
//
// It panics if the current node is not null type.
func (n *Node) MustNull() any {
	v, err := n.GetNull()
	if err != nil {
		panic(err)
	}

	return v
}

// GetNumeric returns the numeric (int/float) value if current node is number type.
//
// Usage:
//
//	root := Unmarshal([]byte("10.5"))
//	val, err := root.GetNumeric()
//	if err != nil {
//		t.Errorf("GetNumeric returns error: %v", err)
//	}
//	println(val) // 10.5
func (n *Node) GetNumeric() (float64, error) {
	if n == nil {
		return 0, errNilNode
	}

	if n.nodeType != Number {
		return 0, errNotNumberNode
	}

	val, err := n.Value()
	if err != nil {
		return 0, err
	}

	v, ok := val.(float64)
	if !ok {
		return 0, errNotNumberNode
	}

	return v, nil
}

// MustNumeric returns the numeric (int/float) value if current node is number type.
//
// It panics if the current node is not number type.
func (n *Node) MustNumeric() float64 {
	v, err := n.GetNumeric()
	if err != nil {
		panic(err)
	}

	return v
}

// GetString returns the string value if current node is string type.
//
// Usage:
//
//	root, err := Unmarshal([]byte("foo"))
//	if err != nil {
//		t.Errorf("Error on Unmarshal(): %s", err)
//	}
//
//	str, err := root.GetString()
//	if err != nil {
//		t.Errorf("should retrieve string value: %s", err)
//	}
//
//	println(str) // "foo"
func (n *Node) GetString() (string, error) {
	if n == nil {
		return "", errEmptyStringNode
	}

	if !n.IsString() {
		return "", errNotStringNode
	}

	val, err := n.Value()
	if err != nil {
		return "", err
	}

	v, ok := val.(string)
	if !ok {
		return "", errNotStringNode
	}

	return v, nil
}

// MustString returns the string value if current node is string type.
//
// It panics if the current node is not string type.
func (n *Node) MustString() string {
	v, err := n.GetString()
	if err != nil {
		panic(err)
	}

	return v
}

// GetBool returns the boolean value if current node is boolean type.
//
// Usage:
//
//	root := Unmarshal([]byte("true"))
//	val, err := root.GetBool()
//	if err != nil {
//		t.Errorf("GetBool returns error: %v", err)
//	}
//	println(val) // true
func (n *Node) GetBool() (bool, error) {
	if n == nil {
		return false, errNilNode
	}

	if n.nodeType != Boolean {
		return false, errNotBoolNode
	}

	val, err := n.Value()
	if err != nil {
		return false, err
	}

	v, ok := val.(bool)
	if !ok {
		return false, errNotBoolNode
	}

	return v, nil
}

// MustBool returns the boolean value if current node is boolean type.
//
// It panics if the current node is not boolean type.
func (n *Node) MustBool() bool {
	v, err := n.GetBool()
	if err != nil {
		panic(err)
	}

	return v
}

// GetArray returns the array value if current node is array type.
//
// Usage:
//
//		root := Must(Unmarshal([]byte(`["foo", 1]`)))
//		arr, err := root.GetArray()
//		if err != nil {
//			t.Errorf("GetArray returns error: %v", err)
//		}
//
//		for _, val := range arr {
//			println(val)
//		}
//
//	 result: "foo", 1
func (n *Node) GetArray() ([]*Node, error) {
	if n == nil {
		return nil, errNilNode
	}

	if n.nodeType != Array {
		return nil, errNotArrayNode
	}

	val, err := n.Value()
	if err != nil {
		return nil, err
	}

	v, ok := val.([]*Node)
	if !ok {
		return nil, errNotArrayNode
	}

	return v, nil
}

// MustArray returns the array value if current node is array type.
//
// It panics if the current node is not array type.
func (n *Node) MustArray() []*Node {
	v, err := n.GetArray()
	if err != nil {
		panic(err)
	}

	return v
}

// AppendArray appends the given values to the current array node.
//
// If the current node is not array type, it returns an error.
//
// Example 1:
//
//	root := Must(Unmarshal([]byte(`[{"foo":"bar"}]`)))
//	if err := root.AppendArray(NullNode("")); err != nil {
//		t.Errorf("should not return error: %s", err)
//	}
//
//	result: [{"foo":"bar"}, null]
//
// Example 2:
//
//	root := Must(Unmarshal([]byte(`["bar", "baz"]`)))
//	err := root.AppendArray(NumberNode("", 1), StringNode("", "foo"))
//	if err != nil {
//		t.Errorf("AppendArray returns error: %v", err)
//	 }
//
//	result: ["bar", "baz", 1, "foo"]
func (n *Node) AppendArray(value ...*Node) error {
	if !n.IsArray() {
		return errInvalidAppend
	}

	for _, val := range value {
		if err := n.append(nil, val); err != nil {
			return err
		}
	}

	n.mark()
	return nil
}

// ArrayEach executes the callback for each element in the JSON array.
//
// Usage:
//
//	jsonArrayNode.ArrayEach(func(i int, valueNode *Node) {
//	    ufmt.Println(i, valueNode)
//	})
func (n *Node) ArrayEach(callback func(i int, target *Node)) {
	if n == nil || !n.IsArray() {
		return
	}

	for idx := 0; idx < len(n.next); idx++ {
		element, err := n.GetIndex(idx)
		if err != nil {
			continue
		}

		callback(idx, element)
	}
}

// GetObject returns the object value if current node is object type.
//
// Usage:
//
//	root := Must(Unmarshal([]byte(`{"key": "value"}`)))
//	obj, err := root.GetObject()
//	if err != nil {
//		t.Errorf("GetObject returns error: %v", err)
//	}
//
//	result: map[string]*Node{"key": StringNode("key", "value")}
func (n *Node) GetObject() (map[string]*Node, error) {
	if n == nil {
		return nil, errNilNode
	}

	if !n.IsObject() {
		return nil, errNotObjectNode
	}

	val, err := n.Value()
	if err != nil {
		return nil, err
	}

	v, ok := val.(map[string]*Node)
	if !ok {
		return nil, errNotObjectNode
	}

	return v, nil
}

// MustObject returns the object value if current node is object type.
//
// It panics if the current node is not object type.
func (n *Node) MustObject() map[string]*Node {
	v, err := n.GetObject()
	if err != nil {
		panic(err)
	}

	return v
}

// AppendObject appends the given key and value to the current object node.
//
// If the current node is not object type, it returns an error.
func (n *Node) AppendObject(key string, value *Node) error {
	if !n.IsObject() {
		return errInvalidAppend
	}

	if err := n.append(&key, value); err != nil {
		return err
	}

	n.mark()
	return nil
}

// ObjectEach executes the callback for each key-value pair in the JSON object.
//
// Usage:
//
//	jsonObjectNode.ObjectEach(func(key string, valueNode *Node) {
//	    ufmt.Println(key, valueNode)
//	})
func (n *Node) ObjectEach(callback func(key string, value *Node)) {
	if n == nil || !n.IsObject() {
		return
	}

	for key, child := range n.next {
		callback(key, child)
	}
}

// String converts the node to a string representation.
func (n *Node) String() string {
	if n == nil {
		return ""
	}

	if n.ready() && !n.modified {
		return string(n.source())
	}

	val, err := Marshal(n)
	if err != nil {
		return "error: " + err.Error()
	}

	return string(val)
}

// Path builds the path of the current node.
//
// For example:
//
//	{ "key": { "sub": [ "val1", "val2" ] }}
//
// The path of "val2" is: $.key.sub[1]
func (n *Node) Path() string {
	if n == nil {
		return ""
	}

	var sb strings.Builder

	if n.prev == nil {
		sb.WriteString("$")
	} else {
		sb.WriteString(n.prev.Path())

		if n.key != nil {
			sb.WriteString("['" + n.Key() + "']")
		} else {
			sb.WriteString("[" + strconv.Itoa(n.Index()) + "]")
		}
	}

	return sb.String()
}

// mark marks the current node as modified.
func (n *Node) mark() {
	node := n
	for node != nil && !node.modified {
		node.modified = true
		node = node.prev
	}
}

// isContainer checks the current node type is array or object.
func (n *Node) isContainer() bool {
	return n.IsArray() || n.IsObject()
}

// remove removes the value from the current container type node.
func (n *Node) remove(v *Node) error {
	if !n.isContainer() {
		return ufmt.Errorf(
			"can't remove value from non-array or non-object node. got=%s",
			n.Type().String(),
		)
	}

	if v.prev != n {
		return errors.New("invalid parent node")
	}

	n.mark()
	if n.IsArray() {
		delete(n.next, strconv.Itoa(*v.index))
		n.dropIndex(*v.index)
	} else {
		delete(n.next, *v.key)
	}

	v.prev = nil
	return nil
}

// dropIndex rebase the index of current array node values.
func (n *Node) dropIndex(idx int) {
	for i := idx + 1; i <= len(n.next); i++ {
		prv := i - 1
		if curr, ok := n.next[strconv.Itoa(i)]; ok {
			curr.index = &prv
			n.next[strconv.Itoa(prv)] = curr
		}

		delete(n.next, strconv.Itoa(i))
	}
}

// append is a helper function to append the given value to the current container type node.
func (n *Node) append(key *string, val *Node) error {
	if n.isSameOrParentNode(val) {
		return errInvalidAppendCycle
	}

	if val.prev != nil {
		if err := val.prev.remove(val); err != nil {
			return err
		}
	}

	val.prev = n
	val.key = key

	if key == nil {
		size := len(n.next)
		val.index = &size
		n.next[strconv.Itoa(size)] = val
	} else {
		if old, ok := n.next[*key]; ok {
			if err := n.remove(old); err != nil {
				return err
			}
		}
		n.next[*key] = val
	}

	return nil
}

func (n *Node) isSameOrParentNode(nd *Node) bool {
	return n == nd || n.isParentNode(nd)
}

func (n *Node) isParentNode(nd *Node) bool {
	if n == nil {
		return false
	}

	for curr := nd.prev; curr != nil; curr = curr.prev {
		if curr == n {
			return true
		}
	}

	return false
}

// cptrs returns the pointer of the given string value.
func cptrs(cpy *string) *string {
	if cpy == nil {
		return nil
	}

	val := *cpy

	return &val
}

// cptri returns the pointer of the given integer value.
func cptri(i *int) *int {
	if i == nil {
		return nil
	}

	val := *i
	return &val
}

// Must panics if the given node is not fulfilled the expectation.
// Usage:
//
//	node := Must(Unmarshal([]byte(`{"key": "value"}`))
func Must(root *Node, expect error) *Node {
	if expect != nil {
		panic(expect)
	}

	return root
}

node_test.gno

package json

import (
	"bytes"
	"sort"
	"strconv"
	"strings"
	"testing"

	"gno.land/p/nt/ufmt/v0"
)

var (
	nilKey   *string
	dummyKey = "key"
)

type _args struct {
	prev *Node
	buf  *buffer
	typ  ValueType
	key  **string
}

type simpleNode struct {
	name string
	node *Node
}

func TestNode_CreateNewNode(t *testing.T) {
	rel := &dummyKey

	tests := []struct {
		name        string
		args        _args
		expectCurr  *Node
		expectErr   bool
		expectPanic bool
	}{
		{
			name: "child for non container type",
			args: _args{
				prev: BoolNode("", true),
				buf:  newBuffer(make([]byte, 10)),
				typ:  Boolean,
				key:  &rel,
			},
			expectCurr: nil,
			expectErr:  true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			defer func() {
				if r := recover(); r != nil {
					if tt.expectPanic {
						return
					}
					t.Errorf("%s panic occurred when not expected: %v", tt.name, r)
				} else if tt.expectPanic {
					t.Errorf("%s expected panic but didn't occur", tt.name)
				}
			}()

			got, err := NewNode(tt.args.prev, tt.args.buf, tt.args.typ, tt.args.key)
			if (err != nil) != tt.expectErr {
				t.Errorf("%s error = %v, expect error %v", tt.name, err, tt.expectErr)
				return
			}

			if tt.expectErr {
				return
			}

			if !compareNodes(got, tt.expectCurr) {
				t.Errorf("%s got = %v, want %v", tt.name, got, tt.expectCurr)
			}
		})
	}
}

func TestNode_Value(t *testing.T) {
	tests := []struct {
		name        string
		data        []byte
		_type       ValueType
		expected    any
		errExpected bool
	}{
		{name: "null", data: []byte("null"), _type: Null, expected: nil},
		{name: "1", data: []byte("1"), _type: Number, expected: float64(1)},
		{name: ".1", data: []byte(".1"), _type: Number, expected: float64(.1)},
		{name: "-.1e1", data: []byte("-.1e1"), _type: Number, expected: float64(-1)},
		{name: "string", data: []byte("\"foo\""), _type: String, expected: "foo"},
		{name: "space", data: []byte("\"foo bar\""), _type: String, expected: "foo bar"},
		{name: "true", data: []byte("true"), _type: Boolean, expected: true},
		{name: "invalid true", data: []byte("tru"), _type: Unknown, errExpected: true},
		{name: "invalid false", data: []byte("fals"), _type: Unknown, errExpected: true},
		{name: "false", data: []byte("false"), _type: Boolean, expected: false},
		{name: "e1", data: []byte("e1"), _type: Unknown, errExpected: true},
		{name: "1a", data: []byte("1a"), _type: Unknown, errExpected: true},
		{name: "string error", data: []byte("\"foo\nbar\""), _type: String, errExpected: true},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			curr := &Node{
				data:     tt.data,
				nodeType: tt._type,
				borders:  [2]int{0, len(tt.data)},
			}

			got, err := curr.Value()
			if err != nil {
				if !tt.errExpected {
					t.Errorf("%s error = %v, expect error %v", tt.name, err, tt.errExpected)
				}
				return
			}

			if got != tt.expected {
				t.Errorf("%s got = %v, want %v", tt.name, got, tt.expected)
			}
		})
	}
}

func TestNode_Delete(t *testing.T) {
	root := Must(Unmarshal([]byte(`{"foo":"bar"}`)))
	if err := root.Delete(); err != nil {
		t.Errorf("Delete returns error: %v", err)
	}

	if value, err := Marshal(root); err != nil {
		t.Errorf("Marshal returns error: %v", err)
	} else if string(value) != `{"foo":"bar"}` {
		t.Errorf("Marshal returns wrong value: %s", string(value))
	}

	foo := root.MustKey("foo")
	if err := foo.Delete(); err != nil {
		t.Errorf("Delete returns error while handling foo: %v", err)
	}

	if value, err := Marshal(root); err != nil {
		t.Errorf("Marshal returns error: %v", err)
	} else if string(value) != `{}` {
		t.Errorf("Marshal returns wrong value: %s", string(value))
	}

	if value, err := Marshal(foo); err != nil {
		t.Errorf("Marshal returns error: %v", err)
	} else if string(value) != `"bar"` {
		t.Errorf("Marshal returns wrong value: %s", string(value))
	}

	if foo.prev != nil {
		t.Errorf("foo.prev should be nil")
	}
}

func TestNode_ObjectNode(t *testing.T) {
	objs := map[string]*Node{
		"key1": NullNode("null"),
		"key2": NumberNode("answer", 42),
		"key3": StringNode("string", "foobar"),
		"key4": BoolNode("bool", true),
	}

	node := ObjectNode("test", objs)

	if len(node.next) != len(objs) {
		t.Errorf("ObjectNode: want %v got %v", len(objs), len(node.next))
	}

	for k, v := range objs {
		if node.next[k] == nil {
			t.Errorf("ObjectNode: want %v got %v", v, node.next[k])
		}
	}
}

func TestNode_AppendObject(t *testing.T) {
	if err := Must(Unmarshal([]byte(`{"foo":"bar","baz":null}`))).AppendObject("biz", NullNode("")); err != nil {
		t.Errorf("AppendArray should return error")
	}

	root := Must(Unmarshal([]byte(`{"foo":"bar"}`)))
	if err := root.AppendObject("baz", NullNode("")); err != nil {
		t.Errorf("AppendObject should not return error: %s", err)
	}

	if value, err := Marshal(root); err != nil {
		t.Errorf("Marshal returns error: %v", err)
	} else if isSameObject(string(value), `"{"foo":"bar","baz":null}"`) {
		t.Errorf("Marshal returns wrong value: %s", string(value))
	}

	// FIXME: this may fail if execute test in more than 3 times in a row.
	if err := root.AppendObject("biz", NumberNode("", 42)); err != nil {
		t.Errorf("AppendObject returns error: %v", err)
	}

	val, err := Marshal(root)
	if err != nil {
		t.Errorf("Marshal returns error: %v", err)
	}

	// FIXME: this may fail if execute test in more than 3 times in a row.
	if isSameObject(string(val), `"{"foo":"bar","baz":null,"biz":42}"`) {
		t.Errorf("Marshal returns wrong value: %s", string(val))
	}
}

func TestNode_ArrayNode(t *testing.T) {
	arr := []*Node{
		NullNode("nil"),
		NumberNode("num", 42),
		StringNode("str", "foobar"),
		BoolNode("bool", true),
	}

	node := ArrayNode("test", arr)

	if len(node.next) != len(arr) {
		t.Errorf("ArrayNode: want %v got %v", len(arr), len(node.next))
	}

	for i, v := range arr {
		if node.next[strconv.Itoa(i)] == nil {
			t.Errorf("ArrayNode: want %v got %v", v, node.next[strconv.Itoa(i)])
		}
	}
}

func TestNode_AppendArray(t *testing.T) {
	if err := Must(Unmarshal([]byte(`[{"foo":"bar"}]`))).AppendArray(NullNode("")); err != nil {
		t.Errorf("should return error")
	}

	root := Must(Unmarshal([]byte(`[{"foo":"bar"}]`)))
	if err := root.AppendArray(NullNode("")); err != nil {
		t.Errorf("should not return error: %s", err)
	}

	if value, err := Marshal(root); err != nil {
		t.Errorf("Marshal returns error: %v", err)
	} else if string(value) != `[{"foo":"bar"},null]` {
		t.Errorf("Marshal returns wrong value: %s", string(value))
	}

	if err := root.AppendArray(
		NumberNode("", 1),
		StringNode("", "foo"),
		Must(Unmarshal([]byte(`[0,1,null,true,"example"]`))),
		Must(Unmarshal([]byte(`{"foo": true, "bar": null, "baz": 123}`))),
	); err != nil {
		t.Errorf("AppendArray returns error: %v", err)
	}

	if value, err := Marshal(root); err != nil {
		t.Errorf("Marshal returns error: %v", err)
	} else if string(value) != `[{"foo":"bar"},null,1,"foo",[0,1,null,true,"example"],{"foo": true, "bar": null, "baz": 123}]` {
		t.Errorf("Marshal returns wrong value: %s", string(value))
	}
}

/******** value getter ********/

func TestNode_GetBool(t *testing.T) {
	root, err := Unmarshal([]byte(`true`))
	if err != nil {
		t.Errorf("Error on Unmarshal(): %s", err.Error())
		return
	}

	value, err := root.GetBool()
	if err != nil {
		t.Errorf("Error on root.GetBool(): %s", err.Error())
	}

	if !value {
		t.Errorf("root.GetBool() is corrupted")
	}
}

func TestNode_GetBool_NotSucceed(t *testing.T) {
	tests := []simpleNode{
		{"nil node", (*Node)(nil)},
		{"literally null node", NullNode("")},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if _, err := tt.node.GetBool(); err == nil {
				t.Errorf("%s should be an error", tt.name)
			}
		})
	}
}

func TestNode_IsBool(t *testing.T) {
	tests := []simpleNode{
		{"true", BoolNode("", true)},
		{"false", BoolNode("", false)},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if !tt.node.IsBool() {
				t.Errorf("%s should be a bool", tt.name)
			}
		})
	}
}

func TestNode_IsBool_With_Unmarshal(t *testing.T) {
	tests := []struct {
		name string
		json []byte
		want bool
	}{
		{"true", []byte("true"), true},
		{"false", []byte("false"), true},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			root, err := Unmarshal(tt.json)
			if err != nil {
				t.Errorf("Error on Unmarshal(): %s", err.Error())
			}

			if root.IsBool() != tt.want {
				t.Errorf("%s should be a bool", tt.name)
			}
		})
	}
}

var nullJson = []byte(`null`)

func TestNode_GetNull(t *testing.T) {
	root, err := Unmarshal(nullJson)
	if err != nil {
		t.Errorf("Error on Unmarshal(): %s", err.Error())
	}

	value, err := root.GetNull()
	if err != nil {
		t.Errorf("error occurred while getting null, %s", err)
	}

	if value != nil {
		t.Errorf("value is not matched. expected: nil, got: %v", value)
	}
}

func TestNode_GetNull_NotSucceed(t *testing.T) {
	tests := []simpleNode{
		{"nil node", (*Node)(nil)},
		{"number node is null", NumberNode("", 42)},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if _, err := tt.node.GetNull(); err == nil {
				t.Errorf("%s should be an error", tt.name)
			}
		})
	}
}

func TestNode_MustNull(t *testing.T) {
	root, err := Unmarshal(nullJson)
	if err != nil {
		t.Errorf("Error on Unmarshal(): %s", err.Error())
	}

	value := root.MustNull()
	if value != nil {
		t.Errorf("value is not matched. expected: nil, got: %v", value)
	}
}

func TestNode_GetNumeric_Float(t *testing.T) {
	root, err := Unmarshal([]byte(`123.456`))
	if err != nil {
		t.Errorf("Error on Unmarshal(): %s", err)
		return
	}

	value, err := root.GetNumeric()
	if err != nil {
		t.Errorf("Error on root.GetNumeric(): %s", err)
	}

	if value != float64(123.456) {
		t.Errorf(ufmt.Sprintf("value is not matched. expected: 123.456, got: %v", value))
	}
}

func TestNode_GetNumeric_Scientific_Notation(t *testing.T) {
	root, err := Unmarshal([]byte(`1e3`))
	if err != nil {
		t.Errorf("Error on Unmarshal(): %s", err)
		return
	}

	value, err := root.GetNumeric()
	if err != nil {
		t.Errorf("Error on root.GetNumeric(): %s", err)
	}

	if value != float64(1000) {
		t.Errorf(ufmt.Sprintf("value is not matched. expected: 1000, got: %v", value))
	}
}

func TestNode_GetNumeric_With_Unmarshal(t *testing.T) {
	root, err := Unmarshal([]byte(`123`))
	if err != nil {
		t.Errorf("Error on Unmarshal(): %s", err)
		return
	}

	value, err := root.GetNumeric()
	if err != nil {
		t.Errorf("Error on root.GetNumeric(): %s", err)
	}

	if value != float64(123) {
		t.Errorf(ufmt.Sprintf("value is not matched. expected: 123, got: %v", value))
	}
}

func TestNode_GetNumeric_NotSucceed(t *testing.T) {
	tests := []simpleNode{
		{"nil node", (*Node)(nil)},
		{"null node", NullNode("")},
		{"string node", StringNode("", "123")},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if _, err := tt.node.GetNumeric(); err == nil {
				t.Errorf("%s should be an error", tt.name)
			}
		})
	}
}

func TestNode_GetString(t *testing.T) {
	root, err := Unmarshal([]byte(`"123foobar 3456"`))
	if err != nil {
		t.Errorf("Error on Unmarshal(): %s", err)
	}

	value, err := root.GetString()
	if err != nil {
		t.Errorf("Error on root.GetString(): %s", err)
	}

	if value != "123foobar 3456" {
		t.Errorf(ufmt.Sprintf("value is not matched. expected: 123, got: %s", value))
	}
}

func TestNode_GetString_NotSucceed(t *testing.T) {
	tests := []simpleNode{
		{"nil node", (*Node)(nil)},
		{"null node", NullNode("")},
		{"number node", NumberNode("", 123)},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if _, err := tt.node.GetString(); err == nil {
				t.Errorf("%s should be an error", tt.name)
			}
		})
	}
}

func TestNode_MustString(t *testing.T) {
	tests := []struct {
		name string
		data []byte
	}{
		{"foo", []byte(`"foo"`)},
		{"foo bar", []byte(`"foo bar"`)},
		{"", []byte(`""`)},
		{"안녕하세요", []byte(`"안녕하세요"`)},
		{"こんにちは", []byte(`"こんにちは"`)},
		{"你好", []byte(`"你好"`)},
		{"one \"encoded\" string", []byte(`"one \"encoded\" string"`)},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			root, err := Unmarshal(tt.data)
			if err != nil {
				t.Errorf("Error on Unmarshal(): %s", err)
			}

			value := root.MustString()
			if value != tt.name {
				t.Errorf("value is not matched. expected: %s, got: %s", tt.name, value)
			}
		})
	}
}

func TestUnmarshal_Array(t *testing.T) {
	root, err := Unmarshal([]byte(" [1,[\"1\",[1,[1,2,3]]]]\r\n"))
	if err != nil {
		t.Errorf("Error on Unmarshal: %s", err.Error())
	}

	if root == nil {
		t.Errorf("Error on Unmarshal: root is nil")
	}

	if root.Type() != Array {
		t.Errorf("Error on Unmarshal: wrong type")
	}

	array, err := root.GetArray()
	if err != nil {
		t.Errorf("error occurred while getting array, %s", err)
	} else if len(array) != 2 {
		t.Errorf("expected 2 elements, got %d", len(array))
	} else if val, err := array[0].GetNumeric(); err != nil {
		t.Errorf("value of array[0] is not numeric. got: %v", array[0].value)
	} else if val != 1 {
		t.Errorf("Error on array[0].GetNumeric(): expected to be '1', got: %v", val)
	} else if val, err := array[1].GetArray(); err != nil {
		t.Errorf("error occurred while getting array, %s", err.Error())
	} else if len(val) != 2 {
		t.Errorf("Error on array[1].GetArray(): expected 2 elements, got %d", len(val))
	} else if el, err := val[0].GetString(); err != nil {
		t.Errorf("error occurred while getting string, %s", err.Error())
	} else if el != "1" {
		t.Errorf("Error on val[0].GetString(): expected to be '1', got: %s", el)
	}
}

var sampleArr = []byte(`[-1, 2, 3, 4, 5, 6]`)

func TestNode_GetArray(t *testing.T) {
	root, err := Unmarshal(sampleArr)
	if err != nil {
		t.Errorf("Error on Unmarshal(): %s", err)
		return
	}

	array, err := root.GetArray()
	if err != nil {
		t.Errorf("Error on root.GetArray(): %s", err)
	}

	if len(array) != 6 {
		t.Errorf(ufmt.Sprintf("length is not matched. expected: 3, got: %d", len(array)))
	}

	for i, node := range array {
		for j, val := range []int{-1, 2, 3, 4, 5, 6} {
			if i == j {
				if v, err := node.GetNumeric(); err != nil {
					t.Errorf(ufmt.Sprintf("Error on node.GetNumeric(): %s", err))
				} else if v != float64(val) {
					t.Errorf(ufmt.Sprintf("value is not matched. expected: %d, got: %v", val, v))
				}
			}
		}
	}
}

func TestNode_GetArray_NotSucceed(t *testing.T) {
	tests := []simpleNode{
		{"nil node", (*Node)(nil)},
		{"null node", NullNode("")},
		{"number node", NumberNode("", 123)},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if _, err := tt.node.GetArray(); err == nil {
				t.Errorf("%s should be an error", tt.name)
			}
		})
	}
}

func TestNode_IsArray(t *testing.T) {
	root, err := Unmarshal(sampleArr)
	if err != nil {
		t.Errorf("Error on Unmarshal(): %s", err)
		return
	}

	if root.Type() != Array {
		t.Errorf(ufmt.Sprintf("Must be an array. got: %s", root.Type().String()))
	}
}

func TestNode_ArrayEach(t *testing.T) {
	tests := []struct {
		name     string
		json     string
		expected []int
	}{
		{
			name:     "empty array",
			json:     `[]`,
			expected: []int{},
		},
		{
			name:     "single element",
			json:     `[42]`,
			expected: []int{42},
		},
		{
			name:     "multiple elements",
			json:     `[1, 2, 3, 4, 5]`,
			expected: []int{1, 2, 3, 4, 5},
		},
		{
			name:     "multiple elements but all values are same",
			json:     `[1, 1, 1, 1, 1]`,
			expected: []int{1, 1, 1, 1, 1},
		},
		{
			name:     "multiple elements with non-numeric values",
			json:     `["a", "b", "c", "d", "e"]`,
			expected: []int{},
		},
		{
			name:     "non-array node",
			json:     `{"not": "an array"}`,
			expected: []int{},
		},
		{
			name:     "array containing numeric and non-numeric elements",
			json:     `["1", 2, 3, "4", 5, "6"]`,
			expected: []int{2, 3, 5},
		},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			root, err := Unmarshal([]byte(tc.json))
			if err != nil {
				t.Fatalf("Unmarshal failed: %v", err)
			}

			var result []int // callback result
			root.ArrayEach(func(index int, element *Node) {
				if val, err := strconv.Atoi(element.String()); err == nil {
					result = append(result, val)
				}
			})

			if len(result) != len(tc.expected) {
				t.Errorf("%s: expected %d elements, got %d", tc.name, len(tc.expected), len(result))
				return
			}

			for i, val := range result {
				if val != tc.expected[i] {
					t.Errorf("%s: expected value at index %d to be %d, got %d", tc.name, i, tc.expected[i], val)
				}
			}
		})
	}
}

func TestNode_Key(t *testing.T) {
	root, err := Unmarshal([]byte(`{"foo": true, "bar": null, "baz": 123, "biz": [1,2,3]}`))
	if err != nil {
		t.Errorf("Error on Unmarshal(): %s", err.Error())
	}

	obj := root.MustObject()
	for key, node := range obj {
		if key != node.Key() {
			t.Errorf("Key() = %v, want %v", node.Key(), key)
		}
	}

	keys := []string{"foo", "bar", "baz", "biz"}
	for _, key := range keys {
		if obj[key].Key() != key {
			t.Errorf("Key() = %v, want %v", obj[key].Key(), key)
		}
	}

	// TODO: resolve stack overflow
	// if root.MustKey("foo").Clone().Key() != "" {
	// 	t.Errorf("wrong key found for cloned key")
	// }

	if (*Node)(nil).Key() != "" {
		t.Errorf("wrong key found for nil node")
	}
}

func TestNode_Size(t *testing.T) {
	root, err := Unmarshal(sampleArr)
	if err != nil {
		t.Errorf("error occurred while unmarshal")
	}

	size := root.Size()
	if size != 6 {
		t.Errorf(ufmt.Sprintf("Size() must be 6. got: %v", size))
	}

	if (*Node)(nil).Size() != 0 {
		t.Errorf(ufmt.Sprintf("Size() must be 0. got: %v", (*Node)(nil).Size()))
	}
}

func TestNode_Index(t *testing.T) {
	root, err := Unmarshal([]byte(`[1, 2, 3, 4, 5, 6]`))
	if err != nil {
		t.Error("error occurred while unmarshal")
	}

	arr := root.MustArray()
	for i, node := range arr {
		if i != node.Index() {
			t.Errorf(ufmt.Sprintf("Index() must be nil. got: %v", i))
		}
	}
}

func TestNode_Index_NotSucceed(t *testing.T) {
	tests := []struct {
		name string
		node *Node
		want int
	}{
		{"nil node", (*Node)(nil), -1},
		{"null node", NullNode(""), -1},
		{"object node", ObjectNode("", nil), -1},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := tt.node.Index(); got != tt.want {
				t.Errorf("Index() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestNode_GetIndex(t *testing.T) {
	root := Must(Unmarshal([]byte(`[1, 2, 3, 4, 5, 6]`)))
	expected := []int{1, 2, 3, 4, 5, 6}

	if len(expected) != root.Size() {
		t.Errorf("length is not matched. expected: %d, got: %d", len(expected), root.Size())
	}

	// TODO: if length exceeds, stack overflow occurs. need to fix
	for i, v := range expected {
		val, err := root.GetIndex(i)
		if err != nil {
			t.Errorf("error occurred while getting index %d, %s", i, err)
		}

		if val.MustNumeric() != float64(v) {
			t.Errorf("value is not matched. expected: %d, got: %v", v, val.MustNumeric())
		}
	}
}

func TestNode_GetIndex_InputIndex_Exceed_Original_Node_Index(t *testing.T) {
	root, err := Unmarshal([]byte(`[1, 2, 3, 4, 5, 6]`))
	if err != nil {
		t.Errorf("error occurred while unmarshal")
	}

	_, err = root.GetIndex(10)
	if err == nil {
		t.Errorf("GetIndex should return error")
	}
}

func TestNode_DeleteIndex(t *testing.T) {
	tests := []struct {
		name     string
		expected string
		index    int
		ok       bool
	}{
		{`null`, ``, 0, false},
		{`1`, ``, 0, false},
		{`{}`, ``, 0, false},
		{`{"foo":"bar"}`, ``, 0, false},
		{`true`, ``, 0, false},
		{`[]`, ``, 0, false},
		{`[]`, ``, -1, false},
		{`[1]`, `[]`, 0, true},
		{`[{}]`, `[]`, 0, true},
		{`[{}, [], 42]`, `[{}, []]`, -1, true},
		{`[{}, [], 42]`, `[[], 42]`, 0, true},
		{`[{}, [], 42]`, `[{}, 42]`, 1, true},
		{`[{}, [], 42]`, `[{}, []]`, 2, true},
		{`[{}, [], 42]`, ``, 10, false},
		{`[{}, [], 42]`, ``, -10, false},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			root := Must(Unmarshal([]byte(tt.name)))
			err := root.DeleteIndex(tt.index)
			if err != nil && tt.ok {
				t.Errorf("DeleteIndex returns error: %v", err)
			}
		})
	}
}

func TestNode_GetKey(t *testing.T) {
	root, err := Unmarshal([]byte(`{"foo": true, "bar": null}`))
	if err != nil {
		t.Error("error occurred while unmarshal")
	}

	value, err := root.GetKey("foo")
	if err != nil {
		t.Errorf("error occurred while getting key, %s", err)
	}

	if value.MustBool() != true {
		t.Errorf("value is not matched. expected: true, got: %v", value.MustBool())
	}

	value, err = root.GetKey("bar")
	if err != nil {
		t.Errorf("error occurred while getting key, %s", err)
	}

	_, err = root.GetKey("baz")
	if err == nil {
		t.Errorf("key baz is not exist. must be failed")
	}

	if value.MustNull() != nil {
		t.Errorf("value is not matched. expected: nil, got: %v", value.MustNull())
	}
}

func TestNode_GetKey_NotSucceed(t *testing.T) {
	tests := []simpleNode{
		{"nil node", (*Node)(nil)},
		{"null node", NullNode("")},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if _, err := tt.node.GetKey(""); err == nil {
				t.Errorf("%s should be an error", tt.name)
			}
		})
	}
}

func TestNode_GetUniqueKeyList(t *testing.T) {
	tests := []struct {
		name     string
		json     string
		expected []string
	}{
		{
			name:     "simple foo/bar",
			json:     `{"foo": true, "bar": null}`,
			expected: []string{"foo", "bar"},
		},
		{
			name:     "empty object",
			json:     `{}`,
			expected: []string{},
		},
		{
			name: "nested object",
			json: `{
				"outer": {
					"inner": {
						"key": "value"
					},
					"array": [1, 2, 3]
				},
				"another": "item"
			}`,
			expected: []string{"outer", "inner", "key", "array", "another"},
		},
		{
			name: "complex object",
			json: `{
				"Image": {
					"Width": 800,
					"Height": 600,
					"Title": "View from 15th Floor",
					"Thumbnail": {
						"Url": "http://www.example.com/image/481989943",
						"Height": 125,
						"Width": 100
					},
					"Animated": false,
					"IDs": [116, 943, 234, 38793]
				}
			}`,
			expected: []string{"Image", "Width", "Height", "Title", "Thumbnail", "Url", "Animated", "IDs"},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			root, err := Unmarshal([]byte(tt.json))
			if err != nil {
				t.Errorf("error occurred while unmarshal")
			}

			value := root.UniqueKeyLists()
			if len(value) != len(tt.expected) {
				t.Errorf("%s length must be %v. got: %v. retrieved keys: %s", tt.name, len(tt.expected), len(value), value)
			}

			for _, key := range value {
				if !contains(tt.expected, key) {
					t.Errorf("EachKey() must be in %v. got: %v", tt.expected, key)
				}
			}
		})
	}
}

// TODO: resolve stack overflow
func TestNode_IsEmpty(t *testing.T) {
	tests := []struct {
		name     string
		node     *Node
		expected bool
	}{
		{"nil node", (*Node)(nil), false}, // nil node is not empty.
		// {"null node", NullNode(""), true},
		{"empty object", ObjectNode("", nil), true},
		{"empty array", ArrayNode("", nil), true},
		{"non-empty object", ObjectNode("", map[string]*Node{"foo": BoolNode("foo", true)}), false},
		{"non-empty array", ArrayNode("", []*Node{BoolNode("0", true)}), false},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := tt.node.Empty(); got != tt.expected {
				t.Errorf("%s = %v, want %v", tt.name, got, tt.expected)
			}
		})
	}
}

func TestNode_Index_EmptyList(t *testing.T) {
	root, err := Unmarshal([]byte(`[]`))
	if err != nil {
		t.Errorf("error occurred while unmarshal")
	}

	array := root.MustArray()
	for i, node := range array {
		if i != node.Index() {
			t.Errorf(ufmt.Sprintf("Index() must be nil. got: %v", i))
		}
	}
}

func TestNode_GetObject(t *testing.T) {
	root, err := Unmarshal([]byte(`{"foo": true,"bar": null}`))
	if err != nil {
		t.Errorf("Error on Unmarshal(): %s", err.Error())
		return
	}

	value, err := root.GetObject()
	if err != nil {
		t.Errorf("Error on root.GetObject(): %s", err.Error())
	}

	if _, ok := value["foo"]; !ok {
		t.Errorf("root.GetObject() is corrupted: foo")
	}

	if _, ok := value["bar"]; !ok {
		t.Errorf("root.GetObject() is corrupted: bar")
	}
}

func TestNode_GetObject_NotSucceed(t *testing.T) {
	tests := []simpleNode{
		{"nil node", (*Node)(nil)},
		{"get object from null node", NullNode("")},
		{"not object node", NumberNode("", 123)},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if _, err := tt.node.GetObject(); err == nil {
				t.Errorf("%s should be an error", tt.name)
			}
		})
	}
}

func TestNode_ObjectEach(t *testing.T) {
	tests := []struct {
		name     string
		json     string
		expected map[string]int
	}{
		{
			name:     "empty object",
			json:     `{}`,
			expected: make(map[string]int),
		},
		{
			name:     "single key-value pair",
			json:     `{"key": 42}`,
			expected: map[string]int{"key": 42},
		},
		{
			name:     "multiple key-value pairs",
			json:     `{"one": 1, "two": 2, "three": 3}`,
			expected: map[string]int{"one": 1, "two": 2, "three": 3},
		},
		{
			name:     "multiple key-value pairs with some non-numeric values",
			json:     `{"one": 1, "two": "2", "three": 3, "four": "4"}`,
			expected: map[string]int{"one": 1, "three": 3},
		},
		{
			name:     "non-object node",
			json:     `["not", "an", "object"]`,
			expected: make(map[string]int),
		},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			root, err := Unmarshal([]byte(tc.json))
			if err != nil {
				t.Fatalf("Unmarshal failed: %v", err)
			}

			result := make(map[string]int)
			root.ObjectEach(func(key string, value *Node) {
				// extract integer values from the object
				if val, err := strconv.Atoi(value.String()); err == nil {
					result[key] = val
				}
			})

			if len(result) != len(tc.expected) {
				t.Errorf("%s: expected %d key-value pairs, got %d", tc.name, len(tc.expected), len(result))
				return
			}

			for key, val := range tc.expected {
				if result[key] != val {
					t.Errorf("%s: expected value for key %s to be %d, got %d", tc.name, key, val, result[key])
				}
			}
		})
	}
}

func Example_TestNode_Must() {
	data := []byte(`{
        "Image": {
            "Width":  800,
            "Height": 600,
            "Title":  "View from 15th Floor",
            "Thumbnail": {
                "Url":    "http://www.example.com/image/481989943",
                "Height": 125,
                "Width":  100
            },
            "Animated" : false,
            "IDs": [116, 943, 234, 38793]
        }
    }`)

	root := Must(Unmarshal(data))
	if root.Size() != 1 {
		ufmt.Printf("root.Size() must be 1. got: %v\n", root.Size())
		return
	}

	ufmt.Printf("Object has %d inheritors inside\n", root.Size())
	// Output:
	// Object has 1 inheritors inside
}

// Calculate AVG price from different types of objects, JSON from: https://goessner.net/articles/JsonPath/index.html#e3
func TestExampleUnmarshal(t *testing.T) {
	data := []byte(`{ "store": {
    "book": [ 
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      { "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      { "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": { "color": "red",
      "price": 19.95
    },
    "tools": null
  }
}`)

	root, err := Unmarshal(data)
	if err != nil {
		t.Errorf("error occurred when unmarshal")
	}

	store := root.MustKey("store").MustObject()

	var prices float64
	size := 0
	for _, objects := range store {
		if objects.IsArray() && objects.Size() > 0 {
			size += objects.Size()
			for _, object := range objects.MustArray() {
				prices += object.MustKey("price").MustNumeric()
			}
		} else if objects.IsObject() && objects.HasKey("price") {
			size++
			prices += objects.MustKey("price").MustNumeric()
		}
	}

	result := int(prices / float64(size))
	ufmt.Sprintf("AVG price: %d", result)
}

func TestNode_ExampleMust_panic(t *testing.T) {
	defer func() {
		if r := recover(); r == nil {
			t.Errorf("The code did not panic")
		}
	}()
	data := []byte(`{]`)
	root := Must(Unmarshal(data))
	ufmt.Sprintf("Object has %d inheritors inside", root.Size())
}

func TestNode_Path(t *testing.T) {
	data := []byte(`{
        "Image": {
            "Width":  800,
            "Height": 600,
            "Title":  "View from 15th Floor",
            "Thumbnail": {
                "Url":    "http://www.example.com/image/481989943",
                "Height": 125,
                "Width":  100
            },
            "Animated" : false,
            "IDs": [116, 943, 234, 38793]
          }
      }`)

	root, err := Unmarshal(data)
	if err != nil {
		t.Errorf("Error on Unmarshal(): %s", err.Error())
		return
	}

	if root.Path() != "$" {
		t.Errorf("Wrong root.Path()")
	}

	element := root.MustKey("Image").MustKey("Thumbnail").MustKey("Url")
	if element.Path() != "$['Image']['Thumbnail']['Url']" {
		t.Errorf("Wrong path found: %s", element.Path())
	}

	if (*Node)(nil).Path() != "" {
		t.Errorf("Wrong (nil).Path()")
	}
}

func TestNode_Path2(t *testing.T) {
	tests := []struct {
		name string
		node *Node
		want string
	}{
		{
			name: "Node with key",
			node: &Node{
				prev: &Node{},
				key:  func() *string { s := "key"; return &s }(),
			},
			want: "$['key']",
		},
		{
			name: "Node with index",
			node: &Node{
				prev:  &Node{},
				index: func() *int { i := 1; return &i }(),
			},
			want: "$[1]",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := tt.node.Path(); got != tt.want {
				t.Errorf("Path() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestNode_Root(t *testing.T) {
	root := &Node{}
	child := &Node{prev: root}
	grandChild := &Node{prev: child}

	tests := []struct {
		name string
		node *Node
		want *Node
	}{
		{
			name: "Root node",
			node: root,
			want: root,
		},
		{
			name: "Child node",
			node: child,
			want: root,
		},
		{
			name: "Grandchild node",
			node: grandChild,
			want: root,
		},
		{
			name: "Node is nil",
			node: nil,
			want: nil,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := tt.node.root(); got != tt.want {
				t.Errorf("root() = %v, want %v", got, tt.want)
			}
		})
	}
}

func contains(slice []string, item string) bool {
	for _, a := range slice {
		if a == item {
			return true
		}
	}

	return false
}

// ignore the sequence of keys by ordering them.
// need to avoid import encoding/json and reflect package.
// because gno does not support them for now.
// TODO: use encoding/json to compare the result after if possible in gno.
func isSameObject(a, b string) bool {
	aPairs := strings.Split(strings.Trim(a, "{}"), ",")
	bPairs := strings.Split(strings.Trim(b, "{}"), ",")

	aMap := make(map[string]string)
	bMap := make(map[string]string)
	for _, pair := range aPairs {
		kv := strings.Split(pair, ":")
		key := strings.Trim(kv[0], `"`)
		value := strings.Trim(kv[1], `"`)
		aMap[key] = value
	}
	for _, pair := range bPairs {
		kv := strings.Split(pair, ":")
		key := strings.Trim(kv[0], `"`)
		value := strings.Trim(kv[1], `"`)
		bMap[key] = value
	}

	aKeys := make([]string, 0, len(aMap))
	bKeys := make([]string, 0, len(bMap))
	for k := range aMap {
		aKeys = append(aKeys, k)
	}

	for k := range bMap {
		bKeys = append(bKeys, k)
	}

	sort.Strings(aKeys)
	sort.Strings(bKeys)

	if len(aKeys) != len(bKeys) {
		return false
	}

	for i := range aKeys {
		if aKeys[i] != bKeys[i] {
			return false
		}

		if aMap[aKeys[i]] != bMap[bKeys[i]] {
			return false
		}
	}

	return true
}

func compareNodes(n1, n2 *Node) bool {
	if n1 == nil || n2 == nil {
		return n1 == n2
	}

	if n1.key != n2.key {
		return false
	}

	if !bytes.Equal(n1.data, n2.data) {
		return false
	}

	if n1.index != n2.index {
		return false
	}

	if n1.borders != n2.borders {
		return false
	}

	if n1.modified != n2.modified {
		return false
	}

	if n1.nodeType != n2.nodeType {
		return false
	}

	if !compareNodes(n1.prev, n2.prev) {
		return false
	}

	if len(n1.next) != len(n2.next) {
		return false
	}

	for k, v := range n1.next {
		if !compareNodes(v, n2.next[k]) {
			return false
		}
	}

	return true
}

parser.gno

package json

import (
	"bytes"
)

const (
	unescapeStackBufSize = 64
	absMinInt64          = 1 << 63
	maxInt64             = absMinInt64 - 1
	maxUint64            = 1<<64 - 1
)

// PaseStringLiteral parses a string from the given byte slice.
func ParseStringLiteral(data []byte) (string, error) {
	var buf [unescapeStackBufSize]byte

	bf, err := Unescape(data, buf[:])
	if err != nil {
		return "", errInvalidStringInput
	}

	return string(bf), nil
}

// ParseBoolLiteral parses a boolean value from the given byte slice.
func ParseBoolLiteral(data []byte) (bool, error) {
	switch {
	case bytes.Equal(data, trueLiteral):
		return true, nil
	case bytes.Equal(data, falseLiteral):
		return false, nil
	default:
		return false, errMalformedBooleanValue
	}
}

parser_test.gno

package json

import "testing"

func TestParseStringLiteral(t *testing.T) {
	tests := []struct {
		input    string
		expected string
		isError  bool
	}{
		{`"Hello, World!"`, "\"Hello, World!\"", false},
		{`\uFF11`, "\uFF11", false},
		{`\uFFFF`, "\uFFFF", false},
		{`true`, "true", false},
		{`false`, "false", false},
		{`\uDF00`, "", true},
	}

	for i, tt := range tests {
		s, err := ParseStringLiteral([]byte(tt.input))

		if !tt.isError && err != nil {
			t.Errorf("%d. unexpected error: %s", i, err)
		}

		if tt.isError && err == nil {
			t.Errorf("%d. expected error, but not error", i)
		}

		if s != tt.expected {
			t.Errorf("%d. expected=%s, but actual=%s", i, tt.expected, s)
		}
	}
}

func TestParseBoolLiteral(t *testing.T) {
	tests := []struct {
		input    string
		expected bool
		isError  bool
	}{
		{`true`, true, false},
		{`false`, false, false},
		{`TRUE`, false, true},
		{`FALSE`, false, true},
		{`foo`, false, true},
		{`"true"`, false, true},
		{`"false"`, false, true},
	}

	for i, tt := range tests {
		b, err := ParseBoolLiteral([]byte(tt.input))

		if !tt.isError && err != nil {
			t.Errorf("%d. unexpected error: %s", i, err)
		}

		if tt.isError && err == nil {
			t.Errorf("%d. expected error, but not error", i)
		}

		if b != tt.expected {
			t.Errorf("%d. expected=%t, but actual=%t", i, tt.expected, b)
		}
	}
}

path.gno

package json

import (
	"errors"
)

// ParsePath takes a JSONPath string and returns a slice of strings representing the path segments.
func ParsePath(path string) ([]string, error) {
	buf := newBuffer([]byte(path))
	result := make([]string, 0)

	for {
		b, err := buf.current()
		if err != nil {
			break
		}

		switch {
		case b == dollarSign || b == atSign:
			result = append(result, string(b))
			buf.step()

		case b == dot:
			buf.step()

			if next, _ := buf.current(); next == dot {
				buf.step()
				result = append(result, "..")

				extractNextSegment(buf, &result)
			} else {
				extractNextSegment(buf, &result)
			}

		case b == bracketOpen:
			start := buf.index
			buf.step()

			for {
				if buf.index >= buf.length || buf.data[buf.index] == bracketClose {
					break
				}

				buf.step()
			}

			if buf.index >= buf.length {
				return nil, errors.New("unexpected end of path")
			}

			segment := string(buf.sliceFromIndices(start+1, buf.index))
			result = append(result, segment)

			buf.step()

		default:
			buf.step()
		}
	}

	return result, nil
}

// extractNextSegment extracts the segment from the current index
// to the next significant character and adds it to the resulting slice.
func extractNextSegment(buf *buffer, result *[]string) {
	start := buf.index
	buf.skipToNextSignificantToken()

	if buf.index <= start {
		return
	}

	segment := string(buf.sliceFromIndices(start, buf.index))
	if segment != "" {
		*result = append(*result, segment)
	}
}

path_test.gno

package json

import "testing"

func TestParseJSONPath(t *testing.T) {
	tests := []struct {
		name     string
		path     string
		expected []string
	}{
		{name: "Empty string path", path: "", expected: []string{}},
		{name: "Root only path", path: "$", expected: []string{"$"}},
		{name: "Root with dot path", path: "$.", expected: []string{"$"}},
		{name: "All objects in path", path: "$..", expected: []string{"$", ".."}},
		{name: "Only children in path", path: "$.*", expected: []string{"$", "*"}},
		{name: "All objects' children in path", path: "$..*", expected: []string{"$", "..", "*"}},
		{name: "Simple dot notation path", path: "$.root.element", expected: []string{"$", "root", "element"}},
		{name: "Complex dot notation path with wildcard", path: "$.root.*.element", expected: []string{"$", "root", "*", "element"}},
		{name: "Path with array wildcard", path: "$.phoneNumbers[*].type", expected: []string{"$", "phoneNumbers", "*", "type"}},
		{name: "Path with filter expression", path: "$.store.book[?(@.price < 10)].title", expected: []string{"$", "store", "book", "?(@.price < 10)", "title"}},
		{name: "Path with formula", path: "$..phoneNumbers..('ty' + 'pe')", expected: []string{"$", "..", "phoneNumbers", "..", "('ty' + 'pe')"}},
		{name: "Simple bracket notation path", path: "$['root']['element']", expected: []string{"$", "'root'", "'element'"}},
		{name: "Complex bracket notation path with wildcard", path: "$['root'][*]['element']", expected: []string{"$", "'root'", "*", "'element'"}},
		{name: "Bracket notation path with integer index", path: "$['store']['book'][0]['title']", expected: []string{"$", "'store'", "'book'", "0", "'title'"}},
		{name: "Complex path with wildcard in bracket notation", path: "$['root'].*['element']", expected: []string{"$", "'root'", "*", "'element'"}},
		{name: "Mixed notation path with dot after bracket", path: "$.['root'].*.['element']", expected: []string{"$", "'root'", "*", "'element'"}},
		{name: "Mixed notation path with dot before bracket", path: "$['root'].*.['element']", expected: []string{"$", "'root'", "*", "'element'"}},
		{name: "Single character path with root", path: "$.a", expected: []string{"$", "a"}},
		{name: "Multiple characters path with root", path: "$.abc", expected: []string{"$", "abc"}},
		{name: "Multiple segments path with root", path: "$.a.b.c", expected: []string{"$", "a", "b", "c"}},
		{name: "Multiple segments path with wildcard and root", path: "$.a.*.c", expected: []string{"$", "a", "*", "c"}},
		{name: "Multiple segments path with filter and root", path: "$.a[?(@.b == 'c')].d", expected: []string{"$", "a", "?(@.b == 'c')", "d"}},
		{name: "Complex path with multiple filters", path: "$.a[?(@.b == 'c')].d[?(@.e == 'f')].g", expected: []string{"$", "a", "?(@.b == 'c')", "d", "?(@.e == 'f')", "g"}},
		{name: "Complex path with multiple filters and wildcards", path: "$.a[?(@.b == 'c')].*.d[?(@.e == 'f')].g", expected: []string{"$", "a", "?(@.b == 'c')", "*", "d", "?(@.e == 'f')", "g"}},
		{name: "Path with array index and root", path: "$.a[0].b", expected: []string{"$", "a", "0", "b"}},
		{name: "Path with multiple array indices and root", path: "$.a[0].b[1].c", expected: []string{"$", "a", "0", "b", "1", "c"}},
		{name: "Path with array index, wildcard and root", path: "$.a[0].*.c", expected: []string{"$", "a", "0", "*", "c"}},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			reult, _ := ParsePath(tt.path)
			if !isEqualSlice(reult, tt.expected) {
				t.Errorf("ParsePath(%s) expected: %v, got: %v", tt.path, tt.expected, reult)
			}
		})
	}
}

func isEqualSlice(a, b []string) bool {
	if len(a) != len(b) {
		return false
	}

	for i, v := range a {
		if v != b[i] {
			return false
		}
	}

	return true
}

token.gno

package json

const (
	bracketOpen    = '['
	bracketClose   = ']'
	parenOpen      = '('
	parenClose     = ')'
	curlyOpen      = '{'
	curlyClose     = '}'
	comma          = ','
	dot            = '.'
	colon          = ':'
	backTick       = '`'
	singleQuote    = '\''
	doubleQuote    = '"'
	emptyString    = ""
	whiteSpace     = ' '
	plus           = '+'
	minus          = '-'
	aesterisk      = '*'
	bang           = '!'
	question       = '?'
	newLine        = '\n'
	tab            = '\t'
	carriageReturn = '\r'
	formFeed       = '\f'
	backSpace      = '\b'
	slash          = '/'
	backSlash      = '\\'
	underScore     = '_'
	dollarSign     = '$'
	atSign         = '@'
	andSign        = '&'
	orSign         = '|'
)

var (
	trueLiteral  = []byte("true")
	falseLiteral = []byte("false")
	nullLiteral  = []byte("null")
)

type ValueType int

const (
	NotExist ValueType = iota
	String
	Number
	Float
	Object
	Array
	Boolean
	Null
	Unknown
)

func (v ValueType) String() string {
	switch v {
	case NotExist:
		return "not-exist"
	case String:
		return "string"
	case Number:
		return "number"
	case Object:
		return "object"
	case Array:
		return "array"
	case Boolean:
		return "boolean"
	case Null:
		return "null"
	default:
		return "unknown"
	}
}