go-json/decode_string.go

66 lines
1.4 KiB
Go
Raw Normal View History

2020-04-23 19:39:20 +03:00
package json
import (
"errors"
"unsafe"
)
type stringDecoder struct {
}
func newStringDecoder() *stringDecoder {
return &stringDecoder{}
}
func (d *stringDecoder) decode(ctx *context, p uintptr) error {
bytes, err := d.decodeByte(ctx)
if err != nil {
return err
}
*(*string)(unsafe.Pointer(p)) = *(*string)(unsafe.Pointer(&bytes))
return nil
}
func (d *stringDecoder) decodeByte(ctx *context) ([]byte, error) {
buf := ctx.buf
buflen := ctx.buflen
2020-04-24 08:07:33 +03:00
cursor := ctx.cursor
2020-04-23 19:39:20 +03:00
for ; cursor < buflen; cursor++ {
2020-04-24 08:07:33 +03:00
switch buf[cursor] {
case ' ', '\n', '\t', '\r':
2020-04-23 19:39:20 +03:00
continue
2020-04-24 08:07:33 +03:00
case '"':
cursor++
start := cursor
for ; cursor < buflen; cursor++ {
switch buf[cursor] {
case '\\':
2020-04-24 08:07:33 +03:00
cursor++
case '"':
2020-04-24 08:07:33 +03:00
literal := buf[start:cursor]
cursor++
ctx.cursor = cursor
return literal, nil
}
}
return nil, errors.New("unexpected error string")
2020-04-26 08:59:45 +03:00
case 'n':
if cursor+3 >= ctx.buflen {
return nil, errors.New("unexpected error. invalid bool character")
}
if buf[cursor+1] != 'u' {
return nil, errors.New("unexpected error. invalid bool character")
}
if buf[cursor+2] != 'l' {
return nil, errors.New("unexpected error. invalid bool character")
}
if buf[cursor+3] != 'l' {
return nil, errors.New("unexpected error. invalid bool character")
}
ctx.cursor += 5
return []byte{}, nil
2020-04-23 19:39:20 +03:00
}
}
2020-04-24 08:07:33 +03:00
return nil, errors.New("unexpected error key delimiter")
2020-04-23 19:39:20 +03:00
}