From 7e046e6aa795d5c3cdd315919a6f9703b2c6bcca Mon Sep 17 00:00:00 2001 From: Tao Wen Date: Tue, 23 May 2017 18:32:39 +0800 Subject: [PATCH] simplify read string, and support null --- feature_iter_string.go | 52 ++++++++++++------------------------------ jsoniter_demo_test.go | 2 +- 2 files changed, 16 insertions(+), 38 deletions(-) diff --git a/feature_iter_string.go b/feature_iter_string.go index e248931..3a41d7b 100644 --- a/feature_iter_string.go +++ b/feature_iter_string.go @@ -2,59 +2,37 @@ package jsoniter import ( "unicode/utf16" - "unsafe" ) -// TODO: avoid append func (iter *Iterator) ReadString() (ret string) { c := iter.nextToken() if c == '"' { - copied := make([]byte, 32) - j := 0 - fast_loop: - for { - i := iter.head - for ; i < iter.tail && j < len(copied); i++ { - c := iter.buf[i] - if c == '"' { - iter.head = i + 1 - copied = copied[:j] - return *(*string)(unsafe.Pointer(&copied)) - } else if c == '\\' { - iter.head = i - 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 - if j == len(copied) { - newBuf := make([]byte, len(copied) * 2) - copy(newBuf, copied) - copied = newBuf + for i := iter.head ; i < iter.tail; i++ { + c := iter.buf[i] + if c == '"' { + ret = string(iter.buf[iter.head:i]) + iter.head = i + 1 + return ret + } else if c == '\\' { + break } } - return iter.readStringSlowPath(copied[:j]) + return iter.readStringSlowPath() + } else if c == 'n' { + iter.skipFixedBytes(3) + return "" } iter.reportError("ReadString", `expects " or n`) return } -func (iter *Iterator) readStringSlowPath(str []byte) (ret string) { +func (iter *Iterator) readStringSlowPath() (ret string) { + var str []byte var c byte for iter.Error == nil { c = iter.readByte() if c == '"' { - return *(*string)(unsafe.Pointer(&str)) + return string(str) } if c == '\\' { c = iter.readByte() diff --git a/jsoniter_demo_test.go b/jsoniter_demo_test.go index e90502c..b94e1b1 100644 --- a/jsoniter_demo_test.go +++ b/jsoniter_demo_test.go @@ -21,4 +21,4 @@ func Test_iterator_api_demo(t *testing.T) { total += iter.ReadInt() } fmt.Println(total) -} +} \ No newline at end of file