forked from vtopc/go-airmat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmattress.go
51 lines (40 loc) · 823 Bytes
/
mattress.go
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
package airmat
// Mattress is a container for a Slice.
// Slice should be updated by the index, not with append(...) func.
type Mattress[T any] struct {
Slice []T
}
func NewMattress[T any](size int) *Mattress[T] {
return &Mattress[T]{
Slice: make([]T, size),
}
}
// SetSize extends or shrinks length of underlying Slice.
func (m *Mattress[T]) SetSize(size int) {
if m.Slice == nil {
m.Slice = make([]T, size)
return
}
l := len(m.Slice)
switch {
case l == size:
break
case l < size:
m.extend(size)
case l > size:
m.shrink(size)
}
}
func (m *Mattress[T]) extend(l int) {
diff := l - len(m.Slice)
// if diff < 0 {
// return
// }
m.Slice = append(m.Slice, make([]T, diff)...)
}
func (m *Mattress[T]) shrink(l int) {
// if len(m.Slice) < len {
// return
// }
m.Slice = m.Slice[:l]
}