tuple immutable
This commit is contained in:
24
tuple.go
24
tuple.go
@@ -1,19 +1,23 @@
|
||||
package extypes
|
||||
|
||||
import "reflect"
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
type Tuple[T any] struct {
|
||||
s Slice[T]
|
||||
}
|
||||
|
||||
func NewTupleFrom[T any](src []T) Tuple[T] {
|
||||
return Tuple[T]{src}
|
||||
}
|
||||
func (t Tuple[T]) Len() int { return t.s.Len() }
|
||||
func (t Tuple[T]) Cap() int { return t.s.Cap() }
|
||||
func (t Tuple[T]) Get(index int) T { return t.s.Get(index) }
|
||||
func NewTupleFrom[T any](src []T) Tuple[T] { return Tuple[T]{src} }
|
||||
func NewTuple[T any]() Tuple[T] { return Tuple[T]{make(Slice[T], 0)} }
|
||||
func (t Tuple[T]) Len() int { return t.s.Len() }
|
||||
func (t Tuple[T]) Cap() int { return t.s.Cap() }
|
||||
func (t Tuple[T]) Get(index int) T { return t.s.Get(index) }
|
||||
|
||||
func (t Tuple[T]) Equal(t2 Tuple[T]) bool {
|
||||
if t.Len() != t2.Len() || t.Cap() != t2.Cap() {
|
||||
if t.Len() != t2.Len() {
|
||||
return false
|
||||
}
|
||||
for i := range t.s {
|
||||
@@ -55,3 +59,7 @@ func (t Tuple[T]) ForEach(f func(int, T)) Tuple[T] {
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func (t Tuple[T]) String() string { return fmt.Sprint(t.s) }
|
||||
func (t *Tuple[T]) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, &t.s) }
|
||||
func (t Tuple[T]) MarshalJSON() ([]byte, error) { return json.Marshal(t.s) }
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package extypes
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTuple(t *testing.T) {
|
||||
t1 := NewTupleFrom([]int{1, 2, 3})
|
||||
@@ -10,3 +13,37 @@ func TestTuple(t *testing.T) {
|
||||
t.Error("t1 and t2 should be equal")
|
||||
}
|
||||
}
|
||||
func TestTuple_MarshalJSON(t *testing.T) {
|
||||
t1 := NewTupleFrom([]int{1, 2, 3})
|
||||
data, err := json.Marshal(t1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := "[1,2,3]"
|
||||
if string(data) != s {
|
||||
t.Error("t1 and t2 should be equal")
|
||||
}
|
||||
}
|
||||
func TestTuple_UnmarshalJSON(t *testing.T) {
|
||||
s := "[1,2,3]"
|
||||
t1 := NewTuple[int]()
|
||||
err := json.Unmarshal([]byte(s), &t1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t2 := NewTupleFrom([]int{1, 2, 3})
|
||||
t.Log(t1, t2)
|
||||
if !t1.Equal(t2) {
|
||||
t.Error("t1 and t2 should be equal")
|
||||
}
|
||||
|
||||
st1 := struct {
|
||||
A int `json:"a"`
|
||||
B Tuple[int] `json:"b"`
|
||||
}{}
|
||||
s2 := `{"a":1,"b":[1,2,3]}`
|
||||
if err := json.Unmarshal([]byte(s2), &st1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Log(st1)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user