Skip to content

Commit

Permalink
detect remaining bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
taowen committed Feb 22, 2018
1 parent a3fdd37 commit be70f29
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 27 deletions.
9 changes: 0 additions & 9 deletions adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,6 @@ func Unmarshal(data []byte, v interface{}) error {
return ConfigDefault.Unmarshal(data, v)
}

func lastNotSpacePos(data []byte) int {
for i := len(data) - 1; i >= 0; i-- {
if data[i] != ' ' && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
return i + 1
}
}
return 0
}

// UnmarshalFromString convenient method to read from string instead of []byte
func UnmarshalFromString(str string, v interface{}) error {
return ConfigDefault.UnmarshalFromString(str, v)
Expand Down
32 changes: 14 additions & 18 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,19 +249,17 @@ func (cfg *frozenConfig) MarshalIndent(v interface{}, prefix, indent string) ([]

func (cfg *frozenConfig) UnmarshalFromString(str string, v interface{}) error {
data := []byte(str)
data = data[:lastNotSpacePos(data)]
iter := cfg.BorrowIterator(data)
defer cfg.ReturnIterator(iter)
iter.ReadVal(v)
if iter.head == iter.tail {
iter.loadMore()
}
if iter.Error == io.EOF {
return nil
}
if iter.Error == nil {
iter.ReportError("UnmarshalFromString", "there are bytes left after unmarshal")
c := iter.nextToken()
if c == 0 {
if iter.Error == io.EOF {
return nil
}
return iter.Error
}
iter.ReportError("Unmarshal", "there are bytes left after unmarshal")
return iter.Error
}

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

func (cfg *frozenConfig) Unmarshal(data []byte, v interface{}) error {
data = data[:lastNotSpacePos(data)]
iter := cfg.BorrowIterator(data)
defer cfg.ReturnIterator(iter)
iter.ReadVal(v)
if iter.head == iter.tail {
iter.loadMore()
}
if iter.Error == io.EOF {
return nil
}
if iter.Error == nil {
iter.ReportError("Unmarshal", "there are bytes left after unmarshal")
c := iter.nextToken()
if c == 0 {
if iter.Error == io.EOF {
return nil
}
return iter.Error
}
iter.ReportError("Unmarshal", "there are bytes left after unmarshal")
return iter.Error
}

Expand Down
5 changes: 5 additions & 0 deletions value_tests/struct_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ func init() {
Field interface{}
})(nil),
input: `{"Field": "hello"}`,
}, unmarshalCase{
ptr: (*struct {
Field interface{}
})(nil),
input: `{"Field": "hello"} `,
}, unmarshalCase{
ptr: (*struct {
Field int `json:"field"`
Expand Down

0 comments on commit be70f29

Please sign in to comment.