list.go 1.63 KB
Newer Older
1 2
package ethutil

obscuren's avatar
obscuren committed
3 4 5
import (
	"encoding/json"
	"reflect"
obscuren's avatar
obscuren committed
6
	"sync"
obscuren's avatar
obscuren committed
7
)
8 9 10 11 12

// 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 {
obscuren's avatar
obscuren committed
13
	mut    sync.Mutex
obscuren's avatar
obscuren committed
14
	val    interface{}
15 16 17 18 19 20 21 22 23 24 25
	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")
	}

obscuren's avatar
obscuren committed
26
	return &List{sync.Mutex{}, t, list, list.Len()}
27 28
}

obscuren's avatar
obscuren committed
29 30 31 32
func EmptyList() *List {
	return NewList([]interface{}{})
}

33 34 35
// Get N element from the embedded slice. Returns nil if OOB.
func (self *List) Get(i int) interface{} {
	if self.list.Len() > i {
obscuren's avatar
obscuren committed
36 37 38
		self.mut.Lock()
		defer self.mut.Unlock()

obscuren's avatar
obscuren committed
39 40 41
		i := self.list.Index(i).Interface()

		return i
42 43 44 45 46
	}

	return nil
}

obscuren's avatar
obscuren committed
47 48 49 50 51 52 53 54
func (self *List) GetAsJson(i int) interface{} {
	e := self.Get(i)

	r, _ := json.Marshal(e)

	return string(r)
}

55 56 57
// Appends value at the end of the slice. Panics when incompatible value
// is given.
func (self *List) Append(v interface{}) {
obscuren's avatar
obscuren committed
58 59 60
	self.mut.Lock()
	defer self.mut.Unlock()

61 62 63 64 65 66 67 68
	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()
}
obscuren's avatar
obscuren committed
69 70 71

// For JavaScript <3
func (self *List) ToJSON() string {
obscuren's avatar
obscuren committed
72 73
	// make(T, 0) != nil
	list := make([]interface{}, 0)
obscuren's avatar
obscuren committed
74 75 76 77 78 79 80 81
	for i := 0; i < self.Length; i++ {
		list = append(list, self.Get(i))
	}

	data, _ := json.Marshal(list)

	return string(data)
}