Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PoC: VMKeeper.QueryEvalJSON #444

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
226 changes: 226 additions & 0 deletions pkgs/encoding/json/encode.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,226 @@
package json

import (
"bytes"
"strconv"
"sync"

gno "github.com/gnolang/gno/pkgs/gnolang"
)

// Marshal returns the JSON encoding of v.
func Marshal(s gno.Store, vs ...gno.TypedValue) ([]byte, error) {
e := newEncodeState()
defer encodeStatePool.Put(e)

if len(vs) > 1 {
e.WriteByte('[')
}

for i, v := range vs {
if i > 0 {
e.WriteByte(',')
}
err := e.marshal(v, s, encOpts{escapeHTML: true})
if err != nil {
return nil, err
}
}

if len(vs) > 1 {
e.WriteByte(']')
}

buf := append([]byte(nil), e.Bytes()...)

return buf, nil
}

type encodeState struct {
bytes.Buffer // accumulated output
}

var encodeStatePool sync.Pool

func newEncodeState() *encodeState {
if v := encodeStatePool.Get(); v != nil {
e := v.(*encodeState)
e.Reset()
return e
}

return &encodeState{}
}

// jsonError is an error wrapper type for internal use only.
type jsonError struct{ error }

func (e *encodeState) marshal(tv gno.TypedValue, s gno.Store, opts encOpts) (err error) {
defer func() {
if r := recover(); r != nil {
if je, ok := r.(jsonError); ok {
err = je.error
} else {
panic(r)
}
}
}()

v := newValue(tv, s)
valueEncoder(v)(e, v, opts)
return nil
}

type encOpts struct {
escapeHTML bool
quoted bool
}

type encoderFunc func(e *encodeState, v Value, opts encOpts)

func valueEncoder(v Value) encoderFunc {
switch v.Kind() {
case gno.InvalidKind:
return invalidValueEncoder
case gno.BoolKind:
return boolEncoder
case gno.IntKind, gno.Int8Kind, gno.Int16Kind, gno.Int32Kind, gno.Int64Kind:
return intEncoder
case gno.UintKind, gno.Uint8Kind, gno.Uint16Kind, gno.Uint32Kind, gno.Uint64Kind:
return uintEncoder
case gno.StringKind:
return stringEncoder
case gno.ArrayKind:
return arrayEncoder
case gno.SliceKind:
return sliceEncoder
case gno.StructKind:
return structEncoder
case gno.PointerKind:
return ptrEncoder
case gno.InterfaceKind:
return interfaceEncoder
default:
panic("unreachable") //todo: unsupportedTypeEncoder?
}
}

func invalidValueEncoder(e *encodeState, v Value, _ encOpts) {
e.WriteString("null")
}

func boolEncoder(e *encodeState, v Value, opts encOpts) {
if opts.quoted {
e.WriteByte('"')
}
if v.Bool() {
e.WriteString("true")
} else {
e.WriteString("false")
}
if opts.quoted {
e.WriteByte('"')
}
}

func stringEncoder(e *encodeState, v Value, opts encOpts) {
e.WriteByte('"')
e.WriteString(v.String())
e.WriteByte('"')
}

func intEncoder(e *encodeState, v Value, opts encOpts) {
if opts.quoted {
e.WriteByte('"')
}

e.WriteString(strconv.FormatInt(v.Int(), 10))

if opts.quoted {
e.WriteByte('"')
}
}

func uintEncoder(e *encodeState, v Value, opts encOpts) {
if opts.quoted {
e.WriteByte('"')
}

e.WriteString(strconv.FormatUint(v.Uint(), 10))

if opts.quoted {
e.WriteByte('"')
}
}

func arrayEncoder(e *encodeState, v Value, opts encOpts) {
e.WriteByte('[')

for i := 0; i < v.Len(); i++ {
if i > 0 {
e.WriteByte(',')
}
elem := v.Index(i)
valueEncoder(elem)(e, elem, opts)
}

e.WriteByte(']')
}

func sliceEncoder(e *encodeState, v Value, opts encOpts) {
e.WriteByte('[')

for i := 0; i < v.Len(); i++ {
if i > 0 {
e.WriteByte(',')
}
elem := v.Index(i)
valueEncoder(elem)(e, elem, opts)
}

e.WriteByte(']')
}

func structEncoder(e *encodeState, v Value, opts encOpts) {
next := byte('{')

fields := v.StructFields()

for i := 0; i < len(fields); i++ {
field := fields[i]
if field.IsZero() {
continue
}
e.WriteByte(next)
next = ','

e.WriteByte('"')
e.WriteString(field.Name())
e.WriteByte('"')
e.WriteByte(':')

valueEncoder(field.Value())(e, field.Value(), opts)
}

if next == '{' {
e.WriteString("{}")
} else {
e.WriteByte('}')
}
}

func ptrEncoder(e *encodeState, v Value, opts encOpts) {
if v.IsNil() {
e.WriteString("null")
return
}
valueEncoder(v.Elem())(e, v.Elem(), opts)
}

func interfaceEncoder(e *encodeState, v Value, opts encOpts) {
if v.IsNil() {
e.WriteString("null")
return
}
valueEncoder(v.Elem())(e, v.Elem(), opts)
}
91 changes: 91 additions & 0 deletions pkgs/encoding/json/encode_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package json

import (
"reflect"
"testing"

gno "github.com/gnolang/gno/pkgs/gnolang"
)

func TestMarshal(t *testing.T) {
var tests = []struct {
name string
in any
want string
}{
{"nil", nil, "null"},
{"bool", true, "true"},
{"bool", false, "false"},
{"int", int(0), "0"},
{"int", int8(10), "10"},
{"int", int16(100), "100"},
{"int", int32(1000), "1000"},
{"int", int64(10000), "10000"},
{"array", [2]int{1, 2}, "[1,2]"},
{"slice", make([]int, 0), "[]"},
{"string", "hello", "\"hello\""},
{"struct", struct {
A int
B string
c string
}{23, "skidoo", "aa"}, `{"A":23,"B":"skidoo"}`},
{"struct-tag", struct {
A int `json:"a"`
B string
}{23, "skidoo"}, `{"a":23,"B":"skidoo"}`},
{"pointer", &struct {
A int
B string
}{23, "skidoo"}, `{"A":23,"B":"skidoo"}`},
//{"map", map[string]int{"one": 1, "two": 2}, `{"one":1,"two":2}`},
}
for _, tt := range tests {
testMarshal := func(t *testing.T, fn func(v any) (gno.TypedValue, gno.Store)) {
v, s := fn(tt.in)

/*
if v.T != nil {
fmt.Printf("t: %T v: %T k: %v\n", v.T, v.V, v.T.Kind())
}
*/

got, err := Marshal(s, v)
//fmt.Printf("got: %s\n", string(got))
if err != nil {
t.Errorf("Marshal(%v) error: %v", tt.in, err)
}
if string(got) != tt.want {
t.Errorf("Marshal(%v) = %v, want %v", tt.in, string(got), tt.want)
}
t.Logf("Marshal(%v) = %v", tt.in, string(got))
}

t.Run(tt.name, func(t *testing.T) {
testMarshal(t, go2GnoTypedValue)
})
t.Run(tt.name+"Native", func(t *testing.T) {
testMarshal(t, go2GnoTypedValueNative)
})
}
}

func go2GnoTypedValueNative(v any) (gno.TypedValue, gno.Store) {
//alloc := gno.NewAllocator(0)
alloc := (*gno.Allocator)(nil)
store := gno.NewStore(alloc, nil, nil)
rv := reflect.ValueOf(v)
btv := gno.Go2GnoNativeValue(alloc, rv)
return btv, store
}

func go2GnoTypedValue(v any) (gno.TypedValue, gno.Store) {
alloc := (*gno.Allocator)(nil)
//alloc := gno.NewAllocator(0)
store := gno.NewStore(alloc, nil, nil)
if v == nil {
return gno.TypedValue{}, store
}
rv := reflect.ValueOf(v)
btv := gno.Go2GnoValue(alloc, store, rv)
return btv, store
}
Loading