1
0
mirror of https://github.com/json-iterator/go.git synced 2025-05-19 21:53:05 +02:00

simplify read string, and support null

This commit is contained in:
Tao Wen 2017-05-23 18:32:39 +08:00
parent 5488fde97f
commit 7e046e6aa7
2 changed files with 16 additions and 38 deletions

View File

@ -2,59 +2,37 @@ package jsoniter
import ( import (
"unicode/utf16" "unicode/utf16"
"unsafe"
) )
// TODO: avoid append
func (iter *Iterator) ReadString() (ret string) { func (iter *Iterator) ReadString() (ret string) {
c := iter.nextToken() c := iter.nextToken()
if c == '"' { if c == '"' {
copied := make([]byte, 32) for i := iter.head ; i < iter.tail; i++ {
j := 0
fast_loop:
for {
i := iter.head
for ; i < iter.tail && j < len(copied); i++ {
c := iter.buf[i] c := iter.buf[i]
if c == '"' { if c == '"' {
ret = string(iter.buf[iter.head:i])
iter.head = i + 1 iter.head = i + 1
copied = copied[:j] return ret
return *(*string)(unsafe.Pointer(&copied))
} else if c == '\\' { } else if c == '\\' {
iter.head = i break
break fast_loop
}
copied[j] = c
j++
}
if i == iter.tail {
if iter.loadMore() {
i = iter.head
continue
} else {
iter.reportError("ReadString", "incomplete string")
return
} }
} }
iter.head = i return iter.readStringSlowPath()
if j == len(copied) { } else if c == 'n' {
newBuf := make([]byte, len(copied) * 2) iter.skipFixedBytes(3)
copy(newBuf, copied) return ""
copied = newBuf
}
}
return iter.readStringSlowPath(copied[:j])
} }
iter.reportError("ReadString", `expects " or n`) iter.reportError("ReadString", `expects " or n`)
return return
} }
func (iter *Iterator) readStringSlowPath(str []byte) (ret string) { func (iter *Iterator) readStringSlowPath() (ret string) {
var str []byte
var c byte var c byte
for iter.Error == nil { for iter.Error == nil {
c = iter.readByte() c = iter.readByte()
if c == '"' { if c == '"' {
return *(*string)(unsafe.Pointer(&str)) return string(str)
} }
if c == '\\' { if c == '\\' {
c = iter.readByte() c = iter.readByte()