]> Cypherpunks.ru repositories - gostls13.git/blob - src/slices/slices.go
725d91d8f5c151f867a90d55d1164cfe27b5cd1d
[gostls13.git] / src / slices / slices.go
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.
4
5 // Package slices defines various functions useful with slices of any type.
6 package slices
7
8 import (
9         "cmp"
10         "unsafe"
11 )
12
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) {
20                 return false
21         }
22         for i := range s1 {
23                 if s1[i] != s2[i] {
24                         return false
25                 }
26         }
27         return true
28 }
29
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) {
37                 return false
38         }
39         for i, v1 := range s1 {
40                 v2 := s2[i]
41                 if !eq(v1, v2) {
42                         return false
43                 }
44         }
45         return true
46 }
47
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 {
57                 if i >= len(s2) {
58                         return +1
59                 }
60                 v2 := s2[i]
61                 if c := cmp.Compare(v1, v2); c != 0 {
62                         return c
63                 }
64         }
65         if len(s1) < len(s2) {
66                 return -1
67         }
68         return 0
69 }
70
71 // CompareFunc is like [Compare] but uses a custom comparison function on each
72 // pair of elements.
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 {
78                 if i >= len(s2) {
79                         return +1
80                 }
81                 v2 := s2[i]
82                 if c := cmp(v1, v2); c != 0 {
83                         return c
84                 }
85         }
86         if len(s1) < len(s2) {
87                 return -1
88         }
89         return 0
90 }
91
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 {
95         for i := range s {
96                 if v == s[i] {
97                         return i
98                 }
99         }
100         return -1
101 }
102
103 // IndexFunc returns the first index i satisfying f(s[i]),
104 // or -1 if none do.
105 func IndexFunc[S ~[]E, E any](s S, f func(E) bool) int {
106         for i := range s {
107                 if f(s[i]) {
108                         return i
109                 }
110         }
111         return -1
112 }
113
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
117 }
118
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
123 }
124
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 {
133         m := len(v)
134         if m == 0 {
135                 return s
136         }
137         n := len(s)
138         if i == n {
139                 return append(s, v...)
140         }
141         if n+m > cap(s) {
142                 // Use append rather than make so that we bump the size of
143                 // the slice up to the next storage class.
144                 // This is what Grow does but we don't call Grow because
145                 // that might copy the values twice.
146                 s2 := append(s[:i], make(S, n+m-i)...)
147                 copy(s2[i:], v)
148                 copy(s2[i+m:], s[i:])
149                 return s2
150         }
151         s = s[:n+m]
152
153         // before:
154         // s: aaaaaaaabbbbccccccccdddd
155         //            ^   ^       ^   ^
156         //            i  i+m      n  n+m
157         // after:
158         // s: aaaaaaaavvvvbbbbcccccccc
159         //            ^   ^       ^   ^
160         //            i  i+m      n  n+m
161         //
162         // a are the values that don't move in s.
163         // v are the values copied in from v.
164         // b and c are the values from s that are shifted up in index.
165         // d are the values that get overwritten, never to be seen again.
166
167         if !overlaps(v, s[i+m:]) {
168                 // Easy case - v does not overlap either the c or d regions.
169                 // (It might be in some of a or b, or elsewhere entirely.)
170                 // The data we copy up doesn't write to v at all, so just do it.
171
172                 copy(s[i+m:], s[i:])
173
174                 // Now we have
175                 // s: aaaaaaaabbbbbbbbcccccccc
176                 //            ^   ^       ^   ^
177                 //            i  i+m      n  n+m
178                 // Note the b values are duplicated.
179
180                 copy(s[i:], v)
181
182                 // Now we have
183                 // s: aaaaaaaavvvvbbbbcccccccc
184                 //            ^   ^       ^   ^
185                 //            i  i+m      n  n+m
186                 // That's the result we want.
187                 return s
188         }
189
190         // The hard case - v overlaps c or d. We can't just shift up
191         // the data because we'd move or clobber the values we're trying
192         // to insert.
193         // So instead, write v on top of d, then rotate.
194         copy(s[n:], v)
195
196         // Now we have
197         // s: aaaaaaaabbbbccccccccvvvv
198         //            ^   ^       ^   ^
199         //            i  i+m      n  n+m
200
201         rotateRight(s[i:], m)
202
203         // Now we have
204         // s: aaaaaaaavvvvbbbbcccccccc
205         //            ^   ^       ^   ^
206         //            i  i+m      n  n+m
207         // That's the result we want.
208         return s
209 }
210
211 // Delete removes the elements s[i:j] from s, returning the modified slice.
212 // Delete panics if s[i:j] is not a valid slice of s.
213 // Delete is O(len(s)-j), so if many items must be deleted, it is better to
214 // make a single call deleting them all together than to delete one at a time.
215 // Delete might not modify the elements s[len(s)-(j-i):len(s)]. If those
216 // elements contain pointers you might consider zeroing those elements so that
217 // objects they reference can be garbage collected.
218 func Delete[S ~[]E, E any](s S, i, j int) S {
219         _ = s[i:j] // bounds check
220
221         return append(s[:i], s[j:]...)
222 }
223
224 // DeleteFunc removes any elements from s for which del returns true,
225 // returning the modified slice.
226 // When DeleteFunc removes m elements, it might not modify the elements
227 // s[len(s)-m:len(s)]. If those elements contain pointers you might consider
228 // zeroing those elements so that objects they reference can be garbage
229 // collected.
230 func DeleteFunc[S ~[]E, E any](s S, del func(E) bool) S {
231         i := IndexFunc(s, del)
232         if i == -1 {
233                 return s
234         }
235         // Don't start copying elements until we find one to delete.
236         for j := i + 1; j < len(s); j++ {
237                 if v := s[j]; !del(v) {
238                         s[i] = v
239                         i++
240                 }
241         }
242         return s[:i]
243 }
244
245 // Replace replaces the elements s[i:j] by the given v, and returns the
246 // modified slice. Replace panics if s[i:j] is not a valid slice of s.
247 func Replace[S ~[]E, E any](s S, i, j int, v ...E) S {
248         _ = s[i:j] // verify that i:j is a valid subslice
249
250         if i == j {
251                 return Insert(s, i, v...)
252         }
253         if j == len(s) {
254                 return append(s[:i], v...)
255         }
256
257         tot := len(s[:i]) + len(v) + len(s[j:])
258         if tot > cap(s) {
259                 // Too big to fit, allocate and copy over.
260                 s2 := append(s[:i], make(S, tot-i)...) // See Insert
261                 copy(s2[i:], v)
262                 copy(s2[i+len(v):], s[j:])
263                 return s2
264         }
265
266         r := s[:tot]
267
268         if i+len(v) <= j {
269                 // Easy, as v fits in the deleted portion.
270                 copy(r[i:], v)
271                 if i+len(v) != j {
272                         copy(r[i+len(v):], s[j:])
273                 }
274                 return r
275         }
276
277         // We are expanding (v is bigger than j-i).
278         // The situation is something like this:
279         // (example has i=4,j=8,len(s)=16,len(v)=6)
280         // s: aaaaxxxxbbbbbbbbyy
281         //        ^   ^       ^ ^
282         //        i   j  len(s) tot
283         // a: prefix of s
284         // x: deleted range
285         // b: more of s
286         // y: area to expand into
287
288         if !overlaps(r[i+len(v):], v) {
289                 // Easy, as v is not clobbered by the first copy.
290                 copy(r[i+len(v):], s[j:])
291                 copy(r[i:], v)
292                 return r
293         }
294
295         // This is a situation where we don't have a single place to which
296         // we can copy v. Parts of it need to go to two different places.
297         // We want to copy the prefix of v into y and the suffix into x, then
298         // rotate |y| spots to the right.
299         //
300         //        v[2:]      v[:2]
301         //         |           |
302         // s: aaaavvvvbbbbbbbbvv
303         //        ^   ^       ^ ^
304         //        i   j  len(s) tot
305         //
306         // If either of those two destinations don't alias v, then we're good.
307         y := len(v) - (j - i) // length of y portion
308
309         if !overlaps(r[i:j], v) {
310                 copy(r[i:j], v[y:])
311                 copy(r[len(s):], v[:y])
312                 rotateRight(r[i:], y)
313                 return r
314         }
315         if !overlaps(r[len(s):], v) {
316                 copy(r[len(s):], v[:y])
317                 copy(r[i:j], v[y:])
318                 rotateRight(r[i:], y)
319                 return r
320         }
321
322         // Now we know that v overlaps both x and y.
323         // That means that the entirety of b is *inside* v.
324         // So we don't need to preserve b at all; instead we
325         // can copy v first, then copy the b part of v out of
326         // v to the right destination.
327         k := startIdx(v, s[j:])
328         copy(r[i:], v)
329         copy(r[i+len(v):], r[i+k:])
330         return r
331 }
332
333 // Clone returns a copy of the slice.
334 // The elements are copied using assignment, so this is a shallow clone.
335 func Clone[S ~[]E, E any](s S) S {
336         // Preserve nil in case it matters.
337         if s == nil {
338                 return nil
339         }
340         return append(S([]E{}), s...)
341 }
342
343 // Compact replaces consecutive runs of equal elements with a single copy.
344 // This is like the uniq command found on Unix.
345 // Compact modifies the contents of the slice s and returns the modified slice,
346 // which may have a smaller length.
347 // When Compact discards m elements in total, it might not modify the elements
348 // s[len(s)-m:len(s)]. If those elements contain pointers you might consider
349 // zeroing those elements so that objects they reference can be garbage collected.
350 func Compact[S ~[]E, E comparable](s S) S {
351         if len(s) < 2 {
352                 return s
353         }
354         i := 1
355         for k := 1; k < len(s); k++ {
356                 if s[k] != s[k-1] {
357                         if i != k {
358                                 s[i] = s[k]
359                         }
360                         i++
361                 }
362         }
363         return s[:i]
364 }
365
366 // CompactFunc is like [Compact] but uses an equality function to compare elements.
367 // For runs of elements that compare equal, CompactFunc keeps the first one.
368 func CompactFunc[S ~[]E, E any](s S, eq func(E, E) bool) S {
369         if len(s) < 2 {
370                 return s
371         }
372         i := 1
373         for k := 1; k < len(s); k++ {
374                 if !eq(s[k], s[k-1]) {
375                         if i != k {
376                                 s[i] = s[k]
377                         }
378                         i++
379                 }
380         }
381         return s[:i]
382 }
383
384 // Grow increases the slice's capacity, if necessary, to guarantee space for
385 // another n elements. After Grow(n), at least n elements can be appended
386 // to the slice without another allocation. If n is negative or too large to
387 // allocate the memory, Grow panics.
388 func Grow[S ~[]E, E any](s S, n int) S {
389         if n < 0 {
390                 panic("cannot be negative")
391         }
392         if n -= cap(s) - len(s); n > 0 {
393                 s = append(s[:cap(s)], make([]E, n)...)[:len(s)]
394         }
395         return s
396 }
397
398 // Clip removes unused capacity from the slice, returning s[:len(s):len(s)].
399 func Clip[S ~[]E, E any](s S) S {
400         return s[:len(s):len(s)]
401 }
402
403 // Rotation algorithm explanation:
404 //
405 // rotate left by 2
406 // start with
407 //   0123456789
408 // split up like this
409 //   01 234567 89
410 // swap first 2 and last 2
411 //   89 234567 01
412 // join first parts
413 //   89234567 01
414 // recursively rotate first left part by 2
415 //   23456789 01
416 // join at the end
417 //   2345678901
418 //
419 // rotate left by 8
420 // start with
421 //   0123456789
422 // split up like this
423 //   01 234567 89
424 // swap first 2 and last 2
425 //   89 234567 01
426 // join last parts
427 //   89 23456701
428 // recursively rotate second part left by 6
429 //   89 01234567
430 // join at the end
431 //   8901234567
432
433 // TODO: There are other rotate algorithms.
434 // This algorithm has the desirable property that it moves each element exactly twice.
435 // The triple-reverse algorithm is simpler and more cache friendly, but takes more writes.
436 // The follow-cycles algorithm can be 1-write but it is not very cache friendly.
437
438 // rotateLeft rotates b left by n spaces.
439 // s_final[i] = s_orig[i+r], wrapping around.
440 func rotateLeft[E any](s []E, r int) {
441         for r != 0 && r != len(s) {
442                 if r*2 <= len(s) {
443                         swap(s[:r], s[len(s)-r:])
444                         s = s[:len(s)-r]
445                 } else {
446                         swap(s[:len(s)-r], s[r:])
447                         s, r = s[len(s)-r:], r*2-len(s)
448                 }
449         }
450 }
451 func rotateRight[E any](s []E, r int) {
452         rotateLeft(s, len(s)-r)
453 }
454
455 // swap swaps the contents of x and y. x and y must be equal length and disjoint.
456 func swap[E any](x, y []E) {
457         for i := 0; i < len(x); i++ {
458                 x[i], y[i] = y[i], x[i]
459         }
460 }
461
462 // overlaps reports whether the memory ranges a[0:len(a)] and b[0:len(b)] overlap.
463 func overlaps[E any](a, b []E) bool {
464         if len(a) == 0 || len(b) == 0 {
465                 return false
466         }
467         elemSize := unsafe.Sizeof(a[0])
468         if elemSize == 0 {
469                 return false
470         }
471         // TODO: use a runtime/unsafe facility once one becomes available. See issue 12445.
472         // Also see crypto/internal/alias/alias.go:AnyOverlap
473         return uintptr(unsafe.Pointer(&a[0])) <= uintptr(unsafe.Pointer(&b[len(b)-1]))+(elemSize-1) &&
474                 uintptr(unsafe.Pointer(&b[0])) <= uintptr(unsafe.Pointer(&a[len(a)-1]))+(elemSize-1)
475 }
476
477 // startIdx returns the index in haystack where the needle starts.
478 // prerequisite: the needle must be aliased entirely inside the haystack.
479 func startIdx[E any](haystack, needle []E) int {
480         p := &needle[0]
481         for i := range haystack {
482                 if p == &haystack[i] {
483                         return i
484                 }
485         }
486         // TODO: what if the overlap is by a non-integral number of Es?
487         panic("needle not found")
488 }
489
490 // Reverse reverses the elements of the slice in place.
491 func Reverse[S ~[]E, E any](s S) {
492         for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
493                 s[i], s[j] = s[j], s[i]
494         }
495 }