From 0c7249ce7d77b86b4116608264ab282fb690f16c Mon Sep 17 00:00:00 2001 From: qydysky Date: Thu, 15 May 2025 00:30:43 +0800 Subject: [PATCH] 1 (#54) --- slice/Slice.go | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/slice/Slice.go b/slice/Slice.go index 708efbf..8d2bc3b 100644 --- a/slice/Slice.go +++ b/slice/Slice.go @@ -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 } } } -- 2.39.2