Skip to content

Commit be70f29

Browse files
committed
detect remaining bytes
1 parent a3fdd37 commit be70f29

File tree

3 files changed

+19
-27
lines changed

3 files changed

+19
-27
lines changed

adapter.go

-9
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,6 @@ func Unmarshal(data []byte, v interface{}) error {
1616
return ConfigDefault.Unmarshal(data, v)
1717
}
1818

19-
func lastNotSpacePos(data []byte) int {
20-
for i := len(data) - 1; i >= 0; i-- {
21-
if data[i] != ' ' && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
22-
return i + 1
23-
}
24-
}
25-
return 0
26-
}
27-
2819
// UnmarshalFromString convenient method to read from string instead of []byte
2920
func UnmarshalFromString(str string, v interface{}) error {
3021
return ConfigDefault.UnmarshalFromString(str, v)

config.go

+14-18
Original file line numberDiff line numberDiff line change
@@ -249,19 +249,17 @@ func (cfg *frozenConfig) MarshalIndent(v interface{}, prefix, indent string) ([]
249249

250250
func (cfg *frozenConfig) UnmarshalFromString(str string, v interface{}) error {
251251
data := []byte(str)
252-
data = data[:lastNotSpacePos(data)]
253252
iter := cfg.BorrowIterator(data)
254253
defer cfg.ReturnIterator(iter)
255254
iter.ReadVal(v)
256-
if iter.head == iter.tail {
257-
iter.loadMore()
258-
}
259-
if iter.Error == io.EOF {
260-
return nil
261-
}
262-
if iter.Error == nil {
263-
iter.ReportError("UnmarshalFromString", "there are bytes left after unmarshal")
255+
c := iter.nextToken()
256+
if c == 0 {
257+
if iter.Error == io.EOF {
258+
return nil
259+
}
260+
return iter.Error
264261
}
262+
iter.ReportError("Unmarshal", "there are bytes left after unmarshal")
265263
return iter.Error
266264
}
267265

@@ -272,19 +270,17 @@ func (cfg *frozenConfig) Get(data []byte, path ...interface{}) Any {
272270
}
273271

274272
func (cfg *frozenConfig) Unmarshal(data []byte, v interface{}) error {
275-
data = data[:lastNotSpacePos(data)]
276273
iter := cfg.BorrowIterator(data)
277274
defer cfg.ReturnIterator(iter)
278275
iter.ReadVal(v)
279-
if iter.head == iter.tail {
280-
iter.loadMore()
281-
}
282-
if iter.Error == io.EOF {
283-
return nil
284-
}
285-
if iter.Error == nil {
286-
iter.ReportError("Unmarshal", "there are bytes left after unmarshal")
276+
c := iter.nextToken()
277+
if c == 0 {
278+
if iter.Error == io.EOF {
279+
return nil
280+
}
281+
return iter.Error
287282
}
283+
iter.ReportError("Unmarshal", "there are bytes left after unmarshal")
288284
return iter.Error
289285
}
290286

value_tests/struct_test.go

+5
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,11 @@ func init() {
1616
Field interface{}
1717
})(nil),
1818
input: `{"Field": "hello"}`,
19+
}, unmarshalCase{
20+
ptr: (*struct {
21+
Field interface{}
22+
})(nil),
23+
input: `{"Field": "hello"} `,
1924
}, unmarshalCase{
2025
ptr: (*struct {
2126
Field int `json:"field"`

0 commit comments

Comments
 (0)