diff options
author | obscuren <geffobscura@gmail.com> | 2014-09-23 01:34:31 +0800 |
---|---|---|
committer | obscuren <geffobscura@gmail.com> | 2014-09-23 01:34:31 +0800 |
commit | ce149d2733bd55e8e9b16dd4b60b6bad17c3d7d9 (patch) | |
tree | ac183aa3312a4589cb3e4995cc103cfa58ef95da /ethutil/list.go | |
parent | 8ef17c2fb138ae254a0cc7ac509a7ab1177ee4ac (diff) | |
parent | 7d08e4f7d14600ee4ed38fc9d435e9c2e0e0fdac (diff) | |
download | dexon-ce149d2733bd55e8e9b16dd4b60b6bad17c3d7d9.tar dexon-ce149d2733bd55e8e9b16dd4b60b6bad17c3d7d9.tar.gz dexon-ce149d2733bd55e8e9b16dd4b60b6bad17c3d7d9.tar.bz2 dexon-ce149d2733bd55e8e9b16dd4b60b6bad17c3d7d9.tar.lz dexon-ce149d2733bd55e8e9b16dd4b60b6bad17c3d7d9.tar.xz dexon-ce149d2733bd55e8e9b16dd4b60b6bad17c3d7d9.tar.zst dexon-ce149d2733bd55e8e9b16dd4b60b6bad17c3d7d9.zip |
Merge branch 'release/0.6.5'
Diffstat (limited to 'ethutil/list.go')
-rw-r--r-- | ethutil/list.go | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/ethutil/list.go b/ethutil/list.go new file mode 100644 index 000000000..9db96cf18 --- /dev/null +++ b/ethutil/list.go @@ -0,0 +1,61 @@ +package ethutil + +import ( + "encoding/json" + "reflect" +) + +// The list type is an anonymous slice handler which can be used +// for containing any slice type to use in an environment which +// does not support slice types (e.g., JavaScript, QML) +type List struct { + list reflect.Value + Length int +} + +// Initialise a new list. Panics if non-slice type is given. +func NewList(t interface{}) *List { + list := reflect.ValueOf(t) + if list.Kind() != reflect.Slice { + panic("list container initialized with a non-slice type") + } + + return &List{list, list.Len()} +} + +func EmptyList() *List { + return NewList([]interface{}{}) +} + +// Get N element from the embedded slice. Returns nil if OOB. +func (self *List) Get(i int) interface{} { + if self.list.Len() > i { + return self.list.Index(i).Interface() + } + + return nil +} + +// Appends value at the end of the slice. Panics when incompatible value +// is given. +func (self *List) Append(v interface{}) { + self.list = reflect.Append(self.list, reflect.ValueOf(v)) + self.Length = self.list.Len() +} + +// Returns the underlying slice as interface. +func (self *List) Interface() interface{} { + return self.list.Interface() +} + +// For JavaScript <3 +func (self *List) ToJSON() string { + var list []interface{} + for i := 0; i < self.Length; i++ { + list = append(list, self.Get(i)) + } + + data, _ := json.Marshal(list) + + return string(data) +} |