OSDN Git Service

new repo
[bytom/vapor.git] / common / list.go
1 package common
2
3 import (
4         "encoding/json"
5         "reflect"
6         "sync"
7 )
8
9 // The list type is an anonymous slice handler which can be used
10 // for containing any slice type to use in an environment which
11 // does not support slice types (e.g., JavaScript, QML)
12 type List struct {
13         mut    sync.Mutex
14         val    interface{}
15         list   reflect.Value
16         Length int
17 }
18
19 // Initialise a new list. Panics if non-slice type is given.
20 func NewList(t interface{}) *List {
21         list := reflect.ValueOf(t)
22         if list.Kind() != reflect.Slice {
23                 panic("list container initialized with a non-slice type")
24         }
25
26         return &List{sync.Mutex{}, t, list, list.Len()}
27 }
28
29 func EmptyList() *List {
30         return NewList([]interface{}{})
31 }
32
33 // Get N element from the embedded slice. Returns nil if OOB.
34 func (self *List) Get(i int) interface{} {
35         if self.list.Len() > i {
36                 self.mut.Lock()
37                 defer self.mut.Unlock()
38
39                 i := self.list.Index(i).Interface()
40
41                 return i
42         }
43
44         return nil
45 }
46
47 func (self *List) GetAsJson(i int) interface{} {
48         e := self.Get(i)
49         r, _ := json.Marshal(e)
50         return string(r)
51 }
52
53 // Appends value at the end of the slice. Panics when incompatible value
54 // is given.
55 func (self *List) Append(v interface{}) {
56         self.mut.Lock()
57         defer self.mut.Unlock()
58
59         self.list = reflect.Append(self.list, reflect.ValueOf(v))
60         self.Length = self.list.Len()
61 }
62
63 // Returns the underlying slice as interface.
64 func (self *List) Interface() interface{} {
65         return self.list.Interface()
66 }
67
68 // For JavaScript <3
69 func (self *List) ToJSON() string {
70         // make(T, 0) != nil
71         list := make([]interface{}, 0)
72         for i := 0; i < self.Length; i++ {
73                 list = append(list, self.Get(i))
74         }
75         data, _ := json.Marshal(list)
76         return string(data)
77 }