diff --git a/encoding/gsm7.go b/encoding/gsm7.go index 350f38c..dd750c7 100644 --- a/encoding/gsm7.go +++ b/encoding/gsm7.go @@ -19,6 +19,11 @@ func (c *GSM7Coder) Encode(s string, buf *bytes.Buffer) error { bitshift byte = 0 leap, shift bool ) + encodedSize := GSM7EncodesInto(&s) + cap := buf.Cap() + if cap < encodedSize { + buf.Grow(encodedSize-cap) + } for index, septet := range utf8 { if septet > 0b01111111 { diff --git a/encoding/gsm7_test.go b/encoding/gsm7_test.go index c337ea6..be7c2e4 100644 --- a/encoding/gsm7_test.go +++ b/encoding/gsm7_test.go @@ -86,6 +86,25 @@ func TestGSM7EncodeDoesNotAllocateMoreThanNecessary(t *testing.T) { } } +func TestGSM7EncodeDoesAllocateWhenNecessary(t *testing.T) { + coder := &GSM7Coder{} + input := "Ducks are fucking great, they quacks, O quackers, what the fuck." + var buf bytes.Buffer + buf.Reset() + + original := buf.Cap() + err := coder.Encode(input, &buf) + modified := buf.Cap() + + if err != nil { + t.Errorf("Expected no error, but got %v", err) + } + + if !(modified > original) { + t.Errorf("Expected buffer to grow but buffer changed from %v to %v", original, modified) + } +} + func TestGSM7EncodeEmptyString(t *testing.T) { coder := &GSM7Coder{} var buf bytes.Buffer