francoispqt / gojay

high performance JSON encoder/decoder with stream API for Golang
MIT License
2.11k stars 112 forks source link

What is the difference between dec.String() and dec.DecodeString() #122

Open sgotliv opened 5 years ago

sgotliv commented 5 years ago

I've noticed that in many cases using dec.DecodeString() eventually leads to InvalidJson error, while parsing the same json and using dec.String() works perfectly. The only difference between them that I see is

dec.called |= 1

Same with DecodeInt vs Int, DecodeArray vs Array and etc.

Can you, please, help me understand why do you need them both.

noamt commented 5 years ago

I'm not the author but I believe that it's tied to whether you are handling a root element or not. Where methods prefixed with Decode are to be used on the root element, and all sub elements are to be decoded with the methods that don't have that prefix.

I think that dec.called |= 1 refers to skipping the expression closing char (for example, }), which allows us to continue to the next element.

If you call a subelement with dec.DecodeSomething, the closing character isn't skipped, and so when handling the next element the parser will try to parse the end of the last expression (}) instead of the opening of the next expression ({).

If you call a subelement with dec.Something, the character the closes the expression is included.