File: slice.go

package info (click to toggle)
golang-github-anacrolix-generics 0.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 184 kB
  • sloc: makefile: 2
file content (73 lines) | stat: -rw-r--r-- 1,703 bytes parent folder | download
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package generics

import (
	"golang.org/x/exp/constraints"
)

// Pops the last element from the slice and returns it. Panics if the slice is empty, or if the
// slice is nil.
func SlicePop[T any](slice *[]T) T {
	lastIndex := len(*slice) - 1
	last := (*slice)[lastIndex]
	*slice = (*slice)[:lastIndex]
	return last
}

func MakeSliceWithLength[T any, L constraints.Integer](slice *[]T, length L) {
	*slice = make([]T, length)
}

func MakeSliceWithCap[T any, L constraints.Integer](slice *[]T, cap L) {
	*slice = make([]T, 0, cap)
}

func Reversed[T any](slice []T) []T {
	reversed := make([]T, len(slice))
	for i := range reversed {
		reversed[i] = slice[len(slice)-1-i]
	}
	return reversed
}

func Singleton[T any](t T) []T {
	return []T{t}
}

// I take it there's no way to do this with a generic return slice element type.
func ConvertToSliceOfAny[T any](ts []T) (ret []any) {
	ret = make([]any, 0, len(ts))
	for _, t := range ts {
		ret = append(ret, t)
	}
	return
}

func ReverseSlice[T any](slice []T) {
	for i := 0; i < len(slice)/2; i++ {
		slice[i], slice[len(slice)-1-i] = slice[len(slice)-1-i], slice[i]
	}
}

func SliceTake[T any](n int, slice []T) []T {
	return slice[:Min(n, len(slice))]
}

func SliceDrop[T any](n int, slice []T) []T {
	return slice[Min(n, len(slice)):]
}

func SliceGet[T any, I constraints.Integer](slice []T, index I) (ret Option[T]) {
	if int(index) < len(slice) {
		ret = Some(slice[index])
	}
	return
}

// Surely you should just pass iterator functions around instead. Go sux.
func SliceMap[From, To any](froms []From, convert func(From) To) []To {
	tos := make([]To, 0, len(froms))
	for _, from := range froms {
		tos = append(tos, convert(from))
	}
	return tos
}