Compare commits

..

2 Commits

Author SHA1 Message Date
f847588a24 Grow buffer when encoding when necessary
Some checks failed
Run Tests / Test (push) Failing after 15s
Benchmark BufferPool / RunBenchmarks (push) Failing after 16s
To maybe hopefully prevent multiple allocations
2024-07-30 23:34:50 +02:00
ee4f8ecfd6 Add memory allocation test
To make sure none is happening
2024-07-30 23:31:54 +02:00
2 changed files with 43 additions and 0 deletions

View File

@@ -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 {

View File

@@ -67,6 +67,44 @@ func TestGSM7EncodeComplex8nASCIIString(t *testing.T) {
}
}
func TestGSM7EncodeDoesNotAllocateMoreThanNecessary(t *testing.T) {
coder := &GSM7Coder{}
input := "Ducks are fucking great, they quacks, O quackers, what the fuck."
buf := bytes.NewBuffer(make([]byte, GSM7EncodesInto(&input)))
buf.Reset()
expected := buf.Cap()
err := coder.Encode(input, buf)
actual := buf.Cap()
if err != nil {
t.Errorf("Expected no error, but got %v", err)
}
if actual != expected {
t.Errorf("Expected buffer of size %v, but got %v", expected, actual)
}
}
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