add lang.Slice

This commit is contained in:
tursom 2022-11-27 18:34:18 +08:00
parent 96bcf656d8
commit a839508b27
4 changed files with 73 additions and 15 deletions

View File

@ -7,9 +7,20 @@
package lang
import (
"reflect"
"unsafe"
)
func TypeName[T any]() string {
t := reflect.TypeOf(Nil[T]())
return t.Name()
}
func TypeNameOf(v any) string {
t := reflect.TypeOf(v)
return t.Name()
}
func Nil[T any]() T {
var n T
return n
@ -33,28 +44,18 @@ func TryCast[T any](v any) (T, bool) {
}
func Cast[T any](v any) T {
defer func() {
r := recover()
if r != nil {
panic(NewTypeCastException("", r, nil))
}
}()
if v == nil {
return Nil[T]()
} else {
return v.(T)
t, ok := v.(T)
if !ok {
panic(NewTypeCastException2[T](v, nil))
}
return t
}
}
func ForceCast[T any](v unsafe.Pointer) *T {
defer func() {
r := recover()
if r != nil {
panic(NewTypeCastException("", r, nil))
}
}()
if v == nil {
return nil
} else {

31
lang/Slice.go Normal file
View File

@ -0,0 +1,31 @@
/*
* Copyright (c) 2022 tursom. All rights reserved.
* Use of this source code is governed by a GPL-3
* license that can be found in the LICENSE file.
*/
package lang
type Slice[T Object] []T
func NewSlice[T Object](size, cap int) Slice[T] {
return make(Slice[T], size, cap)
}
func (s Slice[T]) Contains(value T) bool {
for _, e := range s {
if e.Equals(value) {
return true
}
}
return false
}
func (s *Slice[T]) Append(value T) {
*s = append(*s, value)
}
func (s Slice[T]) Size() int {
return len(s)
}

20
lang/Slice_test.go Normal file
View File

@ -0,0 +1,20 @@
/*
* Copyright (c) 2022 tursom. All rights reserved.
* Use of this source code is governed by a GPL-3
* license that can be found in the LICENSE file.
*/
package lang
import (
"fmt"
"testing"
)
func TestSlice_Append(t *testing.T) {
s := NewSlice[Int](0, 0)
for i := 0; i < 16; i++ {
s.Append(Int(i))
fmt.Println(s)
}
}

View File

@ -6,6 +6,8 @@
package lang
import "fmt"
type TypeCastException struct {
RuntimeException
}
@ -21,3 +23,7 @@ func NewTypeCastException(message string, err any, config *ExceptionConfig) *Typ
SetExceptionName("github.com.tursom.GoCollections.exceptions.TypeCastException")),
}
}
func NewTypeCastException2[T any](v any, config *ExceptionConfig) *TypeCastException {
return NewTypeCastException(fmt.Sprintf("type %s cannot cast to %s", TypeNameOf(v), TypeName[T]()), nil, config)
}