Skip to content

Commit

Permalink
Fix overflow issue
Browse files Browse the repository at this point in the history
  • Loading branch information
marrow16 committed Oct 25, 2022
1 parent dd566d4 commit 2174716
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
17 changes: 13 additions & 4 deletions common.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,22 +86,31 @@ func (nvp *NameValuePair) OmitEmpty() *NameValuePair {
return nvp
}

func (nvp *NameValuePair) ToData() ([]byte, error) {
func (nvp *NameValuePair) ToData() (result []byte, err error) {
useValue := nvp.value
if gdfn, ok := useValue.(func(string) interface{}); ok {
useValue = gdfn(nvp.name)
}
if nvp.omitEmpty && useValue == nil {
return make([]byte, 0, 0), nil
return
}
vData, err := argValueToData(useValue)
if err != nil {
return nil, err
}
result := make([]byte, 0, len(nvp.nameData)+len(vData))
capacity := checkedCapacity(len(nvp.nameData), len(vData))
result = make([]byte, 0, capacity)
result = append(result, nvp.nameData...)
result = append(result, vData...)
return result, nil
return
}

func checkedCapacity(sz1, sz2 int) int {
if tot := sz1 + sz2; tot < sz1 || tot < sz2 {
return 0
} else {
return tot
}
}

type NameValuePairs struct {
Expand Down
11 changes: 11 additions & 0 deletions common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,17 @@ func TestNameValues(t *testing.T) {
require.Equal(t, `{}`, str)
}

func TestCheckedCapacity(t *testing.T) {
tot := checkedCapacity(1, 2)
require.Equal(t, 3, tot)

tot = checkedCapacity(9223372036854775807, 1)
require.Equal(t, 0, tot)

tot = checkedCapacity(9223372036854775807, 9223372036854775807)
require.Equal(t, 0, tot)
}

func TestNameValuesMarshallError(t *testing.T) {
jt, err := NewTemplate(`{?}`)
require.NoError(t, err)
Expand Down

0 comments on commit 2174716

Please sign in to comment.