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.
13 // Equal reports whether two slices are equal: the same length and all
14 // elements equal. If the lengths are different, Equal returns false.
15 // Otherwise, the elements are compared in increasing index order, and the
16 // comparison stops at the first unequal pair.
17 // Floating point NaNs are not considered equal.
18 func Equal[S ~[]E, E comparable](s1, s2 S) bool {
19 if len(s1) != len(s2) {
30 // EqualFunc reports whether two slices are equal using an equality
31 // function on each pair of elements. If the lengths are different,
32 // EqualFunc returns false. Otherwise, the elements are compared in
33 // increasing index order, and the comparison stops at the first index
34 // for which eq returns false.
35 func EqualFunc[S1 ~[]E1, S2 ~[]E2, E1, E2 any](s1 S1, s2 S2, eq func(E1, E2) bool) bool {
36 if len(s1) != len(s2) {
39 for i, v1 := range s1 {
48 // Compare compares the elements of s1 and s2, using [cmp.Compare] on each pair
49 // of elements. The elements are compared sequentially, starting at index 0,
50 // until one element is not equal to the other.
51 // The result of comparing the first non-matching elements is returned.
52 // If both slices are equal until one of them ends, the shorter slice is
53 // considered less than the longer one.
54 // The result is 0 if s1 == s2, -1 if s1 < s2, and +1 if s1 > s2.
55 func Compare[S ~[]E, E cmp.Ordered](s1, s2 S) int {
56 for i, v1 := range s1 {
61 if c := cmp.Compare(v1, v2); c != 0 {
65 if len(s1) < len(s2) {
71 // CompareFunc is like [Compare] but uses a custom comparison function on each
73 // The result is the first non-zero result of cmp; if cmp always
74 // returns 0 the result is 0 if len(s1) == len(s2), -1 if len(s1) < len(s2),
75 // and +1 if len(s1) > len(s2).
76 func CompareFunc[S1 ~[]E1, S2 ~[]E2, E1, E2 any](s1 S1, s2 S2, cmp func(E1, E2) int) int {
77 for i, v1 := range s1 {
82 if c := cmp(v1, v2); c != 0 {
86 if len(s1) < len(s2) {
92 // Index returns the index of the first occurrence of v in s,
93 // or -1 if not present.
94 func Index[S ~[]E, E comparable](s S, v E) int {
103 // IndexFunc returns the first index i satisfying f(s[i]),
105 func IndexFunc[S ~[]E, E any](s S, f func(E) bool) int {
114 // Contains reports whether v is present in s.
115 func Contains[S ~[]E, E comparable](s S, v E) bool {
116 return Index(s, v) >= 0
119 // ContainsFunc reports whether at least one
120 // element e of s satisfies f(e).
121 func ContainsFunc[S ~[]E, E any](s S, f func(E) bool) bool {
122 return IndexFunc(s, f) >= 0
125 // Insert inserts the values v... into s at index i,
126 // returning the modified slice.
127 // The elements at s[i:] are shifted up to make room.
128 // In the returned slice r, r[i] == v[0],
129 // and r[i+len(v)] == value originally at r[i].
130 // Insert panics if i is out of range.
131 // This function is O(len(s) + len(v)).
132 func Insert[S ~[]E, E any](s S, i int, v ...E) S {
136 // Panic if i is not in the range [0:n] inclusive.
142 return append(s, v...)
145 // Use append rather than make so that we bump the size of
146 // the slice up to the next storage class.
147 // This is what Grow does but we don't call Grow because
148 // that might copy the values twice.
149 s2 := append(s[:i], make(S, n+m-i)...)
151 copy(s2[i+m:], s[i:])
157 // s: aaaaaaaabbbbccccccccdddd
161 // s: aaaaaaaavvvvbbbbcccccccc
165 // a are the values that don't move in s.
166 // v are the values copied in from v.
167 // b and c are the values from s that are shifted up in index.
168 // d are the values that get overwritten, never to be seen again.
170 if !overlaps(v, s[i+m:]) {
171 // Easy case - v does not overlap either the c or d regions.
172 // (It might be in some of a or b, or elsewhere entirely.)
173 // The data we copy up doesn't write to v at all, so just do it.
178 // s: aaaaaaaabbbbbbbbcccccccc
181 // Note the b values are duplicated.
186 // s: aaaaaaaavvvvbbbbcccccccc
189 // That's the result we want.
193 // The hard case - v overlaps c or d. We can't just shift up
194 // the data because we'd move or clobber the values we're trying
196 // So instead, write v on top of d, then rotate.
200 // s: aaaaaaaabbbbccccccccvvvv
204 rotateRight(s[i:], m)
207 // s: aaaaaaaavvvvbbbbcccccccc
210 // That's the result we want.
214 // Delete removes the elements s[i:j] from s, returning the modified slice.
215 // Delete panics if j > len(s) or s[i:j] is not a valid slice of s.
216 // Delete is O(len(s)-j), so if many items must be deleted, it is better to
217 // make a single call deleting them all together than to delete one at a time.
218 // Delete might not modify the elements s[len(s)-(j-i):len(s)]. If those
219 // elements contain pointers you might consider zeroing those elements so that
220 // objects they reference can be garbage collected.
221 func Delete[S ~[]E, E any](s S, i, j int) S {
222 _ = s[i:j] // bounds check
224 return append(s[:i], s[j:]...)
227 // DeleteFunc removes any elements from s for which del returns true,
228 // returning the modified slice.
229 // When DeleteFunc removes m elements, it might not modify the elements
230 // s[len(s)-m:len(s)]. If those elements contain pointers you might consider
231 // zeroing those elements so that objects they reference can be garbage
233 func DeleteFunc[S ~[]E, E any](s S, del func(E) bool) S {
234 i := IndexFunc(s, del)
238 // Don't start copying elements until we find one to delete.
239 for j := i + 1; j < len(s); j++ {
240 if v := s[j]; !del(v) {
248 // Replace replaces the elements s[i:j] by the given v, and returns the
250 // Replace panics if j > len(s) or s[i:j] is not a valid slice of s.
251 func Replace[S ~[]E, E any](s S, i, j int, v ...E) S {
252 _ = s[i:j] // bounds check
255 return Insert(s, i, v...)
258 return append(s[:i], v...)
261 tot := len(s[:i]) + len(v) + len(s[j:])
263 // Too big to fit, allocate and copy over.
264 s2 := append(s[:i], make(S, tot-i)...) // See Insert
266 copy(s2[i+len(v):], s[j:])
273 // Easy, as v fits in the deleted portion.
275 copy(r[i+len(v):], s[j:])
279 // We are expanding (v is bigger than j-i).
280 // The situation is something like this:
281 // (example has i=4,j=8,len(s)=16,len(v)=6)
282 // s: aaaaxxxxbbbbbbbbyy
288 // y: area to expand into
290 if !overlaps(r[i+len(v):], v) {
291 // Easy, as v is not clobbered by the first copy.
292 copy(r[i+len(v):], s[j:])
297 // This is a situation where we don't have a single place to which
298 // we can copy v. Parts of it need to go to two different places.
299 // We want to copy the prefix of v into y and the suffix into x, then
300 // rotate |y| spots to the right.
304 // s: aaaavvvvbbbbbbbbvv
308 // If either of those two destinations don't alias v, then we're good.
309 y := len(v) - (j - i) // length of y portion
311 if !overlaps(r[i:j], v) {
313 copy(r[len(s):], v[:y])
314 rotateRight(r[i:], y)
317 if !overlaps(r[len(s):], v) {
318 copy(r[len(s):], v[:y])
320 rotateRight(r[i:], y)
324 // Now we know that v overlaps both x and y.
325 // That means that the entirety of b is *inside* v.
326 // So we don't need to preserve b at all; instead we
327 // can copy v first, then copy the b part of v out of
328 // v to the right destination.
329 k := startIdx(v, s[j:])
331 copy(r[i+len(v):], r[i+k:])
335 // Clone returns a copy of the slice.
336 // The elements are copied using assignment, so this is a shallow clone.
337 func Clone[S ~[]E, E any](s S) S {
338 // The s[:0:0] preserves nil in case it matters.
339 return append(s[:0:0], s...)
342 // Compact replaces consecutive runs of equal elements with a single copy.
343 // This is like the uniq command found on Unix.
344 // Compact modifies the contents of the slice s and returns the modified slice,
345 // which may have a smaller length.
346 // When Compact discards m elements in total, it might not modify the elements
347 // s[len(s)-m:len(s)]. If those elements contain pointers you might consider
348 // zeroing those elements so that objects they reference can be garbage collected.
349 func Compact[S ~[]E, E comparable](s S) S {
354 for k := 1; k < len(s); k++ {
365 // CompactFunc is like [Compact] but uses an equality function to compare elements.
366 // For runs of elements that compare equal, CompactFunc keeps the first one.
367 func CompactFunc[S ~[]E, E any](s S, eq func(E, E) bool) S {
372 for k := 1; k < len(s); k++ {
373 if !eq(s[k], s[k-1]) {
383 // Grow increases the slice's capacity, if necessary, to guarantee space for
384 // another n elements. After Grow(n), at least n elements can be appended
385 // to the slice without another allocation. If n is negative or too large to
386 // allocate the memory, Grow panics.
387 func Grow[S ~[]E, E any](s S, n int) S {
389 panic("cannot be negative")
391 if n -= cap(s) - len(s); n > 0 {
392 s = append(s[:cap(s)], make([]E, n)...)[:len(s)]
397 // Clip removes unused capacity from the slice, returning s[:len(s):len(s)].
398 func Clip[S ~[]E, E any](s S) S {
399 return s[:len(s):len(s)]
402 // Rotation algorithm explanation:
407 // split up like this
409 // swap first 2 and last 2
413 // recursively rotate first left part by 2
421 // split up like this
423 // swap first 2 and last 2
427 // recursively rotate second part left by 6
432 // TODO: There are other rotate algorithms.
433 // This algorithm has the desirable property that it moves each element exactly twice.
434 // The triple-reverse algorithm is simpler and more cache friendly, but takes more writes.
435 // The follow-cycles algorithm can be 1-write but it is not very cache friendly.
437 // rotateLeft rotates b left by n spaces.
438 // s_final[i] = s_orig[i+r], wrapping around.
439 func rotateLeft[E any](s []E, r int) {
440 for r != 0 && r != len(s) {
442 swap(s[:r], s[len(s)-r:])
445 swap(s[:len(s)-r], s[r:])
446 s, r = s[len(s)-r:], r*2-len(s)
450 func rotateRight[E any](s []E, r int) {
451 rotateLeft(s, len(s)-r)
454 // swap swaps the contents of x and y. x and y must be equal length and disjoint.
455 func swap[E any](x, y []E) {
456 for i := 0; i < len(x); i++ {
457 x[i], y[i] = y[i], x[i]
461 // overlaps reports whether the memory ranges a[0:len(a)] and b[0:len(b)] overlap.
462 func overlaps[E any](a, b []E) bool {
463 if len(a) == 0 || len(b) == 0 {
466 elemSize := unsafe.Sizeof(a[0])
470 // TODO: use a runtime/unsafe facility once one becomes available. See issue 12445.
471 // Also see crypto/internal/alias/alias.go:AnyOverlap
472 return uintptr(unsafe.Pointer(&a[0])) <= uintptr(unsafe.Pointer(&b[len(b)-1]))+(elemSize-1) &&
473 uintptr(unsafe.Pointer(&b[0])) <= uintptr(unsafe.Pointer(&a[len(a)-1]))+(elemSize-1)
476 // startIdx returns the index in haystack where the needle starts.
477 // prerequisite: the needle must be aliased entirely inside the haystack.
478 func startIdx[E any](haystack, needle []E) int {
480 for i := range haystack {
481 if p == &haystack[i] {
485 // TODO: what if the overlap is by a non-integral number of Es?
486 panic("needle not found")
489 // Reverse reverses the elements of the slice in place.
490 func Reverse[S ~[]E, E any](s S) {
491 for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
492 s[i], s[j] = s[j], s[i]
496 // Concat returns a new slice concatenating the passed in slices.
497 func Concat[S ~[]E, E any](slices ...S) S {
499 for _, s := range slices {
502 panic("len out of range")
505 newslice := Grow[S](nil, size)
506 for _, s := range slices {
507 newslice = append(newslice, s...)