1 // Copyright 2021 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package slices defines various functions useful with slices of any type.
12 // Equal reports whether two slices are equal: the same length and all
13 // elements equal. If the lengths are different, Equal returns false.
14 // Otherwise, the elements are compared in increasing index order, and the
15 // comparison stops at the first unequal pair.
16 // Floating point NaNs are not considered equal.
17 func Equal[E comparable](s1, s2 []E) bool {
18 if len(s1) != len(s2) {
29 // EqualFunc reports whether two slices are equal using a comparison
30 // function on each pair of elements. If the lengths are different,
31 // EqualFunc returns false. Otherwise, the elements are compared in
32 // increasing index order, and the comparison stops at the first index
33 // for which eq returns false.
34 func EqualFunc[E1, E2 any](s1 []E1, s2 []E2, eq func(E1, E2) bool) bool {
35 if len(s1) != len(s2) {
38 for i, v1 := range s1 {
47 // Index returns the index of the first occurrence of v in s,
48 // or -1 if not present.
49 func Index[E comparable](s []E, v E) int {
58 // IndexFunc returns the first index i satisfying f(s[i]),
60 func IndexFunc[E any](s []E, f func(E) bool) int {
69 // Contains reports whether v is present in s.
70 func Contains[E comparable](s []E, v E) bool {
71 return Index(s, v) >= 0
74 // ContainsFunc reports whether at least one
75 // element e of s satisfies f(e).
76 func ContainsFunc[E any](s []E, f func(E) bool) bool {
77 return IndexFunc(s, f) >= 0
80 // Insert inserts the values v... into s at index i,
81 // returning the modified slice.
82 // The elements at s[i:] are shifted up to make room.
83 // In the returned slice r, r[i] == v[0],
84 // and r[i+len(v)] == value originally at r[i].
85 // Insert panics if i is out of range.
86 // This function is O(len(s) + len(v)).
87 func Insert[S ~[]E, E any](s S, i int, v ...E) S {
94 return append(s, v...)
97 // Use append rather than make so that we bump the size of
98 // the slice up to the next storage class.
99 // This is what Grow does but we don't call Grow because
100 // that might copy the values twice.
101 s2 := append(s[:i], make(S, n+m-i)...)
103 copy(s2[i+m:], s[i:])
109 // s: aaaaaaaabbbbccccccccdddd
113 // s: aaaaaaaavvvvbbbbcccccccc
117 // a are the values that don't move in s.
118 // v are the values copied in from v.
119 // b and c are the values from s that are shifted up in index.
120 // d are the values that get overwritten, never to be seen again.
122 if !overlaps(v, s[i+m:]) {
123 // Easy case - v does not overlap either the c or d regions.
124 // (It might be in some of a or b, or elsewhere entirely.)
125 // The data we copy up doesn't write to v at all, so just do it.
130 // s: aaaaaaaabbbbbbbbcccccccc
133 // Note the b values are duplicated.
138 // s: aaaaaaaavvvvbbbbcccccccc
141 // That's the result we want.
145 // The hard case - v overlaps c or d. We can't just shift up
146 // the data because we'd move or clobber the values we're trying
148 // So instead, write v on top of d, then rotate.
152 // s: aaaaaaaabbbbccccccccvvvv
156 rotateRight(s[i:], m)
159 // s: aaaaaaaavvvvbbbbcccccccc
162 // That's the result we want.
166 // Delete removes the elements s[i:j] from s, returning the modified slice.
167 // Delete panics if s[i:j] is not a valid slice of s.
168 // Delete modifies the contents of the slice s; it does not create a new slice.
169 // Delete is O(len(s)-j), so if many items must be deleted, it is better to
170 // make a single call deleting them all together than to delete one at a time.
171 // Delete might not modify the elements s[len(s)-(j-i):len(s)]. If those
172 // elements contain pointers you might consider zeroing those elements so that
173 // objects they reference can be garbage collected.
174 func Delete[S ~[]E, E any](s S, i, j int) S {
175 _ = s[i:j] // bounds check
177 return append(s[:i], s[j:]...)
180 // DeleteFunc removes any elements from s for which del returns true,
181 // returning the modified slice.
182 // DeleteFunc modifies the contents of the slice s;
183 // it does not create a new slice.
184 // When DeleteFunc removes m elements, it might not modify the elements
185 // s[len(s)-m:len(s)]. If those elements contain pointers you might consider
186 // zeroing those elements so that objects they reference can be garbage
188 func DeleteFunc[S ~[]E, E any](s S, del func(E) bool) S {
189 // Don't start copying elements until we find one to delete.
190 for i, v := range s {
193 for i++; i < len(s); i++ {
206 // Replace replaces the elements s[i:j] by the given v, and returns the
207 // modified slice. Replace panics if s[i:j] is not a valid slice of s.
208 func Replace[S ~[]E, E any](s S, i, j int, v ...E) S {
209 _ = s[i:j] // verify that i:j is a valid subslice
212 return Insert(s, i, v...)
215 return append(s[:i], v...)
218 tot := len(s[:i]) + len(v) + len(s[j:])
220 // Too big to fit, allocate and copy over.
221 s2 := append(s[:i], make(S, tot-i)...) // See Insert
223 copy(s2[i+len(v):], s[j:])
230 // Easy, as v fits in the deleted portion.
233 copy(r[i+len(v):], s[j:])
238 // We are expanding (v is bigger than j-i).
239 // The situation is something like this:
240 // (example has i=4,j=8,len(s)=16,len(v)=6)
241 // s: aaaaxxxxbbbbbbbbyy
247 // y: area to expand into
249 if !overlaps(r[i+len(v):], v) {
250 // Easy, as v is not clobbered by the first copy.
251 copy(r[i+len(v):], s[j:])
256 // This is a situation where we don't have a single place to which
257 // we can copy v. Parts of it need to go to two different places.
258 // We want to copy the prefix of v into y and the suffix into x, then
259 // rotate |y| spots to the right.
263 // s: aaaavvvvbbbbbbbbvv
267 // If either of those two destinations don't alias v, then we're good.
268 y := len(v) - (j - i) // length of y portion
270 if !overlaps(r[i:j], v) {
272 copy(r[len(s):], v[:y])
273 rotateRight(r[i:], y)
276 if !overlaps(r[len(s):], v) {
277 copy(r[len(s):], v[:y])
279 rotateRight(r[i:], y)
283 // Now we know that v overlaps both x and y.
284 // That means that the entirety of b is *inside* v.
285 // So we don't need to preserve b at all; instead we
286 // can copy v first, then copy the b part of v out of
287 // v to the right destination.
288 k := startIdx(v, s[j:])
290 copy(r[i+len(v):], r[i+k:])
294 // Clone returns a copy of the slice.
295 // The elements are copied using assignment, so this is a shallow clone.
296 func Clone[S ~[]E, E any](s S) S {
297 // Preserve nil in case it matters.
301 return append(S([]E{}), s...)
304 // Compact replaces consecutive runs of equal elements with a single copy.
305 // This is like the uniq command found on Unix.
306 // Compact modifies the contents of the slice s; it does not create a new slice.
307 // When Compact discards m elements in total, it might not modify the elements
308 // s[len(s)-m:len(s)]. If those elements contain pointers you might consider
309 // zeroing those elements so that objects they reference can be garbage collected.
310 func Compact[S ~[]E, E comparable](s S) S {
315 for k := 1; k < len(s); k++ {
326 // CompactFunc is like Compact but uses a comparison function.
327 func CompactFunc[S ~[]E, E any](s S, eq func(E, E) bool) S {
332 for k := 1; k < len(s); k++ {
333 if !eq(s[k], s[k-1]) {
343 // Grow increases the slice's capacity, if necessary, to guarantee space for
344 // another n elements. After Grow(n), at least n elements can be appended
345 // to the slice without another allocation. If n is negative or too large to
346 // allocate the memory, Grow panics.
347 func Grow[S ~[]E, E any](s S, n int) S {
349 panic("cannot be negative")
351 if n -= cap(s) - len(s); n > 0 {
352 s = append(s[:cap(s)], make([]E, n)...)[:len(s)]
357 // Clip removes unused capacity from the slice, returning s[:len(s):len(s)].
358 func Clip[S ~[]E, E any](s S) S {
359 return s[:len(s):len(s)]
362 // Rotation algorithm explanation:
367 // split up like this
369 // swap first 2 and last 2
373 // recursively rotate first left part by 2
381 // split up like this
383 // swap first 2 and last 2
387 // recursively rotate second part left by 6
392 // TODO: There are other rotate algorithms.
393 // This algorithm has the desirable property that it moves each element exactly twice.
394 // The triple-reverse algorithm is simpler and more cache friendly, but takes more writes.
395 // The follow-cycles algorithm can be 1-write but it is not very cache friendly.
397 // rotateLeft rotates b left by n spaces.
398 // s_final[i] = s_orig[i+r], wrapping around.
399 func rotateLeft[S ~[]E, E any](s S, r int) {
400 for r != 0 && r != len(s) {
402 swap(s[:r], s[len(s)-r:])
405 swap(s[:len(s)-r], s[r:])
406 s, r = s[len(s)-r:], r*2-len(s)
410 func rotateRight[S ~[]E, E any](s S, r int) {
411 rotateLeft(s, len(s)-r)
414 // swap swaps the contents of x and y. x and y must be equal length and disjoint.
415 func swap[S ~[]E, E any](x, y S) {
416 for i := 0; i < len(x); i++ {
417 x[i], y[i] = y[i], x[i]
421 // overlaps reports whether the memory ranges a[0:len(a)] and b[0:len(b)] overlap.
422 func overlaps[S ~[]E, E any](a, b S) bool {
423 if len(a) == 0 || len(b) == 0 {
426 elemSize := unsafe.Sizeof(a[0])
430 // TODO: use a runtime/unsafe facility once one becomes available. See issue 12445.
431 // Also see crypto/internal/alias/alias.go:AnyOverlap
432 return uintptr(unsafe.Pointer(&a[0])) <= uintptr(unsafe.Pointer(&b[len(b)-1]))+(elemSize-1) &&
433 uintptr(unsafe.Pointer(&b[0])) <= uintptr(unsafe.Pointer(&a[len(a)-1]))+(elemSize-1)
436 // startIdx returns the index in haystack where the needle starts.
437 // prerequisite: the needle must be aliased entirely inside the haystack.
438 func startIdx[S ~[]E, E any](haystack, needle S) int {
440 for i := range haystack {
441 if p == &haystack[i] {
445 // TODO: what if the overlap is by a non-integral number of Es?
446 panic("needle not found")