]> 127.0.0.1 Git - part/.git/commitdiff
slices.Resize v0.28.20240616030125
authorqydysky <qydysky@foxmail.com>
Sun, 16 Jun 2024 02:55:28 +0000 (02:55 +0000)
committerqydysky <qydysky@foxmail.com>
Sun, 16 Jun 2024 02:55:28 +0000 (02:55 +0000)
slice/Slice.go
slice/Slice_test.go

index 5d7cceb953b2116815ca289778cf67ba7ac98b1b..78c4589ebbb7b045ce5c5a4b0800283a0140ad4f 100644 (file)
@@ -221,3 +221,11 @@ func DelBack[S ~[]T, T any](s *S, fromIndex int) {
 func AddBack[S ~[]*T, T any](s *S, t *T) {
        *s = append(*s, t)
 }
+
+func Resize[S ~[]T, T any](s *S, size int) {
+       if len(*s) >= size || cap(*s) >= size {
+               *s = (*s)[:size]
+       } else {
+               *s = append((*s)[:cap(*s)], make([]T, size-cap(*s))...)
+       }
+}
index fc86d8d2dfd2147686c45202ae5ea25d6f6732d8..bb33187f9431627824b9df4cfe49ee0df43edbf3 100644 (file)
@@ -6,6 +6,38 @@ import (
        "unsafe"
 )
 
+func TestResize(t *testing.T) {
+       var s = make([]byte, 10)
+       t.Log(unsafe.Pointer(&s), len(s), cap(s))
+       s = s[:0]
+       t.Log(unsafe.Pointer(&s), len(s), cap(s))
+       Resize(&s, 8)
+       if len(s) != 8 {
+               t.FailNow()
+       }
+       t.Log(unsafe.Pointer(&s), len(s), cap(s))
+       Resize(&s, 4)
+       if len(s) != 4 {
+               t.FailNow()
+       }
+       t.Log(unsafe.Pointer(&s), len(s), cap(s))
+       Resize(&s, 11)
+       if len(s) != 11 {
+               t.FailNow()
+       }
+       t.Log(unsafe.Pointer(&s), len(s), cap(s))
+       Resize(&s, 25)
+       if len(s) != 25 {
+               t.FailNow()
+       }
+       t.Log(unsafe.Pointer(&s), len(s), cap(s))
+       Resize(&s, 3)
+       if len(s) != 3 {
+               t.FailNow()
+       }
+       t.Log(unsafe.Pointer(&s), len(s), cap(s))
+}
+
 func TestXxx(t *testing.T) {
        var (
                b = New[byte](5)