go-json/decode_string.go

64 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{}
}
2020-05-06 20:37:29 +03:00
func (d *stringDecoder) decode(buf []byte, cursor int, p uintptr) (int, error) {
bytes, c, err := d.decodeByte(buf, cursor)
2020-04-23 19:39:20 +03:00
if err != nil {
2020-05-06 20:37:29 +03:00
return 0, err
2020-04-23 19:39:20 +03:00
}
2020-05-06 20:37:29 +03:00
cursor = c
2020-04-23 19:39:20 +03:00
*(*string)(unsafe.Pointer(p)) = *(*string)(unsafe.Pointer(&bytes))
2020-05-06 20:37:29 +03:00
return cursor, nil
2020-04-23 19:39:20 +03:00
}
2020-05-06 20:37:29 +03:00
func (d *stringDecoder) decodeByte(buf []byte, cursor int) ([]byte, int, error) {
buflen := len(buf)
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++
2020-05-06 20:37:29 +03:00
return literal, cursor, nil
2020-04-24 08:07:33 +03:00
}
}
2020-05-06 20:37:29 +03:00
return nil, 0, errors.New("unexpected error string")
2020-04-26 08:59:45 +03:00
case 'n':
2020-05-06 20:37:29 +03:00
if cursor+3 >= buflen {
return nil, 0, errors.New("unexpected error. invalid bool character")
2020-04-26 08:59:45 +03:00
}
if buf[cursor+1] != 'u' {
2020-05-06 20:37:29 +03:00
return nil, 0, errors.New("unexpected error. invalid bool character")
2020-04-26 08:59:45 +03:00
}
if buf[cursor+2] != 'l' {
2020-05-06 20:37:29 +03:00
return nil, 0, errors.New("unexpected error. invalid bool character")
2020-04-26 08:59:45 +03:00
}
if buf[cursor+3] != 'l' {
2020-05-06 20:37:29 +03:00
return nil, 0, errors.New("unexpected error. invalid bool character")
2020-04-26 08:59:45 +03:00
}
2020-05-06 20:37:29 +03:00
cursor += 5
return []byte{}, cursor, nil
2020-04-23 19:39:20 +03:00
}
}
2020-05-06 20:37:29 +03:00
return nil, 0, errors.New("unexpected error key delimiter")
2020-04-23 19:39:20 +03:00
}