Bläddra i källkod

#68 string to int

Tao Wen 8 år sedan
förälder
incheckning
306b2896cf
3 ändrade filer med 44 tillägg och 0 borttagningar
  1. 19 0
      extra/fuzzy_decoder.go
  2. 21 0
      extra/fuzzy_decoder_test.go
  3. 4 0
      feature_iter.go

+ 19 - 0
extra/fuzzy_decoder.go

@@ -8,6 +8,7 @@ import (
 
 func RegisterFuzzyDecoders() {
 	jsoniter.RegisterTypeDecoder("string", &FuzzyStringDecoder{})
+	jsoniter.RegisterTypeDecoder("int", &FuzzyIntDecoder{})
 }
 
 type FuzzyStringDecoder struct {
@@ -26,3 +27,21 @@ func (decoder *FuzzyStringDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Ite
 		iter.ReportError("FuzzyStringDecoder", "not number or string")
 	}
 }
+
+type FuzzyIntDecoder struct {
+}
+
+func (decoder *FuzzyIntDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
+	valueType := iter.WhatIsNext()
+	switch valueType {
+	case jsoniter.Number:
+		// use current iterator
+	case jsoniter.String:
+		str := iter.ReadString()
+		iter = iter.Config().BorrowIterator([]byte(str))
+		defer iter.Config().ReturnIterator(iter)
+	default:
+		iter.ReportError("FuzzyIntDecoder", "not number or string")
+	}
+	*((*int)(ptr)) = iter.ReadInt()
+}

+ 21 - 0
extra/fuzzy_decoder_test.go

@@ -10,6 +10,13 @@ func init() {
 	RegisterFuzzyDecoders()
 }
 
+func Test_string_to_string(t *testing.T) {
+	should := require.New(t)
+	var val string
+	should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
+	should.Equal("100", val)
+}
+
 func Test_int_to_string(t *testing.T) {
 	should := require.New(t)
 	var val string
@@ -23,3 +30,17 @@ func Test_float_to_string(t *testing.T) {
 	should.Nil(jsoniter.UnmarshalFromString(`12.0`, &val))
 	should.Equal("12.0", val)
 }
+
+func Test_string_to_int(t *testing.T) {
+	should := require.New(t)
+	var val int
+	should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
+	should.Equal(100, val)
+}
+
+func Test_int_to_int(t *testing.T) {
+	should := require.New(t)
+	var val int
+	should.Nil(jsoniter.UnmarshalFromString(`100`, &val))
+	should.Equal(100, val)
+}

+ 4 - 0
feature_iter.go

@@ -113,6 +113,10 @@ func ParseString(cfg *frozenConfig, input string) *Iterator {
 	return ParseBytes(cfg, []byte(input))
 }
 
+func (iter *Iterator) Config() *frozenConfig {
+	return iter.cfg
+}
+
 // Reset can reset an Iterator instance for another json buffer in io.Reader
 func (iter *Iterator) Reset(reader io.Reader) *Iterator {
 	iter.reader = reader