francoispqt / gojay

high performance JSON encoder/decoder with stream API for Golang
MIT License
2.11k stars 113 forks source link

prevent from panic encoding scalar types #157

Open Alma-media opened 3 years ago

Alma-media commented 3 years ago

The encoder panics while encoding values explicitly since there is no previous rune:

package main

import (
    "strings"

    "github.com/francoispqt/gojay"
)

func main() {
    var (
        buff    strings.Builder
        encoder = gojay.BorrowEncoder(&buff)
    )
    defer encoder.Release()

    encoder.Float64(42) // or AddFloat ... AddXxxx ...
}

the output will be:

panic: runtime error: index out of range [-1]

goroutine 1 [running]:
github.com/francoispqt/gojay.(*Encoder).getPreviousRune(...)
    /tmp/gopath957066451/pkg/mod/github.com/francoispqt/gojay@v1.2.13/encode.go:201
github.com/francoispqt/gojay.(*Encoder).Float64(0xc0000bb920, 0x4045000000000000)
    /tmp/gopath957066451/pkg/mod/github.com/francoispqt/gojay@v1.2.13/encode_number_float.go:124 +0x205
github.com/francoispqt/gojay.(*Encoder).Float(...)
    /tmp/gopath957066451/pkg/mod/github.com/francoispqt/gojay@v1.2.13/encode_number_float.go:61
github.com/francoispqt/gojay.(*Encoder).AddFloat64(...)
    /tmp/gopath957066451/pkg/mod/github.com/francoispqt/gojay@v1.2.13/encode_number_float.go:112
main.main()
    /tmp/sandbox969752132/prog.go:17 +0x85

fix: check the length of the buffer in order to avoid panics