WIP: moved logic code in test tools to separate package for better code architecture

This commit is contained in:
2025-05-15 18:09:38 +10:00
parent b645f2b6bd
commit 169e0539f6
7 changed files with 472 additions and 374 deletions

56
slicewriter/dummy_test.go Normal file
View File

@@ -0,0 +1,56 @@
package slicewriter
/*
Copyright 2025 Suyono <suyono3484@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import (
"sync"
"testing"
)
func TestDummy(t *testing.T) {
var (
p sync.Pool
a, b []byte
)
p = sync.Pool{
New: func() any {
return make([]byte, 4096)
},
}
a = p.Get().([]byte)
t.Logf("retrieve a from pool: len %d, cap %d", len(a), cap(a))
b = p.Get().([]byte)
t.Logf("retrieve b from pool: len %d, cap %d", len(b), cap(b))
a = a[:1024]
b = b[:1024]
t.Logf("resize a : len %d, cap %d", len(a), cap(a))
t.Logf("resize b : len %d, cap %d", len(b), cap(b))
p.Put(a[:cap(a)])
p.Put(b)
t.Log("after putting back")
a = p.Get().([]byte)
t.Logf("retrieve a from pool: len %d, cap %d", len(a), cap(a))
b = p.Get().([]byte)
t.Logf("retrieve b from pool: len %d, cap %d", len(b), cap(b))
}

View File

@@ -0,0 +1,52 @@
package slicewriter
/*
Copyright 2025 Suyono <suyono3484@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import "io"
type SliceWriter struct {
off int
buf []byte
}
func (w *SliceWriter) Write(p []byte) (int, error) {
if len(p)+w.off <= len(w.buf) {
copy(w.buf[w.off:], p)
w.off += len(p)
return len(p), nil
}
space := len(w.buf) - w.off
copy(w.buf[:w.off], p[:space])
w.off += space
return space, io.ErrShortWrite
}
func (w *SliceWriter) Reset() {
w.off = 0
}
func (w *SliceWriter) Bytes() []byte {
return w.buf[:w.off]
}
func NewSliceWriter(b []byte) *SliceWriter {
return &SliceWriter{
off: 0,
buf: b,
}
}