Commit 24fd4ed9 authored by Kirill Smelkov's avatar Kirill Smelkov

.

parent f72c4971
......@@ -7,7 +7,7 @@ import (
// Grow increase length of slice by n elements.
// If there is not enough capacity the slice is reallocated.
// The memory for grown elements are not initialized.
// The memory for grown elements is not initialized.
func Grow(b []byte, n int) []byte {
ln := len(b) + n
if ln <= cap(b) {
......@@ -33,6 +33,18 @@ func Resize(b []byte, n int) []byte {
}
// Realloc resizes the slice to be of length n not preserving content.
// If slice length is increased and there is not enough capacity the slice is reallocated.
// The memory for all elements becomes uninitialized.
// XXX semantic clash with C realloc(3) ? or it does not matter?
func Realloc(b []byte, n int) []byte {
if cap(b) >= n {
return b[:n]
}
return make([]byte, n, xmath.CeilPow2(uint64(n)))
}
// TODO Resize without copy ?
// // GrowSlice makes sure cap(b) >= n.
......
package xslice
//import (
// "testing"
//)
// TODO
// func TestGrowSlice(t *testing) {
// testv := []struct {in []byte, n int, Cap int} {
// {nil, 0, 0},
// }
//
// }
import (
"bytes"
"reflect"
"testing"
"unsafe"
)
// aliases returns whether two slice memory is aliased
func aliases(b1, b2 []byte) bool {
s1 := (*reflect.SliceHeader)(unsafe.Pointer(&b1))
s2 := (*reflect.SliceHeader)(unsafe.Pointer(&b2))
return s1.Data == s2.Data
}
func TestSlice(t *testing.T) {
s := make([]byte, 0, 10)
testv := []struct {op func([]byte, int) []byte; n, Len, Cap int; aliased bool; content []byte} {
// op, n, Len, Cap, aliased, content
{Grow, 5, 5, 10, true, []byte{0,0,0,0,0}},
// here "Hello" is assigned
{Grow, 6, 11, 16, false, []byte("Hello\x00\x00\x00\x00\x00\x00")},
{Resize, 8, 8, 16, true, []byte("Hello\x00\x00\x00")},
{Resize, 17, 17, 32, false, []byte("Hello\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")},
{Realloc, 16, 16, 32, true, []byte("Hello\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")},
{Realloc, 33, 33, 64, false, make([]byte, 33)},
}
for i, tt := range testv {
sprev := s
s = tt.op(s, tt.n)
if !(len(s) == tt.Len && cap(s) == tt.Cap && bytes.Equal(s, tt.content)) {
t.Fatalf("step %d: %v: unexpected slice state: %v", i, tt, s)
}
if !(aliases(s, sprev) == tt.aliased) {
t.Fatalf("step %d: %v: unexpected slice aliasing: %v", aliases(s, sprev))
}
// assign data after fisrt iteration
if i == 0 {
copy(s, "Hello")
}
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment