diff --git a/common.go b/common.go index ce603a4..a3e5c4b 100644 --- a/common.go +++ b/common.go @@ -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 { diff --git a/common_test.go b/common_test.go index ab03bf1..80e6956 100644 --- a/common_test.go +++ b/common_test.go @@ -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)