From 306b2896cfd8ec7197b4dce08604fbe13e0f85b4 Mon Sep 17 00:00:00 2001 From: Tao Wen Date: Tue, 20 Jun 2017 15:18:24 +0800 Subject: [PATCH] #68 string to int --- extra/fuzzy_decoder.go | 19 +++++++++++++++++++ extra/fuzzy_decoder_test.go | 21 +++++++++++++++++++++ feature_iter.go | 4 ++++ 3 files changed, 44 insertions(+) diff --git a/extra/fuzzy_decoder.go b/extra/fuzzy_decoder.go index 7d60357..25e95d7 100644 --- a/extra/fuzzy_decoder.go +++ b/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() +} diff --git a/extra/fuzzy_decoder_test.go b/extra/fuzzy_decoder_test.go index 4e48b7c..4fa5743 100644 --- a/extra/fuzzy_decoder_test.go +++ b/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) +} diff --git a/feature_iter.go b/feature_iter.go index d29c9d4..2683b95 100644 --- a/feature_iter.go +++ b/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