-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslices.go
More file actions
56 lines (48 loc) · 1.48 KB
/
slices.go
File metadata and controls
56 lines (48 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package nstd
import "unsafe"
// MakeSlice makes a slice with the specified length.
// Different from the built-in [make] function, the capacity
// of the result slice might be larger than the length.
func MakeSlice[S ~[]E, E any](len int) S {
return append(S(nil), make(S, len)...)
}
// MakeSliceWithMinCap makes a slice with capacity not smaller than cap.
// The length of the result slice is zero.
//
// See: https://github.com/golang/go/issues/69872
func MakeSliceWithMinCap[S ~[]E, E any](cap int) S {
return append(S(nil), make(S, cap)...)[:0]
}
// CloneSlice clones a slice.
// Different from [slices.Clone], the result of CloneSlice
// always has equal length and capacity.
func CloneSlice[S ~[]T, T any](s S) S {
var r = make(S, len(s))
copy(r, s)
return r
}
// UnnamedSlice converts s to unnamed type.
func UnnamedSlice[S ~[]T, T any](s S) []T {
return s
}
// MakeOneElemSlice makes a slice containing exact one element from a pointer to element.
// Nil pointers result nil slices.
//
// See: https://github.com/golang/go/issues/76135
func MakeOneElemSlice[T any](e *T) []T {
if e == nil {
return nil
}
return unsafe.Slice(e, 1)
}
// SliceElemPointers returns an iterator which iterates element pointers of a slice.
func SliceElemPointers[E any](s []E) func(func(*E) bool) {
return func(yield func(*E) bool) {
for i := range s {
if !yield(&s[i]) {
break
}
}
}
}
// ToDo: OneElemSlice: https://github.com/golang/go/issues/76109 https://github.com/golang/go/issues/76135