forked from jianfengye/collection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
str_collection.go
109 lines (92 loc) · 2.17 KB
/
str_collection.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package collection
import (
"encoding/json"
"errors"
"fmt"
"strings"
)
type StrCollection struct {
AbsCollection
objs []string
}
func compareString(a interface{}, b interface{}) int {
as := a.(string)
bs := b.(string)
return strings.Compare(as, bs)
}
func NewStrCollection(objs []string) *StrCollection {
arr := &StrCollection{
objs: objs,
}
arr.AbsCollection.compare = compareString
arr.AbsCollection.Parent = arr
return arr
}
// Copy copy collection
func (arr *StrCollection) Copy() ICollection {
objs2 := make([]string, len(arr.objs))
copy(objs2, arr.objs)
arr.objs = objs2
return arr
}
func (arr *StrCollection) NewEmpty(err ...error) ICollection {
arr2 := NewStrCollection([]string{})
if len(err) != 0 {
arr2.SetErr(err[0])
}
return arr2
}
func (arr *StrCollection) Insert(index int, obj interface{}) ICollection {
if arr.Err() != nil {
return arr
}
if i, ok := obj.(string); ok {
length := len(arr.objs)
// 如果是append操作,直接调用系统的append,不新创建collection
if index >= length {
arr.objs = append(arr.objs, i)
return arr
}
arr.objs = append(arr.objs, "0")
copy(arr.objs[index+1:], arr.objs[index:])
arr.objs[index] = i
} else {
return arr.SetErr(errors.New("Insert: type error"))
}
return arr
}
func (arr *StrCollection) Remove(i int) ICollection {
if arr.Err() != nil {
return arr
}
len := arr.Count()
if i >= len {
return arr.SetErr(errors.New("index exceeded"))
}
arr.objs = append(arr.objs[0:i], arr.objs[i+1:len]...)
return arr
}
func (arr *StrCollection) Index(i int) IMix {
return NewMix(arr.objs[i]).SetCompare(arr.compare)
}
func (arr *StrCollection) SetIndex(i int, val interface{}) ICollection {
arr.objs[i] = val.(string)
return arr
}
func (arr *StrCollection) Count() int {
return len(arr.objs)
}
func (arr *StrCollection) DD() {
ret := fmt.Sprintf("StrCollection(%d):{\n", arr.Count())
for k, v := range arr.objs {
ret = ret + fmt.Sprintf("\t%d:\t%s\n", k, v)
}
ret = ret + "}\n"
fmt.Print(ret)
}
func (arr *StrCollection) ToJson() ([]byte, error) {
return json.Marshal(arr.objs)
}
func (arr *StrCollection) FromJson(data []byte) error {
return json.Unmarshal(data, &(arr.objs))
}