فهرست منبع

add ReadBase64

Tao Wen 9 سال پیش
والد
کامیت
b04c1e7485
2فایلهای تغییر یافته به همراه55 افزوده شده و 2 حذف شده
  1. 42 2
      jsoniter.go
  2. 13 0
      jsoniter_base64_test.go

+ 42 - 2
jsoniter.go

@@ -6,10 +6,16 @@ import (
 	"unicode/utf16"
 	"strconv"
 	"unsafe"
+	"encoding/base64"
 )
 
 var digits []byte
 
+
+var needCheckValues []uint8
+
+var needCheckMasks []uint8
+
 func init() {
 	digits = make([]byte, 256)
 	for i := 0; i < len(digits); i++ {
@@ -24,6 +30,26 @@ func init() {
 	for i := 'A'; i <= 'F'; i++ {
 		digits[i] = byte((i - 'A') + 10);
 	}
+	needCheckValues = []uint8{
+		uint8(0xff) >> 7,
+		uint8(0xff) >> 6,
+		uint8(0xff) >> 5,
+		uint8(0xff) >> 4,
+		uint8(0xff) >> 3,
+		uint8(0xff) >> 2,
+		uint8(0xff) >> 1,
+		uint8(0xff) >> 0,
+	}
+	needCheckMasks = []uint8{
+		uint8(1) << 0,
+		uint8(1) << 1,
+		uint8(1) << 2,
+		uint8(1) << 3,
+		uint8(1) << 4,
+		uint8(1) << 5,
+		uint8(1) << 6,
+		uint8(1) << 7,
+	}
 }
 
 type Iterator struct {
@@ -549,8 +575,7 @@ func (iter *Iterator) ReadObject() (ret string) {
 func (iter *Iterator) readObjectField() (ret string) {
 	str := iter.ReadStringAsBytes()
 	field := *(*string)(unsafe.Pointer(&str))
-	c := iter.nextToken()
-	if c != ':' {
+	if iter.nextToken() != ':' {
 		iter.ReportError("ReadObject", "expect : after object field")
 		return
 	}
@@ -642,6 +667,21 @@ func (iter *Iterator) ReadBool() (ret bool) {
 	}
 }
 
+func (iter *Iterator) ReadBase64() (ret []byte) {
+	src := iter.ReadStringAsBytes()
+	if iter.Error != nil {
+		return
+	}
+	b64 := base64.StdEncoding
+	ret = make([]byte, b64.DecodedLen(len(src)))
+	n, err := b64.Decode(ret, src)
+	if err != nil {
+		iter.Error = err
+		return
+	}
+	return ret[:n]
+}
+
 func (iter *Iterator) ReadNull() (ret bool) {
 	c := iter.readByte()
 	if c == 'n' {

+ 13 - 0
jsoniter_base64_test.go

@@ -0,0 +1,13 @@
+package jsoniter
+
+import (
+	"testing"
+	"bytes"
+)
+
+func Test_read_base64(t *testing.T) {
+	iter := ParseString(`"YWJj"`)
+	if !bytes.Equal(iter.ReadBase64(), []byte("abc")) {
+		t.FailNow()
+	}
+}