github.com/database64128/shadowsocks-go@v1.7.0/slices/slices.go (about) 1 package slices 2 3 // Equal reports whether two slices are equal: the same length and all 4 // elements equal. If the lengths are different, Equal returns false. 5 // Otherwise, the elements are compared in increasing index order, and the 6 // comparison stops at the first unequal pair. 7 // Floating point NaNs are not considered equal. 8 func Equal[E comparable](s1, s2 []E) bool { 9 if len(s1) != len(s2) { 10 return false 11 } 12 for i := range s1 { 13 if s1[i] != s2[i] { 14 return false 15 } 16 } 17 return true 18 } 19 20 // Contains reports whether v is present in s. 21 func Contains[E comparable](s []E, v E) bool { 22 for i := range s { 23 if v == s[i] { 24 return true 25 } 26 } 27 return false 28 } 29 30 // Insert inserts the values v... into s at index i, 31 // returning the modified slice. 32 // In the returned slice r, r[i] == v[0]. 33 // Insert panics if i is out of range. 34 // This function is O(len(s) + len(v)). 35 func Insert[S ~[]E, E any](s S, i int, v ...E) S { 36 tot := len(s) + len(v) 37 if tot <= cap(s) { 38 s2 := s[:tot] 39 copy(s2[i+len(v):], s[i:]) 40 copy(s2[i:], v) 41 return s2 42 } 43 s2 := make(S, tot) 44 copy(s2, s[:i]) 45 copy(s2[i:], v) 46 copy(s2[i+len(v):], s[i:]) 47 return s2 48 } 49 50 // Extend extends the input slice by n elements. head is the full extended 51 // slice, while tail is the appended part. If the original slice has sufficient 52 // capacity no allocation is performed. 53 func Extend[E any](in []E, n int) (head, tail []E) { 54 if total := len(in) + n; cap(in) >= total { 55 head = in[:total] 56 } else { 57 head = make([]E, total) 58 copy(head, in) 59 } 60 tail = head[len(in):] 61 return 62 }