Skip to content

Commit

Permalink
properly extend strings (#95)
Browse files Browse the repository at this point in the history
* properly extend strings

* revert unintended changes

---------

Co-authored-by: Steven Allen <[email protected]>
  • Loading branch information
whyrusleeping and Stebalien authored Jun 9, 2024
1 parent 88ce035 commit 7054243
Show file tree
Hide file tree
Showing 5 changed files with 116 additions and 0 deletions.
11 changes: 11 additions & 0 deletions testgen/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,15 @@ func main() {
if err != nil {
panic(err)
}

err = cbg.Gen{
MaxArrayLength: 10,
MaxByteLength: 9,
MaxStringLength: 10000,
}.WriteTupleEncodersToFile("testing/cbor_options_gen2.go", "testing",
types.LongString{},
)
if err != nil {
panic(err)
}
}
83 changes: 83 additions & 0 deletions testing/cbor_options_gen2.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions testing/roundtrip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ func TestNilPreserveWorks(t *testing.T) {
testTypeRoundtrips(t, reflect.TypeOf(TestSliceNilPreserve{}))
}

func TestLongStrings(t *testing.T) {
testTypeRoundtrips(t, reflect.TypeOf(LongString{}))
}

type RoundTripOptions struct {
Golden []byte
}
Expand Down
15 changes: 15 additions & 0 deletions testing/types.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package testing

import (
"math/rand"
"reflect"

"github.com/ipfs/go-cid"

cbg "github.com/whyrusleeping/cbor-gen"
Expand Down Expand Up @@ -179,3 +182,15 @@ type LimitedStruct struct {
Byts []byte
Str string
}

type LongString struct {
Val string
}

func (ls LongString) Generate(rand *rand.Rand, size int) reflect.Value {
ols := new(LongString)
s := make([]byte, 9999)
rand.Read(s)
ols.Val = string(s)
return reflect.ValueOf(ols).Elem()
}
3 changes: 3 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,9 @@ func ReadStringWithMax(r io.Reader, maxLength uint64) (string, error) {
}

bufp := stringBufPool.Get().(*[]byte)
if cap(*bufp) < int(l) {
*bufp = append((*bufp)[:cap(*bufp)], make([]byte, int(l)-cap(*bufp))...)
}
buf := (*bufp)[:l] // shares same backing array as pooled slice
defer func() {
// optimizes to memclr
Expand Down

0 comments on commit 7054243

Please sign in to comment.