]> 127.0.0.1 Git - part/.git/commitdiff
1 (#54) v0.28.20250514163050
authorqydysky <qydysky@foxmail.com>
Wed, 14 May 2025 16:30:43 +0000 (00:30 +0800)
committerGitHub <noreply@github.com>
Wed, 14 May 2025 16:30:43 +0000 (00:30 +0800)
slice/Slice.go

index 708efbf27aea8d6439403e88070fcd0798d136b5..8d2bc3b6d9b372e191337427c0f720f684634630 100644 (file)
@@ -67,6 +67,22 @@ func (t *Buf[T]) AppendTo(to *Buf[T]) error {
 
 var ErrOverMax = perrors.New("slices.Append", "ErrOverMax")
 
+func (t *Buf[T]) Cap() int {
+       t.l.RLock()
+       defer t.l.RUnlock()
+       return cap(t.buf)
+}
+
+func (t *Buf[T]) ExpandCapTo(size int) {
+       t.l.Lock()
+       defer t.l.Unlock()
+       if cap(t.buf) >= size {
+               return
+       } else {
+               t.buf = append(t.buf[:cap(t.buf)], make([]T, size-cap(t.buf))...)
+       }
+}
+
 func (t *Buf[T]) Append(data []T) error {
        t.l.Lock()
        defer t.l.Unlock()
@@ -76,10 +92,11 @@ func (t *Buf[T]) Append(data []T) error {
        } else if len(t.buf) == 0 {
                t.buf = make([]T, len(data))
        } else {
-               diff := len(t.buf) - t.bufsize - len(data)
+               diff := cap(t.buf) - t.bufsize - len(data)
                if diff < 0 {
-                       t.buf = append(t.buf, make([]T, -diff)...)
+                       t.buf = append(t.buf[:cap(t.buf)], make([]T, -diff)...)
                }
+               t.buf = t.buf[:t.bufsize+len(data)]
        }
        t.bufsize += copy(t.buf[t.bufsize:], data)
        t.modified.t += 1
@@ -234,7 +251,7 @@ func Del[S ~[]T, T any](s *S, f func(t *T) (del bool)) {
        for i := 0; i < len(*s); i++ {
                if f(&(*s)[i]) {
                        *s = append((*s)[:i], (*s)[i+1:]...)
-                       i-=1
+                       i -= 1
                }
        }
 }