Skip to content

Commit

Permalink
Merge pull request #82 from elee1766/grow
Browse files Browse the repository at this point in the history
add Grow function
  • Loading branch information
ernado committed Aug 7, 2023
2 parents d2a6a27 + 8794476 commit 50bd6f0
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 1 deletion.
5 changes: 5 additions & 0 deletions enc.go
Expand Up @@ -59,6 +59,11 @@ func (e *Encoder) ResetWriter(out io.Writer) {
e.first = e.first[:0]
}

// Grow grows the underlying buffer
func (e *Encoder) Grow(n int) {
e.w.Grow(n)
}

// Bytes returns underlying buffer.
func (e Encoder) Bytes() []byte { return e.w.Buf }

Expand Down
16 changes: 16 additions & 0 deletions enc_test.go
Expand Up @@ -32,6 +32,22 @@ func requireCompat(t *testing.T, cb func(*Encoder), v any) {
testEncoderModes(t, cb, string(buf))
}

func TestEncoderGrow(t *testing.T) {
should := require.New(t)
e := &Encoder{}
should.Equal(0, len(e.Bytes()))
should.Equal(0, cap(e.Bytes()))
e.Grow(1024)
should.Equal(0, len(e.Bytes()))
should.Equal(1024, cap(e.Bytes()))
e.Grow(512)
should.Equal(0, len(e.Bytes()))
should.Equal(1024, cap(e.Bytes()))
e.Grow(4096)
should.Equal(0, len(e.Bytes()))
should.Equal(4096, cap(e.Bytes()))
}

func TestEncoderByteShouldGrowBuffer(t *testing.T) {
should := require.New(t)
e := GetEncoder()
Expand Down
14 changes: 13 additions & 1 deletion w.go
@@ -1,6 +1,9 @@
package jx

import "io"
import (
"bytes"
"io"
)

// Writer writes json tokens to underlying buffer.
//
Expand Down Expand Up @@ -51,6 +54,15 @@ func (w *Writer) ResetWriter(out io.Writer) {
w.stream.Reset(out)
}

// Grow grows the underlying buffer.
//
// Calls (*bytes.Buffer).Grow(n int) on w.Buf.
func (w *Writer) Grow(n int) {
buf := bytes.NewBuffer(w.Buf)
buf.Grow(n)
w.Buf = buf.Bytes()
}

// byte writes a single byte.
func (w *Writer) byte(c byte) (fail bool) {
if w.stream == nil {
Expand Down
16 changes: 16 additions & 0 deletions w_test.go
Expand Up @@ -23,3 +23,19 @@ func TestWriter_String(t *testing.T) {
w.True()
require.Equal(t, "true", w.String())
}

func TestWriter_Grow(t *testing.T) {
should := require.New(t)
e := &Writer{}
should.Equal(0, len(e.Buf))
should.Equal(0, cap(e.Buf))
e.Grow(1024)
should.Equal(0, len(e.Buf))
should.Equal(1024, cap(e.Buf))
e.Grow(512)
should.Equal(0, len(e.Buf))
should.Equal(1024, cap(e.Buf))
e.Grow(4096)
should.Equal(0, len(e.Buf))
should.Equal(4096, cap(e.Buf))
}

0 comments on commit 50bd6f0

Please sign in to comment.