diff options
Diffstat (limited to 'src/slices/slices.go')
-rw-r--r-- | src/slices/slices.go | 50 |
1 files changed, 28 insertions, 22 deletions
diff --git a/src/slices/slices.go b/src/slices/slices.go index d96dd8d37c..ae4c2adbf4 100644 --- a/src/slices/slices.go +++ b/src/slices/slices.go @@ -355,40 +355,46 @@ func Clone[S ~[]E, E any](s S) S { // which may have a smaller length. // Compact zeroes the elements between the new length and the original length. func Compact[S ~[]E, E comparable](s S) S { - if len(s) < 2 { - return s - } - i := 1 - for k := 1; k < len(s); k++ { - if s[k] != s[k-1] { - if i != k { - s[i] = s[k] + if len(s) > 1 { + for k := 1; k < len(s); k++ { + if s[k] == s[k-1] { + s2 := s[k:] + for k2 := 1; k2 < len(s2); k2++ { + if s2[k2] != s2[k2-1] { + s[k] = s2[k2] + k++ + } + } + + clear(s[k:]) // zero/nil out the obsolete elements, for GC + return s[:k] } - i++ } } - clear(s[i:]) // zero/nil out the obsolete elements, for GC - return s[:i] + return s } // CompactFunc is like [Compact] but uses an equality function to compare elements. // For runs of elements that compare equal, CompactFunc keeps the first one. // CompactFunc zeroes the elements between the new length and the original length. func CompactFunc[S ~[]E, E any](s S, eq func(E, E) bool) S { - if len(s) < 2 { - return s - } - i := 1 - for k := 1; k < len(s); k++ { - if !eq(s[k], s[k-1]) { - if i != k { - s[i] = s[k] + if len(s) > 1 { + for k := 1; k < len(s); k++ { + if eq(s[k], s[k-1]) { + s2 := s[k:] + for k2 := 1; k2 < len(s2); k2++ { + if !eq(s2[k2], s2[k2-1]) { + s[k] = s2[k2] + k++ + } + } + + clear(s[k:]) // zero/nil out the obsolete elements, for GC + return s[:k] } - i++ } } - clear(s[i:]) // zero/nil out the obsolete elements, for GC - return s[:i] + return s } // Grow increases the slice's capacity, if necessary, to guarantee space for |