Tao Wen 8 lat temu
rodzic
commit
38d613acf2
3 zmienionych plików z 93 dodań i 9 usunięć
  1. 15 9
      feature_any.go
  2. 71 0
      feature_any_bool.go
  3. 7 0
      jsoniter_bool_test.go

+ 15 - 9
feature_any.go

@@ -14,17 +14,24 @@ type Any interface {
 }
 
 func (iter *Iterator) ReadAny() Any {
-	valueType := iter.WhatIsNext()
-	switch valueType {
-	case Nil:
-		iter.skipFixedBytes(4)
+	c := iter.nextToken()
+	switch c {
+	case '"':
+		return iter.readStringAny()
+	case 'n':
+		iter.skipFixedBytes(3) // null
 		return &nilAny{}
-	case Number:
+	case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
+		iter.unreadByte()
 		return iter.readNumberAny()
-	case String:
-		return iter.readStringAny()
+	case 't':
+		iter.skipFixedBytes(3) // true
+		return &trueAny{}
+	case 'f':
+		iter.skipFixedBytes(4) // false
+		return &falseAny{}
 	}
-	iter.reportError("ReadAny", fmt.Sprintf("unexpected value type: %v", valueType))
+	iter.reportError("ReadAny", fmt.Sprintf("unexpected character: %v", c))
 	return &invalidAny{}
 }
 
@@ -62,7 +69,6 @@ func (iter *Iterator) readNumberAny() Any {
 }
 
 func (iter *Iterator) readStringAny() Any {
-	iter.head++
 	lazyBuf := make([]byte, 1, 8)
 	lazyBuf[0] = '"'
 	for {

+ 71 - 0
feature_any_bool.go

@@ -0,0 +1,71 @@
+package jsoniter
+
+type trueAny struct {
+}
+
+func (any *trueAny) LastError() error {
+	return nil
+}
+
+func (any *trueAny) ToBool() bool {
+	return true
+}
+
+func (any *trueAny) ToInt() int {
+	return 1
+}
+
+func (any *trueAny) ToInt32() int32 {
+	return 1
+}
+
+func (any *trueAny) ToInt64() int64 {
+	return 1
+}
+
+func (any *trueAny) ToFloat32() float32 {
+	return 1
+}
+
+func (any *trueAny) ToFloat64() float64 {
+	return 1
+}
+
+func (any *trueAny) ToString() string {
+	return "true"
+}
+
+type falseAny struct {
+}
+
+func (any *falseAny) LastError() error {
+	return nil
+}
+
+func (any *falseAny) ToBool() bool {
+	return false
+}
+
+func (any *falseAny) ToInt() int {
+	return 0
+}
+
+func (any *falseAny) ToInt32() int32 {
+	return 0
+}
+
+func (any *falseAny) ToInt64() int64 {
+	return 0
+}
+
+func (any *falseAny) ToFloat32() float32 {
+	return 0
+}
+
+func (any *falseAny) ToFloat64() float64 {
+	return 0
+}
+
+func (any *falseAny) ToString() string {
+	return "false"
+}

+ 7 - 0
jsoniter_bool_test.go

@@ -20,6 +20,13 @@ func Test_false(t *testing.T) {
 	should.False(iter.ReadBool())
 }
 
+func Test_read_bool_as_any(t *testing.T) {
+	should := require.New(t)
+	any, err := UnmarshalAnyFromString("true")
+	should.Nil(err)
+	should.True(any.ToBool())
+}
+
 func Test_write_true_false(t *testing.T) {
 	should := require.New(t)
 	buf := &bytes.Buffer{}