/
slices.go
61 lines (56 loc) · 1.81 KB
/
slices.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
52
53
54
55
56
57
58
59
60
61
package reflection
import (
"fmt"
"reflect"
)
// AppendDefaultSliceElement appends a field to slice with the
// value returned by GetDefaultValue for the former last slice
// element, or the zero value of the type if the slice was empty.
func AppendDefaultSliceElement(slice reflect.Value) reflect.Value {
if slice.Kind() != reflect.Slice {
panic(fmt.Errorf("Expected slice type, got %T", slice.Interface()))
}
var newField reflect.Value
if slice.Len() > 0 {
newField = GetDefaultValue(slice.Index(slice.Len() - 1))
} else {
newField = reflect.Zero(slice.Type().Elem())
}
return reflect.Append(slice, newField)
}
// SetSliceLengh sets the length of a slice by sub-slicing a slice that's too long,
// or appending empty fields with the result of AppendDefaultSliceElement.
func SetSliceLengh(slice reflect.Value, length int) reflect.Value {
if length > slice.Len() {
for i := slice.Len(); i < length; i++ {
slice = AppendDefaultSliceElement(slice)
}
} else if length < slice.Len() {
slice = slice.Slice(0, length)
}
return slice
}
// DeleteDefaultSliceElementsVal deletes slice elements where IsDefaultValue
// returns true.
func DeleteDefaultSliceElementsVal(slice reflect.Value) reflect.Value {
if slice.Kind() != reflect.Slice {
panic(fmt.Errorf("Expected slice type, got %T", slice.Interface()))
}
for i := slice.Len() - 1; i >= 0; i-- {
if IsDefaultValue(slice.Index(i)) {
before := slice.Slice(0, i)
if i == slice.Len()-1 {
slice = before
} else {
after := slice.Slice(i+1, slice.Len())
slice = reflect.AppendSlice(before, after)
}
}
}
return slice
}
// DeleteDefaultSliceElements deletes slice elements where IsDefaultValue
// returns true.
func DeleteDefaultSliceElements(slice interface{}) interface{} {
return DeleteDefaultSliceElementsVal(reflect.ValueOf(slice)).Interface()
}