mirror of
https://github.com/duke-git/lancet.git
synced 2026-11-16 05:12:11 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eb9ad10f25 | ||
|
|
22316061d8 | ||
|
|
5774d0e95e | ||
|
|
9555cb2fc5 | ||
|
|
9b0a0caa75 | ||
|
|
ec11fdf345 | ||
|
|
172712df30 | ||
|
|
a296281408 | ||
|
|
f220ea4c3f | ||
|
|
129da3f2ed | ||
|
|
65806afc7d | ||
|
|
4db163b4b7 | ||
|
|
0f4f73fbba | ||
|
|
145959ee62 | ||
|
|
33a7e5bf6d | ||
|
|
99ed115de4 | ||
|
|
34c7e36d29 | ||
|
|
59cd9bd06f | ||
|
|
18e9bc9cda | ||
|
|
b282ada39e | ||
|
|
b40eea78c3 | ||
|
|
c701a35586 | ||
|
|
778bd2e14f | ||
|
|
86dc6c0019 | ||
|
|
417cf68bd8 | ||
|
|
cb45ef2d36 | ||
|
|
3811d3db8e | ||
|
|
e2524f4498 | ||
|
|
7c77aa00fb | ||
|
|
eb3b1e33d2 | ||
|
|
752f1ed63d | ||
|
|
5c04ffae97 | ||
|
|
f1db13387b | ||
|
|
be9b167a9b | ||
|
|
febd1030af | ||
|
|
fe4c81a677 | ||
|
|
8225b6d7d9 | ||
|
|
6ff2966d50 | ||
|
|
70b8fc764e | ||
|
|
f525703d9f | ||
|
|
be3bc0c43f | ||
|
|
9685357daf | ||
|
|
9a8b67ac85 | ||
|
|
19ccb13893 | ||
|
|
ef22b5b339 | ||
|
|
3b94ec1932 | ||
|
|
e49a01e725 | ||
|
|
13b7b1c61e | ||
|
|
227501958f | ||
|
|
835111c832 | ||
|
|
747dddee8b | ||
|
|
cf1b27a35a | ||
|
|
d2103346c4 | ||
|
|
ce3967b1d5 | ||
|
|
de682f2214 | ||
|
|
b252b415fa | ||
|
|
c0841d7be5 | ||
|
|
b3fd282b50 | ||
|
|
a1cebec9f2 | ||
|
|
88cf1600e8 | ||
|
|
0851b68b83 | ||
|
|
5c13fd4f2f | ||
|
|
889d0cc3d6 | ||
|
|
aa05027cab | ||
|
|
fabc3483ed | ||
|
|
30363242bb | ||
|
|
5d3964d81a | ||
|
|
6c3dc3e7d6 | ||
|
|
2a2e1ca551 | ||
|
|
e1821eed2c | ||
|
|
62f0a96d91 | ||
|
|
cbdc3971dd | ||
|
|
350450bb67 | ||
|
|
f407e51b24 | ||
|
|
3c6c3a14cf | ||
|
|
41bafdef92 | ||
|
|
fc624195c7 | ||
|
|
5b3a59e785 | ||
|
|
74abb2d3f1 | ||
|
|
3f12b34eea | ||
|
|
cd43004a91 | ||
|
|
3ac9461c00 | ||
|
|
309b07ae8a | ||
|
|
8fe56b6dc7 | ||
|
|
15a0dad0d8 | ||
|
|
93c777a418 | ||
|
|
5ff1c6578f | ||
|
|
7d4b9510a2 | ||
|
|
9f0ad2354a | ||
|
|
55b66dee99 | ||
|
|
4c64a16204 | ||
|
|
385e64cc52 | ||
|
|
be45a259db | ||
|
|
6f703fe577 | ||
|
|
cb8d93c499 | ||
|
|
ae1014c572 | ||
|
|
d5b9e67330 | ||
|
|
a81403766f | ||
|
|
83c069e234 |
No files matched your search
+2202
-2066
File diff suppressed because it is too large.
Load diff
@@ -77,6 +77,7 @@ func (l *LRUCache[K, V]) Delete(key K) bool {
|
|||||||
if ok {
|
if ok {
|
||||||
key := l.deleteNode(node)
|
key := l.deleteNode(node)
|
||||||
delete(l.cache, key)
|
delete(l.cache, key)
|
||||||
|
l.length = len(l.cache)
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
l.length = len(l.cache)
|
l.length = len(l.cache)
|
||||||
|
|||||||
@@ -32,3 +32,27 @@ func TestLRUCache(t *testing.T) {
|
|||||||
_, ok = cache.Get(2)
|
_, ok = cache.Get(2)
|
||||||
assert.Equal(false, ok)
|
assert.Equal(false, ok)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestLRUCacheDeleteLen(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
cache := NewLRUCache[int, int](3)
|
||||||
|
for key := 1; key <= 3; key++ {
|
||||||
|
cache.Put(key, key)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, key := range []int{2, 1, 3} {
|
||||||
|
before := cache.Len()
|
||||||
|
if !cache.Delete(key) {
|
||||||
|
t.Fatalf("Delete(%d) = false, want true", key)
|
||||||
|
}
|
||||||
|
if got := cache.Len(); got != before-1 {
|
||||||
|
t.Fatalf("Len() after Delete(%d) = %d, want %d", key, got, before-1)
|
||||||
|
}
|
||||||
|
if cache.Delete(key) {
|
||||||
|
t.Fatalf("Delete(%d) = true for a missing key", key)
|
||||||
|
}
|
||||||
|
if got := cache.Len(); got != before-1 {
|
||||||
|
t.Fatalf("Len() after missing Delete(%d) = %d, want %d", key, got, before-1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -45,6 +45,9 @@ func BinarySearch[T any](sortedSlice []T, target T, lowIndex, highIndex int, com
|
|||||||
// If not found return -1.
|
// If not found return -1.
|
||||||
// Play: https://go.dev/play/p/Anozfr8ZLH3
|
// Play: https://go.dev/play/p/Anozfr8ZLH3
|
||||||
func BinaryIterativeSearch[T any](sortedSlice []T, target T, lowIndex, highIndex int, comparator constraints.Comparator) int {
|
func BinaryIterativeSearch[T any](sortedSlice []T, target T, lowIndex, highIndex int, comparator constraints.Comparator) int {
|
||||||
|
if len(sortedSlice) == 0 {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
startIndex := lowIndex
|
startIndex := lowIndex
|
||||||
endIndex := highIndex
|
endIndex := highIndex
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package algorithm
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestBinaryIterativeSearchEmpty(t *testing.T) {
|
||||||
|
for _, source := range [][]int{nil, {}} {
|
||||||
|
if got := BinaryIterativeSearch(source, 1, 0, 0, &intComparator{}); got != -1 {
|
||||||
|
t.Errorf("got %d, want -1", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-1
@@ -188,7 +188,8 @@ func CountSort[T any](slice []T, comparator constraints.Comparator) []T {
|
|||||||
count := 0
|
count := 0
|
||||||
for j := 0; j < size; j++ {
|
for j := 0; j < size; j++ {
|
||||||
//slice[i] > slice[j]
|
//slice[i] > slice[j]
|
||||||
if comparator.Compare(slice[i], slice[j]) == 1 {
|
order := comparator.Compare(slice[i], slice[j])
|
||||||
|
if order == 1 || (order == 0 && j < i) {
|
||||||
count++
|
count++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -199,6 +199,9 @@ func TestMergeSort(t *testing.T) {
|
|||||||
func TestCountSort(t *testing.T) {
|
func TestCountSort(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
assert := internal.NewAssert(t, "TestCountSort")
|
assert := internal.NewAssert(t, "TestCountSort")
|
||||||
|
assert.Equal([]int{1, 2, 2}, CountSort([]int{2, 1, 2}, &intComparator{}))
|
||||||
|
assert.Equal([]people{{"young", 10}, {"first", 20}, {"second", 20}},
|
||||||
|
CountSort([]people{{"first", 20}, {"young", 10}, {"second", 20}}, &peopleAgeComparator{}))
|
||||||
|
|
||||||
peoples := []people{
|
peoples := []people{
|
||||||
{Name: "a", Age: 20},
|
{Name: "a", Age: 20},
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package convertor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/duke-git/lancet/v2/internal"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDeepCloneScalarTypes(t *testing.T) {
|
||||||
|
assert := internal.NewAssert(t, "TestDeepCloneScalarTypes")
|
||||||
|
type label string
|
||||||
|
type counter int64
|
||||||
|
assert.Equal(label("value"), DeepClone(label("value")))
|
||||||
|
assert.Equal(counter(42), DeepClone(counter(42)))
|
||||||
|
assert.Equal(uintptr(42), DeepClone(uintptr(42)))
|
||||||
|
value := label("pointed")
|
||||||
|
cloned := DeepClone(&value)
|
||||||
|
assert.Equal(value, *cloned)
|
||||||
|
*cloned = "changed"
|
||||||
|
assert.Equal(label("pointed"), value)
|
||||||
|
var empty any
|
||||||
|
assert.Equal(&empty, DeepClone(&empty))
|
||||||
|
}
|
||||||
+50
-14
@@ -228,6 +228,42 @@ func ToPointer[T any](value T) *T {
|
|||||||
return &value
|
return &value
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ToPointers convert a slice of values to a slice of pointers.
|
||||||
|
// Play: https://go.dev/play/p/ZUoXd2i5ZkV
|
||||||
|
func ToPointers[T any](values []T) []*T {
|
||||||
|
result := make([]*T, len(values))
|
||||||
|
for i := range values {
|
||||||
|
result[i] = &values[i]
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// FromPointer returns the value pointed to by the pointer.
|
||||||
|
// Play: https://go.dev/play/p/wAp90V7Zu6g
|
||||||
|
func FromPointer[T any](ptr *T) T {
|
||||||
|
if ptr == nil {
|
||||||
|
var zeroValue T
|
||||||
|
return zeroValue
|
||||||
|
}
|
||||||
|
|
||||||
|
return *ptr
|
||||||
|
}
|
||||||
|
|
||||||
|
// FromPointers convert a slice of pointers to a slice of values.
|
||||||
|
// Play: https://go.dev/play/p/qIPsyYtNy3Q
|
||||||
|
func FromPointers[T any](pointers []*T) []T {
|
||||||
|
result := make([]T, len(pointers))
|
||||||
|
for i, ptr := range pointers {
|
||||||
|
if ptr == nil {
|
||||||
|
var zeroValue T
|
||||||
|
result[i] = zeroValue
|
||||||
|
} else {
|
||||||
|
result[i] = *ptr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
// ToMap convert a slice of structs to a map based on iteratee function.
|
// ToMap convert a slice of structs to a map based on iteratee function.
|
||||||
// Play: https://go.dev/play/p/tVFy7E-t24l
|
// Play: https://go.dev/play/p/tVFy7E-t24l
|
||||||
func ToMap[T any, K comparable, V any](array []T, iteratee func(T) (K, V)) map[K]V {
|
func ToMap[T any, K comparable, V any](array []T, iteratee func(T) (K, V)) map[K]V {
|
||||||
@@ -406,15 +442,15 @@ func ToStdBase64(value any) string {
|
|||||||
if value == nil || (reflect.ValueOf(value).Kind() == reflect.Ptr && reflect.ValueOf(value).IsNil()) {
|
if value == nil || (reflect.ValueOf(value).Kind() == reflect.Ptr && reflect.ValueOf(value).IsNil()) {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
switch value.(type) {
|
switch v := value.(type) {
|
||||||
case []byte:
|
case []byte:
|
||||||
return base64.StdEncoding.EncodeToString(value.([]byte))
|
return base64.StdEncoding.EncodeToString(v)
|
||||||
case string:
|
case string:
|
||||||
return base64.StdEncoding.EncodeToString([]byte(value.(string)))
|
return base64.StdEncoding.EncodeToString([]byte(v))
|
||||||
case error:
|
case error:
|
||||||
return base64.StdEncoding.EncodeToString([]byte(value.(error).Error()))
|
return base64.StdEncoding.EncodeToString([]byte(v.Error()))
|
||||||
default:
|
default:
|
||||||
marshal, err := json.Marshal(value)
|
marshal, err := json.Marshal(v)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
@@ -428,15 +464,15 @@ func ToUrlBase64(value any) string {
|
|||||||
if value == nil || (reflect.ValueOf(value).Kind() == reflect.Ptr && reflect.ValueOf(value).IsNil()) {
|
if value == nil || (reflect.ValueOf(value).Kind() == reflect.Ptr && reflect.ValueOf(value).IsNil()) {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
switch value.(type) {
|
switch v := value.(type) {
|
||||||
case []byte:
|
case []byte:
|
||||||
return base64.URLEncoding.EncodeToString(value.([]byte))
|
return base64.URLEncoding.EncodeToString(v)
|
||||||
case string:
|
case string:
|
||||||
return base64.URLEncoding.EncodeToString([]byte(value.(string)))
|
return base64.URLEncoding.EncodeToString([]byte(v))
|
||||||
case error:
|
case error:
|
||||||
return base64.URLEncoding.EncodeToString([]byte(value.(error).Error()))
|
return base64.URLEncoding.EncodeToString([]byte(v.Error()))
|
||||||
default:
|
default:
|
||||||
marshal, err := json.Marshal(value)
|
marshal, err := json.Marshal(v)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
@@ -450,7 +486,7 @@ func ToRawStdBase64(value any) string {
|
|||||||
if value == nil || (reflect.ValueOf(value).Kind() == reflect.Ptr && reflect.ValueOf(value).IsNil()) {
|
if value == nil || (reflect.ValueOf(value).Kind() == reflect.Ptr && reflect.ValueOf(value).IsNil()) {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
switch value.(type) {
|
switch v := value.(type) {
|
||||||
case []byte:
|
case []byte:
|
||||||
return base64.RawStdEncoding.EncodeToString(value.([]byte))
|
return base64.RawStdEncoding.EncodeToString(value.([]byte))
|
||||||
case string:
|
case string:
|
||||||
@@ -458,7 +494,7 @@ func ToRawStdBase64(value any) string {
|
|||||||
case error:
|
case error:
|
||||||
return base64.RawStdEncoding.EncodeToString([]byte(value.(error).Error()))
|
return base64.RawStdEncoding.EncodeToString([]byte(value.(error).Error()))
|
||||||
default:
|
default:
|
||||||
marshal, err := json.Marshal(value)
|
marshal, err := json.Marshal(v)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
@@ -472,7 +508,7 @@ func ToRawUrlBase64(value any) string {
|
|||||||
if value == nil || (reflect.ValueOf(value).Kind() == reflect.Ptr && reflect.ValueOf(value).IsNil()) {
|
if value == nil || (reflect.ValueOf(value).Kind() == reflect.Ptr && reflect.ValueOf(value).IsNil()) {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
switch value.(type) {
|
switch v := value.(type) {
|
||||||
case []byte:
|
case []byte:
|
||||||
return base64.RawURLEncoding.EncodeToString(value.([]byte))
|
return base64.RawURLEncoding.EncodeToString(value.([]byte))
|
||||||
case string:
|
case string:
|
||||||
@@ -480,7 +516,7 @@ func ToRawUrlBase64(value any) string {
|
|||||||
case error:
|
case error:
|
||||||
return base64.RawURLEncoding.EncodeToString([]byte(value.(error).Error()))
|
return base64.RawURLEncoding.EncodeToString([]byte(value.(error).Error()))
|
||||||
default:
|
default:
|
||||||
marshal, err := json.Marshal(value)
|
marshal, err := json.Marshal(v)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -169,6 +169,45 @@ func ExampleToPointer() {
|
|||||||
// 123
|
// 123
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ExampleToPointers() {
|
||||||
|
strs := []string{"a", "b", "c"}
|
||||||
|
pointerStrs := ToPointers(strs)
|
||||||
|
fmt.Println(*pointerStrs[0])
|
||||||
|
fmt.Println(*pointerStrs[1])
|
||||||
|
fmt.Println(*pointerStrs[2])
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// a
|
||||||
|
// b
|
||||||
|
// c
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleFromPointer() {
|
||||||
|
str := "abc"
|
||||||
|
strPtr := &str
|
||||||
|
result := FromPointer(strPtr)
|
||||||
|
fmt.Println(result)
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// abc
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleFromPointers() {
|
||||||
|
strs := []string{"a", "b", "c"}
|
||||||
|
strPtr := []*string{&strs[0], &strs[1], &strs[2]}
|
||||||
|
|
||||||
|
result := FromPointers(strPtr)
|
||||||
|
|
||||||
|
fmt.Println(result[0])
|
||||||
|
fmt.Println(result[1])
|
||||||
|
fmt.Println(result[2])
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// a
|
||||||
|
// b
|
||||||
|
// c
|
||||||
|
}
|
||||||
|
|
||||||
func ExampleToMap() {
|
func ExampleToMap() {
|
||||||
type Message struct {
|
type Message struct {
|
||||||
name string
|
name string
|
||||||
|
|||||||
@@ -16,49 +16,10 @@ func (c *cloner) clone(v reflect.Value) reflect.Value {
|
|||||||
case reflect.Invalid:
|
case reflect.Invalid:
|
||||||
return reflect.ValueOf(nil)
|
return reflect.ValueOf(nil)
|
||||||
|
|
||||||
// bool
|
case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
|
||||||
case reflect.Bool:
|
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
|
||||||
return reflect.ValueOf(v.Bool())
|
reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128, reflect.String:
|
||||||
|
return v
|
||||||
//int
|
|
||||||
case reflect.Int:
|
|
||||||
return reflect.ValueOf(int(v.Int()))
|
|
||||||
case reflect.Int8:
|
|
||||||
return reflect.ValueOf(int8(v.Int()))
|
|
||||||
case reflect.Int16:
|
|
||||||
return reflect.ValueOf(int16(v.Int()))
|
|
||||||
case reflect.Int32:
|
|
||||||
return reflect.ValueOf(int32(v.Int()))
|
|
||||||
case reflect.Int64:
|
|
||||||
return reflect.ValueOf(v.Int())
|
|
||||||
|
|
||||||
// uint
|
|
||||||
case reflect.Uint:
|
|
||||||
return reflect.ValueOf(uint(v.Uint()))
|
|
||||||
case reflect.Uint8:
|
|
||||||
return reflect.ValueOf(uint8(v.Uint()))
|
|
||||||
case reflect.Uint16:
|
|
||||||
return reflect.ValueOf(uint16(v.Uint()))
|
|
||||||
case reflect.Uint32:
|
|
||||||
return reflect.ValueOf(uint32(v.Uint()))
|
|
||||||
case reflect.Uint64:
|
|
||||||
return reflect.ValueOf(v.Uint())
|
|
||||||
|
|
||||||
// float
|
|
||||||
case reflect.Float32:
|
|
||||||
return reflect.ValueOf(float32(v.Float()))
|
|
||||||
case reflect.Float64:
|
|
||||||
return reflect.ValueOf(v.Float())
|
|
||||||
|
|
||||||
// complex
|
|
||||||
case reflect.Complex64:
|
|
||||||
return reflect.ValueOf(complex64(v.Complex()))
|
|
||||||
case reflect.Complex128:
|
|
||||||
return reflect.ValueOf(v.Complex())
|
|
||||||
|
|
||||||
// string
|
|
||||||
case reflect.String:
|
|
||||||
return reflect.ValueOf(v.String())
|
|
||||||
|
|
||||||
// array
|
// array
|
||||||
case reflect.Array, reflect.Slice:
|
case reflect.Array, reflect.Slice:
|
||||||
@@ -90,11 +51,16 @@ func (c *cloner) clone(v reflect.Value) reflect.Value {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *cloner) cloneArray(v reflect.Value) reflect.Value {
|
func (c *cloner) cloneArray(v reflect.Value) reflect.Value {
|
||||||
if v.IsNil() {
|
if v.Kind() == reflect.Slice && v.IsNil() {
|
||||||
return reflect.Zero(v.Type())
|
return reflect.Zero(v.Type())
|
||||||
}
|
}
|
||||||
|
|
||||||
arr := reflect.MakeSlice(v.Type(), v.Len(), v.Len())
|
var arr reflect.Value
|
||||||
|
if v.Kind() == reflect.Array {
|
||||||
|
arr = reflect.New(v.Type()).Elem()
|
||||||
|
} else {
|
||||||
|
arr = reflect.MakeSlice(v.Type(), v.Len(), v.Len())
|
||||||
|
}
|
||||||
|
|
||||||
for i := 0; i < v.Len(); i++ {
|
for i := 0; i < v.Len(); i++ {
|
||||||
val := c.clone(v.Index(i))
|
val := c.clone(v.Index(i))
|
||||||
@@ -179,8 +145,10 @@ func (c *cloner) clonePtr(v reflect.Value) reflect.Value {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
clonedPtr := reflect.New(newVal.Type())
|
clonedPtr := reflect.New(v.Type().Elem())
|
||||||
clonedPtr.Elem().Set(newVal)
|
if newVal.IsValid() {
|
||||||
|
clonedPtr.Elem().Set(newVal)
|
||||||
|
}
|
||||||
|
|
||||||
return clonedPtr
|
return clonedPtr
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -302,6 +302,75 @@ func TestToPointer(t *testing.T) {
|
|||||||
assert.Equal(*result, 123)
|
assert.Equal(*result, 123)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestToPointers(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
assert := internal.NewAssert(t, "TestToPointers")
|
||||||
|
|
||||||
|
intVals := []int{1, 2, 3}
|
||||||
|
result := ToPointers(intVals)
|
||||||
|
|
||||||
|
assert.Equal(3, len(result))
|
||||||
|
assert.Equal(1, *result[0])
|
||||||
|
assert.Equal(2, *result[1])
|
||||||
|
assert.Equal(3, *result[2])
|
||||||
|
|
||||||
|
stringVals := []string{"a", "b", "c"}
|
||||||
|
resultStr := ToPointers(stringVals)
|
||||||
|
assert.Equal(3, len(resultStr))
|
||||||
|
assert.Equal("a", *resultStr[0])
|
||||||
|
assert.Equal("b", *resultStr[1])
|
||||||
|
assert.Equal("c", *resultStr[2])
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFromPointer(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
assert := internal.NewAssert(t, "TestFromPointer")
|
||||||
|
|
||||||
|
intVal := 123
|
||||||
|
pointer := &intVal
|
||||||
|
result := FromPointer(pointer)
|
||||||
|
|
||||||
|
assert.Equal(123, result)
|
||||||
|
|
||||||
|
stringVal := "abc"
|
||||||
|
stringPointer := &stringVal
|
||||||
|
resultStr := FromPointer(stringPointer)
|
||||||
|
|
||||||
|
assert.Equal("abc", resultStr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFromPointers(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
assert := internal.NewAssert(t, "TestFromPointers")
|
||||||
|
|
||||||
|
intPointers := []*int{new(int), new(int), new(int)}
|
||||||
|
*intPointers[0] = 1
|
||||||
|
*intPointers[1] = 2
|
||||||
|
*intPointers[2] = 3
|
||||||
|
|
||||||
|
result := FromPointers(intPointers)
|
||||||
|
|
||||||
|
assert.Equal(3, len(result))
|
||||||
|
assert.Equal(1, result[0])
|
||||||
|
assert.Equal(2, result[1])
|
||||||
|
assert.Equal(3, result[2])
|
||||||
|
|
||||||
|
stringPointers := []*string{new(string), new(string), new(string)}
|
||||||
|
*stringPointers[0] = "a"
|
||||||
|
*stringPointers[1] = "b"
|
||||||
|
*stringPointers[2] = "c"
|
||||||
|
|
||||||
|
resultStr := FromPointers(stringPointers)
|
||||||
|
|
||||||
|
assert.Equal(3, len(resultStr))
|
||||||
|
assert.Equal("a", resultStr[0])
|
||||||
|
assert.Equal("b", resultStr[1])
|
||||||
|
assert.Equal("c", resultStr[2])
|
||||||
|
}
|
||||||
|
|
||||||
func TestEncodeByte(t *testing.T) {
|
func TestEncodeByte(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
@@ -325,6 +394,18 @@ func TestDecodeByte(t *testing.T) {
|
|||||||
assert.Equal("abc", obj)
|
assert.Equal("abc", obj)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestDeepCloneArrays(t *testing.T) {
|
||||||
|
assert := internal.NewAssert(t, "TestDeepCloneArrays")
|
||||||
|
value := 42
|
||||||
|
type pair [2]*int
|
||||||
|
src := pair{&value, nil}
|
||||||
|
got := DeepClone(src)
|
||||||
|
assert.Equal(src, got)
|
||||||
|
*got[0] = 99
|
||||||
|
assert.Equal(42, *src[0])
|
||||||
|
assert.Equal([0]int{}, DeepClone([0]int{}))
|
||||||
|
}
|
||||||
|
|
||||||
func TestDeepClone(t *testing.T) {
|
func TestDeepClone(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package cryptor_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/duke-git/lancet/v2/cryptor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ExampleSm3() {
|
||||||
|
data := []byte("hello world")
|
||||||
|
hash := cryptor.Sm3(data)
|
||||||
|
|
||||||
|
fmt.Println(hex.EncodeToString(hash))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// 44f0061e69fa6fdfc290c494654a05dc0c053da7e5c52b84ef93a9d67d3fff88
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleSm4EcbEncrypt() {
|
||||||
|
key := []byte("1234567890abcdef") // 16 bytes key
|
||||||
|
plaintext := []byte("hello world")
|
||||||
|
|
||||||
|
encrypted := cryptor.Sm4EcbEncrypt(plaintext, key)
|
||||||
|
decrypted := cryptor.Sm4EcbDecrypt(encrypted, key)
|
||||||
|
|
||||||
|
fmt.Println(string(decrypted))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// hello world
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleSm4CbcEncrypt() {
|
||||||
|
key := []byte("1234567890abcdef") // 16 bytes key
|
||||||
|
plaintext := []byte("hello world")
|
||||||
|
|
||||||
|
encrypted := cryptor.Sm4CbcEncrypt(plaintext, key)
|
||||||
|
decrypted := cryptor.Sm4CbcDecrypt(encrypted, key)
|
||||||
|
|
||||||
|
fmt.Println(string(decrypted))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// hello world
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleGenerateSm2Key() {
|
||||||
|
// Generate SM2 key pair
|
||||||
|
privateKey, err := cryptor.GenerateSm2Key()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
plaintext := []byte("hello world")
|
||||||
|
|
||||||
|
// Encrypt with public key
|
||||||
|
ciphertext, err := cryptor.Sm2Encrypt(&privateKey.PublicKey, plaintext)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decrypt with private key
|
||||||
|
decrypted, err := cryptor.Sm2Decrypt(privateKey, ciphertext)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println(string(decrypted))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// hello world
|
||||||
|
}
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
package cryptor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/elliptic"
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"math/big"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SM2 implements the Chinese SM2 elliptic curve public key algorithm.
|
||||||
|
// SM2 is based on elliptic curve cryptography and provides encryption, decryption, signing and verification.
|
||||||
|
//
|
||||||
|
// Note: This implementation uses crypto/elliptic package methods (GenerateKey, ScalarBaseMult, ScalarMult, IsOnCurve)
|
||||||
|
// which are marked as deprecated in Go 1.20+. These methods still work correctly and are widely used.
|
||||||
|
// The //nolint:staticcheck directive suppresses deprecation warnings.
|
||||||
|
// A future version may replace these with a custom elliptic curve implementation.
|
||||||
|
|
||||||
|
var (
|
||||||
|
sm2P256 *sm2Curve
|
||||||
|
sm2P256Params = &elliptic.CurveParams{Name: "sm2p256v1"}
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
// SM2 curve parameters
|
||||||
|
sm2P256Params.P, _ = new(big.Int).SetString("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF", 16)
|
||||||
|
sm2P256Params.N, _ = new(big.Int).SetString("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123", 16)
|
||||||
|
sm2P256Params.B, _ = new(big.Int).SetString("28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93", 16)
|
||||||
|
sm2P256Params.Gx, _ = new(big.Int).SetString("32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7", 16)
|
||||||
|
sm2P256Params.Gy, _ = new(big.Int).SetString("BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0", 16)
|
||||||
|
sm2P256Params.BitSize = 256
|
||||||
|
|
||||||
|
sm2P256 = &sm2Curve{sm2P256Params}
|
||||||
|
}
|
||||||
|
|
||||||
|
type sm2Curve struct {
|
||||||
|
*elliptic.CurveParams
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sm2PrivateKey represents an SM2 private key.
|
||||||
|
type Sm2PrivateKey struct {
|
||||||
|
D *big.Int
|
||||||
|
PublicKey Sm2PublicKey
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sm2PublicKey represents an SM2 public key.
|
||||||
|
type Sm2PublicKey struct {
|
||||||
|
X, Y *big.Int
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenerateSm2Key generates a new SM2 private/public key pair.
|
||||||
|
// Play: https://go.dev/play/p/bKYMqRLvIx3
|
||||||
|
func GenerateSm2Key() (*Sm2PrivateKey, error) {
|
||||||
|
priv, x, y, err := elliptic.GenerateKey(sm2P256, rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
privateKey := &Sm2PrivateKey{
|
||||||
|
D: new(big.Int).SetBytes(priv),
|
||||||
|
PublicKey: Sm2PublicKey{
|
||||||
|
X: x,
|
||||||
|
Y: y,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
return privateKey, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sm2Encrypt encrypts plaintext using SM2 public key.
|
||||||
|
// Returns ciphertext in the format: C1 || C3 || C2
|
||||||
|
// C1 = kG (65 bytes in uncompressed format)
|
||||||
|
// C3 = Hash(x2 || M || y2) (32 bytes for SM3)
|
||||||
|
// C2 = M xor t (same length as plaintext)
|
||||||
|
// Play: https://go.dev/play/p/bKYMqRLvIx3
|
||||||
|
func Sm2Encrypt(pub *Sm2PublicKey, plaintext []byte) ([]byte, error) {
|
||||||
|
if pub == nil || pub.X == nil || pub.Y == nil {
|
||||||
|
return nil, errors.New("sm2: invalid public key")
|
||||||
|
}
|
||||||
|
|
||||||
|
for {
|
||||||
|
// Generate random k
|
||||||
|
k, err := randFieldElement(sm2P256, rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// C1 = kG
|
||||||
|
c1x, c1y := sm2P256.ScalarBaseMult(k.Bytes())
|
||||||
|
|
||||||
|
// kP = (x2, y2)
|
||||||
|
x2, y2 := sm2P256.ScalarMult(pub.X, pub.Y, k.Bytes())
|
||||||
|
|
||||||
|
// Derive key using KDF
|
||||||
|
kdfLen := len(plaintext)
|
||||||
|
t := sm2KDF(append(toBytes(sm2P256, x2), toBytes(sm2P256, y2)...), kdfLen)
|
||||||
|
|
||||||
|
// Check if t is all zeros
|
||||||
|
allZero := true
|
||||||
|
for _, b := range t {
|
||||||
|
if b != 0 {
|
||||||
|
allZero = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if allZero {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// C2 = M xor t
|
||||||
|
c2 := make([]byte, len(plaintext))
|
||||||
|
for i := 0; i < len(plaintext); i++ {
|
||||||
|
c2[i] = plaintext[i] ^ t[i]
|
||||||
|
}
|
||||||
|
|
||||||
|
// C3 = Hash(x2 || M || y2)
|
||||||
|
c3Input := append(toBytes(sm2P256, x2), plaintext...)
|
||||||
|
c3Input = append(c3Input, toBytes(sm2P256, y2)...)
|
||||||
|
c3 := Sm3(c3Input)
|
||||||
|
|
||||||
|
// Return C1 || C3 || C2
|
||||||
|
c1 := sm2MarshalUncompressed(sm2P256, c1x, c1y)
|
||||||
|
result := append(c1, c3...)
|
||||||
|
result = append(result, c2...)
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sm2Decrypt decrypts ciphertext using SM2 private key.
|
||||||
|
// Expects ciphertext in the format: C1 || C3 || C2
|
||||||
|
// Play: https://go.dev/play/p/bKYMqRLvIx3
|
||||||
|
func Sm2Decrypt(priv *Sm2PrivateKey, ciphertext []byte) ([]byte, error) {
|
||||||
|
if priv == nil || priv.D == nil {
|
||||||
|
return nil, errors.New("sm2: invalid private key")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse C1 (65 bytes), C3 (32 bytes), C2 (remaining)
|
||||||
|
if len(ciphertext) < 97 {
|
||||||
|
return nil, errors.New("sm2: ciphertext too short")
|
||||||
|
}
|
||||||
|
|
||||||
|
c1 := ciphertext[:65]
|
||||||
|
c3 := ciphertext[65:97]
|
||||||
|
c2 := ciphertext[97:]
|
||||||
|
|
||||||
|
// Parse C1
|
||||||
|
c1x, c1y := sm2UnmarshalUncompressed(sm2P256, c1)
|
||||||
|
if c1x == nil {
|
||||||
|
return nil, errors.New("sm2: invalid C1 point")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify C1 is on curve
|
||||||
|
if !sm2P256.IsOnCurve(c1x, c1y) {
|
||||||
|
return nil, errors.New("sm2: C1 not on curve")
|
||||||
|
}
|
||||||
|
|
||||||
|
// dC1 = (x2, y2)
|
||||||
|
x2, y2 := sm2P256.ScalarMult(c1x, c1y, priv.D.Bytes())
|
||||||
|
|
||||||
|
// Derive key using KDF
|
||||||
|
kdfLen := len(c2)
|
||||||
|
t := sm2KDF(append(toBytes(sm2P256, x2), toBytes(sm2P256, y2)...), kdfLen)
|
||||||
|
|
||||||
|
// M = C2 xor t
|
||||||
|
plaintext := make([]byte, len(c2))
|
||||||
|
for i := 0; i < len(c2); i++ {
|
||||||
|
plaintext[i] = c2[i] ^ t[i]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify C3 = Hash(x2 || M || y2)
|
||||||
|
u := append(toBytes(sm2P256, x2), plaintext...)
|
||||||
|
u = append(u, toBytes(sm2P256, y2)...)
|
||||||
|
hash := Sm3(u)
|
||||||
|
|
||||||
|
for i := 0; i < len(c3); i++ {
|
||||||
|
if c3[i] != hash[i] {
|
||||||
|
return nil, errors.New("sm2: hash verification failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return plaintext, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SM2 KDF (Key Derivation Function)
|
||||||
|
func sm2KDF(z []byte, klen int) []byte {
|
||||||
|
limit := (klen + 31) / 32
|
||||||
|
result := make([]byte, 0, limit*32)
|
||||||
|
|
||||||
|
for i := 1; i <= limit; i++ {
|
||||||
|
counter := make([]byte, 4)
|
||||||
|
binary.BigEndian.PutUint32(counter, uint32(i))
|
||||||
|
hash := Sm3(append(z, counter...))
|
||||||
|
result = append(result, hash...)
|
||||||
|
}
|
||||||
|
|
||||||
|
return result[:klen]
|
||||||
|
}
|
||||||
|
|
||||||
|
func toBytes(curve elliptic.Curve, value *big.Int) []byte {
|
||||||
|
byteLen := (curve.Params().BitSize + 7) / 8
|
||||||
|
buf := make([]byte, byteLen)
|
||||||
|
b := value.Bytes()
|
||||||
|
copy(buf[byteLen-len(b):], b)
|
||||||
|
return buf
|
||||||
|
}
|
||||||
|
|
||||||
|
func sm2MarshalUncompressed(curve *sm2Curve, x, y *big.Int) []byte {
|
||||||
|
byteLen := (curve.BitSize + 7) / 8
|
||||||
|
ret := make([]byte, 1+2*byteLen)
|
||||||
|
ret[0] = 4 // uncompressed point
|
||||||
|
|
||||||
|
xBytes := x.Bytes()
|
||||||
|
copy(ret[1+byteLen-len(xBytes):], xBytes)
|
||||||
|
yBytes := y.Bytes()
|
||||||
|
copy(ret[1+2*byteLen-len(yBytes):], yBytes)
|
||||||
|
|
||||||
|
return ret
|
||||||
|
}
|
||||||
|
|
||||||
|
func sm2UnmarshalUncompressed(curve *sm2Curve, data []byte) (*big.Int, *big.Int) {
|
||||||
|
byteLen := (curve.BitSize + 7) / 8
|
||||||
|
if len(data) != 1+2*byteLen {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if data[0] != 4 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
x := new(big.Int).SetBytes(data[1 : 1+byteLen])
|
||||||
|
y := new(big.Int).SetBytes(data[1+byteLen:])
|
||||||
|
|
||||||
|
return x, y
|
||||||
|
}
|
||||||
|
|
||||||
|
func randFieldElement(c elliptic.Curve, rand io.Reader) (*big.Int, error) {
|
||||||
|
params := c.Params()
|
||||||
|
b := make([]byte, params.BitSize/8+8)
|
||||||
|
_, err := io.ReadFull(rand, b)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
k := new(big.Int).SetBytes(b)
|
||||||
|
n := new(big.Int).Sub(params.N, big.NewInt(1))
|
||||||
|
k.Mod(k, n)
|
||||||
|
k.Add(k, big.NewInt(1))
|
||||||
|
|
||||||
|
return k, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
package cryptor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"hash"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SM3 implements the Chinese SM3 cryptographic hash algorithm.
|
||||||
|
// SM3 produces a 256-bit (32-byte) hash value.
|
||||||
|
|
||||||
|
const (
|
||||||
|
sm3BlockSize = 64
|
||||||
|
sm3Size = 32
|
||||||
|
sm3T1 = 0x79cc4519
|
||||||
|
sm3T2 = 0x7a879d8a
|
||||||
|
)
|
||||||
|
|
||||||
|
var sm3IV = [8]uint32{
|
||||||
|
0x7380166f, 0x4914b2b9, 0x172442d7, 0xda8a0600,
|
||||||
|
0xa96f30bc, 0x163138aa, 0xe38dee4d, 0xb0fb0e4e,
|
||||||
|
}
|
||||||
|
|
||||||
|
type sm3Digest struct {
|
||||||
|
h [8]uint32
|
||||||
|
x [sm3BlockSize]byte
|
||||||
|
nx int
|
||||||
|
len uint64
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sm3 returns a new hash.Hash computing the SM3 checksum.
|
||||||
|
// Play: https://go.dev/play/p/zDAQpteAiOc
|
||||||
|
func Sm3(data []byte) []byte {
|
||||||
|
h := newSm3()
|
||||||
|
h.Write(data)
|
||||||
|
return h.Sum(nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newSm3() hash.Hash {
|
||||||
|
d := new(sm3Digest)
|
||||||
|
d.Reset()
|
||||||
|
return d
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *sm3Digest) Reset() {
|
||||||
|
d.h = sm3IV
|
||||||
|
d.nx = 0
|
||||||
|
d.len = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *sm3Digest) Size() int {
|
||||||
|
return sm3Size
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *sm3Digest) BlockSize() int {
|
||||||
|
return sm3BlockSize
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *sm3Digest) Write(p []byte) (nn int, err error) {
|
||||||
|
nn = len(p)
|
||||||
|
d.len += uint64(nn)
|
||||||
|
|
||||||
|
if d.nx > 0 {
|
||||||
|
n := copy(d.x[d.nx:], p)
|
||||||
|
d.nx += n
|
||||||
|
if d.nx == sm3BlockSize {
|
||||||
|
sm3Block(d, d.x[:])
|
||||||
|
d.nx = 0
|
||||||
|
}
|
||||||
|
p = p[n:]
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(p) >= sm3BlockSize {
|
||||||
|
n := len(p) &^ (sm3BlockSize - 1)
|
||||||
|
sm3Block(d, p[:n])
|
||||||
|
p = p[n:]
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(p) > 0 {
|
||||||
|
d.nx = copy(d.x[:], p)
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *sm3Digest) Sum(in []byte) []byte {
|
||||||
|
d0 := *d
|
||||||
|
hash := d0.checkSum()
|
||||||
|
return append(in, hash[:]...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *sm3Digest) checkSum() [sm3Size]byte {
|
||||||
|
len := d.len
|
||||||
|
var tmp [64]byte
|
||||||
|
tmp[0] = 0x80
|
||||||
|
|
||||||
|
if len%64 < 56 {
|
||||||
|
d.Write(tmp[0 : 56-len%64])
|
||||||
|
} else {
|
||||||
|
d.Write(tmp[0 : 64+56-len%64])
|
||||||
|
}
|
||||||
|
|
||||||
|
len <<= 3
|
||||||
|
binary.BigEndian.PutUint64(tmp[:], len)
|
||||||
|
d.Write(tmp[0:8])
|
||||||
|
|
||||||
|
if d.nx != 0 {
|
||||||
|
panic("d.nx != 0")
|
||||||
|
}
|
||||||
|
|
||||||
|
var digest [sm3Size]byte
|
||||||
|
for i := 0; i < 8; i++ {
|
||||||
|
binary.BigEndian.PutUint32(digest[i*4:], d.h[i])
|
||||||
|
}
|
||||||
|
|
||||||
|
return digest
|
||||||
|
}
|
||||||
|
|
||||||
|
func sm3Block(dig *sm3Digest, p []byte) {
|
||||||
|
var w [68]uint32
|
||||||
|
var w1 [64]uint32
|
||||||
|
|
||||||
|
h0, h1, h2, h3, h4, h5, h6, h7 := dig.h[0], dig.h[1], dig.h[2], dig.h[3], dig.h[4], dig.h[5], dig.h[6], dig.h[7]
|
||||||
|
|
||||||
|
for len(p) >= sm3BlockSize {
|
||||||
|
for i := 0; i < 16; i++ {
|
||||||
|
j := i * 4
|
||||||
|
w[i] = binary.BigEndian.Uint32(p[j : j+4])
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 16; i < 68; i++ {
|
||||||
|
w[i] = sm3P1(w[i-16]^w[i-9]^sm3RotateLeft(w[i-3], 15)) ^ sm3RotateLeft(w[i-13], 7) ^ w[i-6]
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < 64; i++ {
|
||||||
|
w1[i] = w[i] ^ w[i+4]
|
||||||
|
}
|
||||||
|
|
||||||
|
A, B, C, D, E, F, G, H := h0, h1, h2, h3, h4, h5, h6, h7
|
||||||
|
|
||||||
|
for j := 0; j < 64; j++ {
|
||||||
|
var ss1, ss2, tt1, tt2, t uint32
|
||||||
|
|
||||||
|
if j < 16 {
|
||||||
|
t = sm3T1
|
||||||
|
} else {
|
||||||
|
t = sm3T2
|
||||||
|
}
|
||||||
|
|
||||||
|
ss1 = sm3RotateLeft(sm3RotateLeft(A, 12)+E+sm3RotateLeft(t, uint32(j%32)), 7)
|
||||||
|
ss2 = ss1 ^ sm3RotateLeft(A, 12)
|
||||||
|
|
||||||
|
if j < 16 {
|
||||||
|
tt1 = sm3FF0(A, B, C) + D + ss2 + w1[j]
|
||||||
|
tt2 = sm3GG0(E, F, G) + H + ss1 + w[j]
|
||||||
|
} else {
|
||||||
|
tt1 = sm3FF1(A, B, C) + D + ss2 + w1[j]
|
||||||
|
tt2 = sm3GG1(E, F, G) + H + ss1 + w[j]
|
||||||
|
}
|
||||||
|
|
||||||
|
D = C
|
||||||
|
C = sm3RotateLeft(B, 9)
|
||||||
|
B = A
|
||||||
|
A = tt1
|
||||||
|
H = G
|
||||||
|
G = sm3RotateLeft(F, 19)
|
||||||
|
F = E
|
||||||
|
E = sm3P0(tt2)
|
||||||
|
}
|
||||||
|
|
||||||
|
h0 ^= A
|
||||||
|
h1 ^= B
|
||||||
|
h2 ^= C
|
||||||
|
h3 ^= D
|
||||||
|
h4 ^= E
|
||||||
|
h5 ^= F
|
||||||
|
h6 ^= G
|
||||||
|
h7 ^= H
|
||||||
|
|
||||||
|
p = p[sm3BlockSize:]
|
||||||
|
}
|
||||||
|
|
||||||
|
dig.h[0], dig.h[1], dig.h[2], dig.h[3], dig.h[4], dig.h[5], dig.h[6], dig.h[7] = h0, h1, h2, h3, h4, h5, h6, h7
|
||||||
|
}
|
||||||
|
|
||||||
|
func sm3RotateLeft(x, n uint32) uint32 {
|
||||||
|
return (x << n) | (x >> (32 - n))
|
||||||
|
}
|
||||||
|
|
||||||
|
func sm3P0(x uint32) uint32 {
|
||||||
|
return x ^ sm3RotateLeft(x, 9) ^ sm3RotateLeft(x, 17)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sm3P1(x uint32) uint32 {
|
||||||
|
return x ^ sm3RotateLeft(x, 15) ^ sm3RotateLeft(x, 23)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sm3FF0(x, y, z uint32) uint32 {
|
||||||
|
return x ^ y ^ z
|
||||||
|
}
|
||||||
|
|
||||||
|
func sm3FF1(x, y, z uint32) uint32 {
|
||||||
|
return (x & y) | (x & z) | (y & z)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sm3GG0(x, y, z uint32) uint32 {
|
||||||
|
return x ^ y ^ z
|
||||||
|
}
|
||||||
|
|
||||||
|
func sm3GG1(x, y, z uint32) uint32 {
|
||||||
|
return (x & y) | (^x & z)
|
||||||
|
}
|
||||||
@@ -0,0 +1,270 @@
|
|||||||
|
package cryptor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/cipher"
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/binary"
|
||||||
|
"io"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SM4 implements the Chinese SM4 block cipher.
|
||||||
|
// SM4 is a 128-bit block cipher with 128-bit keys.
|
||||||
|
// This implementation uses pre-computed lookup tables for optimal performance.
|
||||||
|
|
||||||
|
const sm4BlockSize = 16
|
||||||
|
|
||||||
|
// Pre-computed T-transformation lookup tables for performance optimization
|
||||||
|
var sm4T1Table [256][4]uint32 // S-box + L1 transformation
|
||||||
|
var sm4T2Table [256][4]uint32 // S-box + L2 transformation
|
||||||
|
|
||||||
|
var sm4Sbox = [256]byte{
|
||||||
|
0xd6, 0x90, 0xe9, 0xfe, 0xcc, 0xe1, 0x3d, 0xb7, 0x16, 0xb6, 0x14, 0xc2, 0x28, 0xfb, 0x2c, 0x05,
|
||||||
|
0x2b, 0x67, 0x9a, 0x76, 0x2a, 0xbe, 0x04, 0xc3, 0xaa, 0x44, 0x13, 0x26, 0x49, 0x86, 0x06, 0x99,
|
||||||
|
0x9c, 0x42, 0x50, 0xf4, 0x91, 0xef, 0x98, 0x7a, 0x33, 0x54, 0x0b, 0x43, 0xed, 0xcf, 0xac, 0x62,
|
||||||
|
0xe4, 0xb3, 0x1c, 0xa9, 0xc9, 0x08, 0xe8, 0x95, 0x80, 0xdf, 0x94, 0xfa, 0x75, 0x8f, 0x3f, 0xa6,
|
||||||
|
0x47, 0x07, 0xa7, 0xfc, 0xf3, 0x73, 0x17, 0xba, 0x83, 0x59, 0x3c, 0x19, 0xe6, 0x85, 0x4f, 0xa8,
|
||||||
|
0x68, 0x6b, 0x81, 0xb2, 0x71, 0x64, 0xda, 0x8b, 0xf8, 0xeb, 0x0f, 0x4b, 0x70, 0x56, 0x9d, 0x35,
|
||||||
|
0x1e, 0x24, 0x0e, 0x5e, 0x63, 0x58, 0xd1, 0xa2, 0x25, 0x22, 0x7c, 0x3b, 0x01, 0x21, 0x78, 0x87,
|
||||||
|
0xd4, 0x00, 0x46, 0x57, 0x9f, 0xd3, 0x27, 0x52, 0x4c, 0x36, 0x02, 0xe7, 0xa0, 0xc4, 0xc8, 0x9e,
|
||||||
|
0xea, 0xbf, 0x8a, 0xd2, 0x40, 0xc7, 0x38, 0xb5, 0xa3, 0xf7, 0xf2, 0xce, 0xf9, 0x61, 0x15, 0xa1,
|
||||||
|
0xe0, 0xae, 0x5d, 0xa4, 0x9b, 0x34, 0x1a, 0x55, 0xad, 0x93, 0x32, 0x30, 0xf5, 0x8c, 0xb1, 0xe3,
|
||||||
|
0x1d, 0xf6, 0xe2, 0x2e, 0x82, 0x66, 0xca, 0x60, 0xc0, 0x29, 0x23, 0xab, 0x0d, 0x53, 0x4e, 0x6f,
|
||||||
|
0xd5, 0xdb, 0x37, 0x45, 0xde, 0xfd, 0x8e, 0x2f, 0x03, 0xff, 0x6a, 0x72, 0x6d, 0x6c, 0x5b, 0x51,
|
||||||
|
0x8d, 0x1b, 0xaf, 0x92, 0xbb, 0xdd, 0xbc, 0x7f, 0x11, 0xd9, 0x5c, 0x41, 0x1f, 0x10, 0x5a, 0xd8,
|
||||||
|
0x0a, 0xc1, 0x31, 0x88, 0xa5, 0xcd, 0x7b, 0xbd, 0x2d, 0x74, 0xd0, 0x12, 0xb8, 0xe5, 0xb4, 0xb0,
|
||||||
|
0x89, 0x69, 0x97, 0x4a, 0x0c, 0x96, 0x77, 0x7e, 0x65, 0xb9, 0xf1, 0x09, 0xc5, 0x6e, 0xc6, 0x84,
|
||||||
|
0x18, 0xf0, 0x7d, 0xec, 0x3a, 0xdc, 0x4d, 0x20, 0x79, 0xee, 0x5f, 0x3e, 0xd7, 0xcb, 0x39, 0x48,
|
||||||
|
}
|
||||||
|
|
||||||
|
var sm4FK = [4]uint32{0xa3b1bac6, 0x56aa3350, 0x677d9197, 0xb27022dc}
|
||||||
|
|
||||||
|
var sm4CK = [32]uint32{
|
||||||
|
0x00070e15, 0x1c232a31, 0x383f464d, 0x545b6269,
|
||||||
|
0x70777e85, 0x8c939aa1, 0xa8afb6bd, 0xc4cbd2d9,
|
||||||
|
0xe0e7eef5, 0xfc030a11, 0x181f262d, 0x343b4249,
|
||||||
|
0x50575e65, 0x6c737a81, 0x888f969d, 0xa4abb2b9,
|
||||||
|
0xc0c7ced5, 0xdce3eaf1, 0xf8ff060d, 0x141b2229,
|
||||||
|
0x30373e45, 0x4c535a61, 0x686f767d, 0x848b9299,
|
||||||
|
0xa0a7aeb5, 0xbcc3cad1, 0xd8dfe6ed, 0xf4fb0209,
|
||||||
|
0x10171e25, 0x2c333a41, 0x484f565d, 0x646b7279,
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化预计算查找表
|
||||||
|
func init() {
|
||||||
|
// Pre-compute all possible T1 and T2 transformations
|
||||||
|
for pos := 0; pos < 4; pos++ {
|
||||||
|
for i := 0; i < 256; i++ {
|
||||||
|
// S-box 替换
|
||||||
|
sboxVal := sm4Sbox[i]
|
||||||
|
|
||||||
|
// 根据字节位置计算偏移
|
||||||
|
shift := uint32((3 - pos) * 8)
|
||||||
|
b := uint32(sboxVal) << shift
|
||||||
|
|
||||||
|
// L1 变换:b ^ ROL(b,2) ^ ROL(b,10) ^ ROL(b,18) ^ ROL(b,24)
|
||||||
|
sm4T1Table[i][pos] = b ^ sm4RotateLeft(b, 2) ^ sm4RotateLeft(b, 10) ^ sm4RotateLeft(b, 18) ^ sm4RotateLeft(b, 24)
|
||||||
|
|
||||||
|
// L2 变换:b ^ ROL(b,13) ^ ROL(b,23)
|
||||||
|
sm4T2Table[i][pos] = b ^ sm4RotateLeft(b, 13) ^ sm4RotateLeft(b, 23)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type sm4Cipher struct {
|
||||||
|
enc [32]uint32
|
||||||
|
dec [32]uint32
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sm4EcbEncrypt encrypts data using SM4 in ECB mode.
|
||||||
|
// key must be 16 bytes.
|
||||||
|
// Play: https://go.dev/play/p/l5IQxYuuaED
|
||||||
|
func Sm4EcbEncrypt(data, key []byte) []byte {
|
||||||
|
if len(key) != 16 {
|
||||||
|
panic("sm4: key length must be 16 bytes")
|
||||||
|
}
|
||||||
|
|
||||||
|
c := newSm4Cipher(key)
|
||||||
|
padded := pkcs7Padding(data, sm4BlockSize)
|
||||||
|
encrypted := make([]byte, len(padded))
|
||||||
|
|
||||||
|
for i := 0; i < len(padded); i += sm4BlockSize {
|
||||||
|
c.Encrypt(encrypted[i:i+sm4BlockSize], padded[i:i+sm4BlockSize])
|
||||||
|
}
|
||||||
|
|
||||||
|
return encrypted
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sm4EcbDecrypt decrypts data using SM4 in ECB mode.
|
||||||
|
// key must be 16 bytes.
|
||||||
|
// Play: https://go.dev/play/p/l5IQxYuuaED
|
||||||
|
func Sm4EcbDecrypt(encrypted, key []byte) []byte {
|
||||||
|
if len(key) != 16 {
|
||||||
|
panic("sm4: key length must be 16 bytes")
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(encrypted)%sm4BlockSize != 0 {
|
||||||
|
panic("sm4: encrypted data length must be multiple of block size")
|
||||||
|
}
|
||||||
|
|
||||||
|
c := newSm4Cipher(key)
|
||||||
|
decrypted := make([]byte, len(encrypted))
|
||||||
|
|
||||||
|
for i := 0; i < len(encrypted); i += sm4BlockSize {
|
||||||
|
c.Decrypt(decrypted[i:i+sm4BlockSize], encrypted[i:i+sm4BlockSize])
|
||||||
|
}
|
||||||
|
|
||||||
|
return pkcs7UnPadding(decrypted)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sm4CbcEncrypt encrypts data using SM4 in CBC mode.
|
||||||
|
// key must be 16 bytes.
|
||||||
|
// Play: https://go.dev/play/p/65Q6iYhLRTa
|
||||||
|
func Sm4CbcEncrypt(data, key []byte) []byte {
|
||||||
|
if len(key) != 16 {
|
||||||
|
panic("sm4: key length must be 16 bytes")
|
||||||
|
}
|
||||||
|
|
||||||
|
c := newSm4Cipher(key)
|
||||||
|
padded := pkcs7Padding(data, sm4BlockSize)
|
||||||
|
|
||||||
|
iv := make([]byte, sm4BlockSize)
|
||||||
|
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
|
||||||
|
panic("sm4: failed to generate IV: " + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
encrypted := make([]byte, len(padded))
|
||||||
|
mode := cipher.NewCBCEncrypter(c, iv)
|
||||||
|
mode.CryptBlocks(encrypted, padded)
|
||||||
|
|
||||||
|
return append(iv, encrypted...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sm4CbcDecrypt decrypts data using SM4 in CBC mode.
|
||||||
|
// key must be 16 bytes.
|
||||||
|
// Play: https://go.dev/play/p/65Q6iYhLRTa
|
||||||
|
func Sm4CbcDecrypt(encrypted, key []byte) []byte {
|
||||||
|
if len(key) != 16 {
|
||||||
|
panic("sm4: key length must be 16 bytes")
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(encrypted) < sm4BlockSize {
|
||||||
|
panic("sm4: encrypted data too short")
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(encrypted)%sm4BlockSize != 0 {
|
||||||
|
panic("sm4: encrypted data length must be multiple of block size")
|
||||||
|
}
|
||||||
|
|
||||||
|
c := newSm4Cipher(key)
|
||||||
|
iv := encrypted[:sm4BlockSize]
|
||||||
|
ciphertext := encrypted[sm4BlockSize:]
|
||||||
|
|
||||||
|
decrypted := make([]byte, len(ciphertext))
|
||||||
|
mode := cipher.NewCBCDecrypter(c, iv)
|
||||||
|
mode.CryptBlocks(decrypted, ciphertext)
|
||||||
|
|
||||||
|
return pkcs7UnPadding(decrypted)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newSm4Cipher(key []byte) *sm4Cipher {
|
||||||
|
c := &sm4Cipher{}
|
||||||
|
|
||||||
|
var mk [4]uint32
|
||||||
|
for i := 0; i < 4; i++ {
|
||||||
|
mk[i] = binary.BigEndian.Uint32(key[i*4 : (i+1)*4])
|
||||||
|
}
|
||||||
|
|
||||||
|
var k [36]uint32
|
||||||
|
k[0] = mk[0] ^ sm4FK[0]
|
||||||
|
k[1] = mk[1] ^ sm4FK[1]
|
||||||
|
k[2] = mk[2] ^ sm4FK[2]
|
||||||
|
k[3] = mk[3] ^ sm4FK[3]
|
||||||
|
|
||||||
|
for i := 0; i < 32; i++ {
|
||||||
|
k[i+4] = k[i] ^ sm4T2Fast(k[i+1]^k[i+2]^k[i+3]^sm4CK[i])
|
||||||
|
c.enc[i] = k[i+4]
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < 32; i++ {
|
||||||
|
c.dec[i] = c.enc[31-i]
|
||||||
|
}
|
||||||
|
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *sm4Cipher) BlockSize() int {
|
||||||
|
return sm4BlockSize
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *sm4Cipher) Encrypt(dst, src []byte) {
|
||||||
|
if len(src) < sm4BlockSize {
|
||||||
|
panic("sm4: input not full block")
|
||||||
|
}
|
||||||
|
if len(dst) < sm4BlockSize {
|
||||||
|
panic("sm4: output not full block")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用局部变量避免数组分配,提升性能
|
||||||
|
x0 := binary.BigEndian.Uint32(src[0:4])
|
||||||
|
x1 := binary.BigEndian.Uint32(src[4:8])
|
||||||
|
x2 := binary.BigEndian.Uint32(src[8:12])
|
||||||
|
x3 := binary.BigEndian.Uint32(src[12:16])
|
||||||
|
|
||||||
|
// 32 轮加密
|
||||||
|
for i := 0; i < 32; i++ {
|
||||||
|
t := x1 ^ x2 ^ x3 ^ c.enc[i]
|
||||||
|
x0 ^= sm4T1Fast(t)
|
||||||
|
x0, x1, x2, x3 = x1, x2, x3, x0
|
||||||
|
}
|
||||||
|
|
||||||
|
binary.BigEndian.PutUint32(dst[0:4], x3)
|
||||||
|
binary.BigEndian.PutUint32(dst[4:8], x2)
|
||||||
|
binary.BigEndian.PutUint32(dst[8:12], x1)
|
||||||
|
binary.BigEndian.PutUint32(dst[12:16], x0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *sm4Cipher) Decrypt(dst, src []byte) {
|
||||||
|
if len(src) < sm4BlockSize {
|
||||||
|
panic("sm4: input not full block")
|
||||||
|
}
|
||||||
|
if len(dst) < sm4BlockSize {
|
||||||
|
panic("sm4: output not full block")
|
||||||
|
}
|
||||||
|
|
||||||
|
x0 := binary.BigEndian.Uint32(src[0:4])
|
||||||
|
x1 := binary.BigEndian.Uint32(src[4:8])
|
||||||
|
x2 := binary.BigEndian.Uint32(src[8:12])
|
||||||
|
x3 := binary.BigEndian.Uint32(src[12:16])
|
||||||
|
|
||||||
|
// 32 轮解密
|
||||||
|
for i := 0; i < 32; i++ {
|
||||||
|
t := x1 ^ x2 ^ x3 ^ c.dec[i]
|
||||||
|
x0 ^= sm4T1Fast(t)
|
||||||
|
x0, x1, x2, x3 = x1, x2, x3, x0
|
||||||
|
}
|
||||||
|
|
||||||
|
binary.BigEndian.PutUint32(dst[0:4], x3)
|
||||||
|
binary.BigEndian.PutUint32(dst[4:8], x2)
|
||||||
|
binary.BigEndian.PutUint32(dst[8:12], x1)
|
||||||
|
binary.BigEndian.PutUint32(dst[12:16], x0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用预计算查找表的快速 T1 变换(用于加密轮函数)
|
||||||
|
func sm4T1Fast(a uint32) uint32 {
|
||||||
|
return sm4T1Table[byte(a>>24)][0] ^
|
||||||
|
sm4T1Table[byte(a>>16)][1] ^
|
||||||
|
sm4T1Table[byte(a>>8)][2] ^
|
||||||
|
sm4T1Table[byte(a)][3]
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用预计算查找表的快速 T2 变换(用于密钥扩展)
|
||||||
|
func sm4T2Fast(a uint32) uint32 {
|
||||||
|
return sm4T2Table[byte(a>>24)][0] ^
|
||||||
|
sm4T2Table[byte(a>>16)][1] ^
|
||||||
|
sm4T2Table[byte(a>>8)][2] ^
|
||||||
|
sm4T2Table[byte(a)][3]
|
||||||
|
}
|
||||||
|
|
||||||
|
func sm4RotateLeft(x uint32, n uint32) uint32 {
|
||||||
|
return (x << n) | (x >> (32 - n))
|
||||||
|
}
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
package cryptor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/hex"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/duke-git/lancet/v2/internal"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSm3(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
assert := internal.NewAssert(t, "TestSm3")
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
input string
|
||||||
|
expected string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
input: "abc",
|
||||||
|
expected: "66c7f0f462eeedd9d1f2d46bdc10e4e24167c4875cf2f7a2297da02b8f4ba8e0",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
input: "abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd",
|
||||||
|
expected: "debe9ff92275b8a138604889c18e5a4d6fdb70e5387e5765293dcba39c0c5732",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
input: "",
|
||||||
|
expected: "1ab21d8355cfa17f8e61194831e81a8f22bec8c728fefb747ed035eb5082aa2b",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
result := Sm3([]byte(tt.input))
|
||||||
|
resultHex := hex.EncodeToString(result)
|
||||||
|
assert.Equal(tt.expected, resultHex)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSm4EcbEncryptDecrypt(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
assert := internal.NewAssert(t, "TestSm4EcbEncryptDecrypt")
|
||||||
|
|
||||||
|
key := []byte("1234567890abcdef") // 16 bytes
|
||||||
|
plaintext := []byte("Hello, SM4!")
|
||||||
|
|
||||||
|
// Encrypt
|
||||||
|
encrypted := Sm4EcbEncrypt(plaintext, key)
|
||||||
|
assert.IsNotNil(encrypted)
|
||||||
|
|
||||||
|
// Decrypt
|
||||||
|
decrypted := Sm4EcbDecrypt(encrypted, key)
|
||||||
|
assert.Equal(plaintext, decrypted)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSm4CbcEncryptDecrypt(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
assert := internal.NewAssert(t, "TestSm4CbcEncryptDecrypt")
|
||||||
|
|
||||||
|
key := []byte("1234567890abcdef") // 16 bytes
|
||||||
|
plaintext := []byte("Hello, SM4 CBC mode!")
|
||||||
|
|
||||||
|
// Encrypt
|
||||||
|
encrypted := Sm4CbcEncrypt(plaintext, key)
|
||||||
|
assert.IsNotNil(encrypted)
|
||||||
|
|
||||||
|
// Decrypt
|
||||||
|
decrypted := Sm4CbcDecrypt(encrypted, key)
|
||||||
|
assert.Equal(plaintext, decrypted)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSm4EcbWithLongData(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
assert := internal.NewAssert(t, "TestSm4EcbWithLongData")
|
||||||
|
|
||||||
|
key := []byte("1234567890abcdef")
|
||||||
|
plaintext := []byte("This is a longer message that spans multiple blocks for SM4 encryption testing.")
|
||||||
|
|
||||||
|
encrypted := Sm4EcbEncrypt(plaintext, key)
|
||||||
|
decrypted := Sm4EcbDecrypt(encrypted, key)
|
||||||
|
|
||||||
|
assert.Equal(plaintext, decrypted)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSm2EncryptDecrypt(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
assert := internal.NewAssert(t, "TestSm2EncryptDecrypt")
|
||||||
|
|
||||||
|
// Generate key pair
|
||||||
|
privateKey, err := GenerateSm2Key()
|
||||||
|
assert.IsNil(err)
|
||||||
|
assert.IsNotNil(privateKey)
|
||||||
|
|
||||||
|
plaintext := []byte("Hello, SM2!")
|
||||||
|
|
||||||
|
// Encrypt with public key
|
||||||
|
ciphertext, err := Sm2Encrypt(&privateKey.PublicKey, plaintext)
|
||||||
|
assert.IsNil(err)
|
||||||
|
assert.IsNotNil(ciphertext)
|
||||||
|
|
||||||
|
// Decrypt with private key
|
||||||
|
decrypted, err := Sm2Decrypt(privateKey, ciphertext)
|
||||||
|
assert.IsNil(err)
|
||||||
|
assert.Equal(plaintext, decrypted)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSm2WithLongData(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
assert := internal.NewAssert(t, "TestSm2WithLongData")
|
||||||
|
|
||||||
|
privateKey, err := GenerateSm2Key()
|
||||||
|
assert.IsNil(err)
|
||||||
|
|
||||||
|
plaintext := []byte("This is a longer message for SM2 encryption testing. " +
|
||||||
|
"SM2 is an elliptic curve public key cryptography algorithm.")
|
||||||
|
|
||||||
|
ciphertext, err := Sm2Encrypt(&privateKey.PublicKey, plaintext)
|
||||||
|
assert.IsNil(err)
|
||||||
|
|
||||||
|
decrypted, err := Sm2Decrypt(privateKey, ciphertext)
|
||||||
|
assert.IsNil(err)
|
||||||
|
assert.Equal(plaintext, decrypted)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSm4InvalidKeyLength(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
assert := internal.NewAssert(t, "TestSm4InvalidKeyLength")
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
if r := recover(); r != nil {
|
||||||
|
assert.IsNotNil(r)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
key := []byte("short")
|
||||||
|
plaintext := []byte("test")
|
||||||
|
Sm4EcbEncrypt(plaintext, key) // Should panic
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSm2InvalidInput(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
assert := internal.NewAssert(t, "TestSm2InvalidInput")
|
||||||
|
|
||||||
|
// Test with nil public key
|
||||||
|
_, err := Sm2Encrypt(nil, []byte("test"))
|
||||||
|
assert.IsNotNil(err)
|
||||||
|
|
||||||
|
// Test with nil private key
|
||||||
|
_, err = Sm2Decrypt(nil, []byte("test"))
|
||||||
|
assert.IsNotNil(err)
|
||||||
|
|
||||||
|
// Test with invalid ciphertext
|
||||||
|
privateKey, _ := GenerateSm2Key()
|
||||||
|
_, err = Sm2Decrypt(privateKey, []byte("short"))
|
||||||
|
assert.IsNotNil(err)
|
||||||
|
}
|
||||||
@@ -1,51 +1,51 @@
|
|||||||
-----BEGIN rsa private key-----
|
-----BEGIN rsa private key-----
|
||||||
MIIJKAIBAAKCAgEAw0anfgtraA2uaZwoLpLBvo1EkfYvDBgeXoMQ4WMKbcw6jU8k
|
MIIJKAIBAAKCAgEA4TSGNCTws7pRURptw911vSr9rISCcjSgpjxVFtxkDpri/L+Q
|
||||||
18E+f3WM52I2RssEk6g0X1vIiarHZU5qyxbv2iNoT7EfgizzlXYvx06pM69GNBQr
|
HwDaDpTnAx2FKfFkBbYNklSl3JtY4vZQ8hNDvfHbwt+PagbNaeiu5l1agl7s2ssW
|
||||||
V46+lNhiOv4eeLZcOHBnxAyizlIKyLuwO+C1cX/6BxuXjX3ogw+6IaBFZN/EOMmT
|
SXQ2dIKx45gtQxsuvAVGvmdgVEuyt/UwJrHgcyt5cqYejtRI5rcj509Pxegb3B84
|
||||||
Wc6sPKrnNCEqgCNiTbPAXb+N8j5Iv8QPs0AwVTB3jC9LP0mRt2GGD0cu+QIZkoGE
|
gkPwgy6xb2jYWBZ+pi6aLdm2TGX8SCsbCJcO5SD3GFI4fG9OhsSaToD0/OSYzIbQ
|
||||||
hyW9Dd+0tgeIK32uXCF8uDjNpUV1TxCdn5H+lvgddxfiaIJAdY5UaTx48XRIdULh
|
8WP6D7KX3y5tVHFqV6eFHT2ZIskDRzN8z6cDxp+K2QcCtv5F7yqnjVBYbnk0dmC/
|
||||||
QrVKXJNyTYWTXbezViYIf1nXOdDI2hsGgKTfNVCocDT1LcT5zebijFHVCWfAAKEP
|
woAaNMgvpSaC94cv0oFOS1TWivZDgpLkUJL2hu4V1xGflkHVAdz/DlSUIfiJ47sL
|
||||||
RLdzPZomkFIa3rQQgChgePzE8Oqsaxuwx8sU09NAo3giSq1OmBBwly7h60Lwtm8+
|
HOHnjBQXY81ruh10Xwf7Sh0P9TfNod0KITSZaqXljYaomEfMOXHn8t1xxy6mAF/c
|
||||||
XuwmWtEgZoSQy2Hm8UMAJ3guotfYuS8mPQBi55JZpdqVN0D5SdwuWXhHpO4xDodN
|
Zf/nSmXn+r3ue+cYHxPD0sHYQQqCCAAsNO/VT0Z1NXzjLwc497LwrfXnin0J2EGD
|
||||||
YAoMMei1NNgrX2zN3FCS8PVi97wD6cQ8xsWM62nByrzIjmPwTfoCb3qP/928FMJM
|
yNQf2LKCj8JhICRw72tMrzp8XAHodfxWNQzPL26k7ZzIGUUmlMn7ku0WcU2BsiGn
|
||||||
g7b3bYBrUnOrpVWZfAIDs4H7DoP8VLL4rMgB5PuWNQ13gtX7y5ZOyLhopiKLnar9
|
SXNPlFmeOqOzfdmgmiERbQPd3uzZ3a7pxhWlKGZSakZPEJeZHDEobmm+uBkr4OzI
|
||||||
XiN8GAMANBdKRI2anGEozrfJoelJ5POXZwSatRjbL+nWO3YnBzEunCw1xmMCAwEA
|
gc/jBNp3xa3wXiPxftzoPB3TpUQdN/mgW/DeHMS7V56ie3vqYZQG1vUC7rsCAwEA
|
||||||
AQKCAgBAYYABP3SW5sPVD+XzjPERiPPNh7P1MdJ5aI7dMFEU6Bt50VkdRRn83d2p
|
AQKCAgA1GCgHxSnGhcfEIkH8qoqmpasW8Eq82DGD37eD40PnuZaIVjWJSa8fPvXT
|
||||||
v6iTaIXGxNMXiWQxdzusO9FbyeEkMz5F3+i6e2WHpmKUPGvunV/w9aFgibBt1HV2
|
4zLQ96tIOWqrtC9CepGTONVOrUIMVygjoodyTNZDAOuzPhEnqW+YCcdgW/i2sVV1
|
||||||
a6fSNpVrCiw758qZaVUi3zZ4V1qa5A2j4EX0IUnSRBIi2ftnCZtg+Zx6JHiGu/Xk
|
Phx1tMPo6imKnF62oP4qprDKfqdXH8nLQOT1cZEaa9UYJLe/BgEDfYzaEWBz3R9S
|
||||||
KvcfLgtQAO5wOiJrdnt3tgVTHNuSipsvfbw6TmAbbKzNRrPG5xlVQxxVjmypMVMc
|
D9rpsav8TAJniuuSyXyYGymNdee6F3KKFmBg3fEajuF+XqLjuJVZqvM55gM/jjCG
|
||||||
HJmZdSNSPrwm5JtwXNkTSzAclv6v+XeFdztvJ1pnJ5jO5WAegy8MchNgcfLlWLt7
|
GrEF9pNGxST6BtrCu7d9IuNrJYobWuPmVOPL9tjQETNderLOoN7AhgDPv1nuVb/9
|
||||||
sYlngZQ/1+Q/UHh0GFDQD87yBOmNz8KK5n+5gWB5iumdJ4BHTgUOfXpWilwb0JWG
|
5L191C5vJ7MoyYCnVHYII8+WO3/JUMJVIk2cqssJ7/Kmg9HEkwSf18YqlZrL06tk
|
||||||
r7ctqCYrbXXTvsIbRl47zGPzEsbs0mSLAuLzZ3IQ60uaYRt322bqzZQNBwJcUXYM
|
sqSGjE+/BioPoVuYUXXge44vO1wubirEWE2j4MIac8h77YEVk3/z3L63n8KyJLee
|
||||||
lRb6nc9BVAzqhvUemOlACbYlqXENmQy/Nz14nsNdy4Qrynsfon92dRZ0m+9rJ9Hj
|
jBrbQoUIKQJxRM7KnOYvUuXtEuYd0koZaoYAUPoK/rEbtKpeEXSdSxrVf/eFAwXX
|
||||||
99K4CNPz0FdayC7jTL76b8QEzoF2MGiKIL5yQYXm9Pt9p0g8g9sER7G7UyrMFqtl
|
Rco0RIorId0eqrMr/ourR8T9A9NZJ0Tho432L/opd4iqy29TkbNHJ076LIM4ZmF7
|
||||||
tfylkAWRX5hgDCwQQ/Gqefn7xb/kG/4D1FBE5i2yU4tYw5NCzENo8Y3mUhBqiQql
|
KY0zlxiLEz9984Sn4cwyGAN/XrF2I/80du9GETMADlX+ut2Kaa6RWLaeANHuHqZY
|
||||||
G33sSv2JK/woxRWSbyGLfu1Iq2L8H/q4CdN55xat2iKbpL8omQKCAQEA6qX7V8A0
|
UJu83F88ijFxrRE/L7KzTcx5qLmkuLzs3REWb/RO8hqj+yOSUQKCAQEA8SbJS8un
|
||||||
uCg0E/Uid6/Xma0dvZ7e5BMKcx0uElSUhUpB6JnEQRlgljRXF/Op8Iae09Gox6bZ
|
OWBXY5ZggutOHDobFsB/rdaM5s4tawO3w9UllwzN+wotkVvdtdRCN6jUdefF7Elc
|
||||||
nU5Ow61wtSrnJY+f/2RVs9xYB+SSO0L0yE/XPKsBveH0dH9R4BWmH+KZ3sLaYovs
|
wfJH69xXEmztpagdYU5TNTdAIRegr4mDNO0a2ESZ7xDT+9oO/Zf61n1g2YMSxWGc
|
||||||
ZDsApR782Zh+1TthUT2s4vZ0G25f46xsjKpUzQLmgWeC3UEOThtQo/UZzLeprImI
|
1AhDO35bgMdimNlM65s9Nz4R1ZK3euTg0p2IpkIRTd+VRI9sxA9PQG4b5Zy9HHnS
|
||||||
fijMw+5jYUgHSXN80BXO56JzHQJU6SIDmA4BrlD0qPaDyzLVdNhG/nIbYKvf120p
|
Wv6DN7ULNKE2PBVlGWBXUGEndSXnnkTzIk8D2yZG0cpxiQilWlzs+XRa8URxRiy2
|
||||||
ogWqEYIgVN4KyjLsvVgfxCEF4Ucwov9VCNgsVTlEtYWzAXEXqf2AW1j7Sh4GlVOz
|
hdTSQPv9gR9hU833Ane9TlF6Y/tThVzOFV8DoUbyQuyyRcIqjvNnI8FAT69VTPr3
|
||||||
W4UsfiGaSCjM7wKCAQEA1QuDLQ4cf4UEKsdPOnDYrkHwx6JBBHpkyZZcLhlT/S5A
|
ogm8wWuksG2qkwKCAQEA7xJhL0YoUfmdt3s6YN97BhgZbFbm52XJiXPz/mlhlqwK
|
||||||
AcvVcEJjeseNfCEexO7SChenlRQEVB8iXO28ZEumWePEz2JK9rq9p7AItk+ba/D9
|
98w9vts4g5CAcnQbGyuj6r+OdQKgzK6YxJvs0DAokuQVYlqjfkB4KS55HDSzjKKy
|
||||||
qzfvZ/XE+1xs5szTfwr12Of8b9dXxhoW8gKcFPnKOHxvua6SyocmRlnZtaJRFZ7x
|
N7WYXqp5Tnb+FCMycn7WvhEKbwMSvSI5e6L+aMOog/+FsLwdfDmfljEacYMBn2zq
|
||||||
RxOZhfWoOUnc+ySYKhKyuipKR4KmyDd2d2ovxptlMFnj2RJzfjUIZiQpKTa8kXf7
|
AiAY8suN5dSKYXH6tf034FjyJYzT0HP2LA/qN/eXeF2fplapT0uXbjB9psUX6HEu
|
||||||
sYaOgFiNC0AFAs9ZLCEX3NYTKpgVbVKNIaKtNj8GIAG2YPnT/VcbQtj9ULyJcvEw
|
KPsEvl4xwJmAf8z+t6wbr6bTeHWCVvBsT/BQFrpkBacpohPRF0hb2JSetkT4dAk+
|
||||||
IdzJXn+Cv6ie1nP05P+eo/gtGmm5okXzMQNv0wcFzQKCAQBmDVBWJtMG8P1NXMTj
|
8xfnlCwm0h6ghSwcqWcQaOQ31drzsBRSmliwX9y8OQKCAQBkr4AOYHpyj1INZ4Tm
|
||||||
1wdm3+LacHkyKpHV5O//qud5XQVzO0UepwHZ8eObGC9l27bCGyJTyt5ESyV4dztY
|
RJ65VF1pE3h7uX/dAiqeas/4OO9X8OWzsh0yervIJlZ7bMdAb0QJEtxisejrhnTo
|
||||||
n9MuA9wrQCEB+6gRrrhmq8U4RXkv+pPkWJxv+lvKoL/CiFQxjP9b8s0Z/otWRTbl
|
YYibyORzc0N0jZv99SKHCBA7MeAqegIXedw4ZGQr55+4nGKqjnpw5P+Y29ZOacSE
|
||||||
ECzBYnT911wUzelLcOKla30+ZGpDS6qixzkkL0IgeELHPDc/UPWrg5lofSgpYsm4
|
sTrufJQMLyXRAd5qYLaw3g0sgs/CMwWMkRR+qq+L8KRzT0XgiZ+/2vFEQs3AnZuP
|
||||||
KpJ4wJCdE48MMRvtlvEE//UeMaFLhgwSXDyPqIkrq1CdI1WC4t2UnPaJb/s6aCTV
|
HtxJG9m5TatHCTlzRR8+yqUFJx6CCqo4/6CFyZFYeEINKVKrN5tf5F1U5XXf4haH
|
||||||
pEh/DkzmQKh4LYCYLNUbXv9FvHbzjdezNvXWf7AyD32+vOF1p79nPKL5/96M8OJf
|
KfX2CqHeauYkZAqI4i+OGCCHdcNLPBb8cF1CmP4x71iZ6h8S5i7kVEi+Y/hmfa4m
|
||||||
1dbjAoIBABKld02yNnxSwBKebyjGR7C4xMI0SUyDCd868cZ3IQq/yYpetMemh95v
|
Z7N3AoIBABvaBU5vmvTp4rDkf0mX34o3NocDnMTqe88yngNOnZrjEigKOEtK2Muj
|
||||||
KMr8exzxaiDIATrjDZ3vO6q2hA6jMGQds1QTXkxJ+995YMnUHd5MsWcS9jk7IYp+
|
AwPSePHyZJdNl7gUBU2zLYMCM1WRtrheMAuUSaXEtvr9OgjKLvy8W4zX8BdfPuCg
|
||||||
hGmO89PiubHKXCXNyzjjf66e29paIoDfI0g1J1PikE8H/i4Pjtk9mBCIfp9i6N5a
|
RjtsWk0yb6wW6iNCtWUpXo8DzyW/XZt7IkUTtU+qmufxcoY03/SFyMFUofNvOWnE
|
||||||
wKSah1bnXA0/NlEb9kz/zbaV7KiNYUXiGDcfjkw1iA6oi5G34Lk6ryTSihZhqbaa
|
GBcAI1geVushEZzESkznpY8+j2fTxWa1aYsEX5coVEz3Azxxi7Z9sQX/MG9JI/yv
|
||||||
W9XrH/rkypnhgrvvo7B10TRocJCW44pZnATQ2OULgq9PHpy6Y61Tvsq38Ef9EQyF
|
JWQ+KpKVT2hoRAyti/C687NgaMQtFMf/0H7cViijOmgB8HeFk3hZN2c0qrr9Zcxm
|
||||||
TaGndH+2f8QKLKhrKHwzcx2PF3J44uECggEBAM0UGu/Aj4tIRmrcuPGHypkcxMY6
|
2waIvBIUOrotlD+q0Wb7ByCKIooYeikCggEBANeckCBhJ+JLa3XYQeQ1wCwx8VzZ
|
||||||
BS2irwiVD9/8Xnx0/r8RSnBuAXEUY8wTrP0GqGm9PZjFCXKyxk3gi6SkahTu6/SF
|
qUh+Fn0PHP14kkCyGH5JHRYz4JwxjZhhtSSH4i8glJCDEO4Nd8o5b7ziyJ6wjtmB
|
||||||
WecgomVnONI+ivpHRLmRXTTPEv7iu1F+2jgVQyg0mOR5WLE0r25S6NS6IlnnrTSo
|
T/R6RxeWoCIyrmah5Fk/gHKbQJJP10yaDI2Pa2Dh5CDylNxaxMfuuHrM6KICXKqB
|
||||||
QuIJa1wRIfyXrMpYk77YIOny+mYB4FYr25tChgieQGR4m3dlZICPYqOyFh9GORZ8
|
Ke7V5vFK+sgrO5PCEEIyEu3xGg9sFeZRpMvAxn85e2xLRN2lt/rekEqRpbsNK0QD
|
||||||
k1cVboGtKGYtAemzAh/PyUp716tMz44fnnHPzINUFI3ucybqUwpGiR9s0E3L+GsV
|
Vjl5n2QKjg+yGtS9iFPP9BPT331SL1J0gyPZn86UcGNFbQFAN43z7cU9Jvk1FcQC
|
||||||
3h7a2v90RdyWcuAPJL0B5FL5NoHhOMYb1rCMu00FyqCKqXCgte2w2psOP60=
|
ywP+0ziNE4AxRFwqVMXnsHvAJ55ppLOXJ8p+gJSo0HKky6hr6WkJHKsfw4I=
|
||||||
-----END rsa private key-----
|
-----END rsa private key-----
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
-----BEGIN rsa public key-----
|
-----BEGIN rsa public key-----
|
||||||
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAw0anfgtraA2uaZwoLpLB
|
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA4TSGNCTws7pRURptw911
|
||||||
vo1EkfYvDBgeXoMQ4WMKbcw6jU8k18E+f3WM52I2RssEk6g0X1vIiarHZU5qyxbv
|
vSr9rISCcjSgpjxVFtxkDpri/L+QHwDaDpTnAx2FKfFkBbYNklSl3JtY4vZQ8hND
|
||||||
2iNoT7EfgizzlXYvx06pM69GNBQrV46+lNhiOv4eeLZcOHBnxAyizlIKyLuwO+C1
|
vfHbwt+PagbNaeiu5l1agl7s2ssWSXQ2dIKx45gtQxsuvAVGvmdgVEuyt/UwJrHg
|
||||||
cX/6BxuXjX3ogw+6IaBFZN/EOMmTWc6sPKrnNCEqgCNiTbPAXb+N8j5Iv8QPs0Aw
|
cyt5cqYejtRI5rcj509Pxegb3B84gkPwgy6xb2jYWBZ+pi6aLdm2TGX8SCsbCJcO
|
||||||
VTB3jC9LP0mRt2GGD0cu+QIZkoGEhyW9Dd+0tgeIK32uXCF8uDjNpUV1TxCdn5H+
|
5SD3GFI4fG9OhsSaToD0/OSYzIbQ8WP6D7KX3y5tVHFqV6eFHT2ZIskDRzN8z6cD
|
||||||
lvgddxfiaIJAdY5UaTx48XRIdULhQrVKXJNyTYWTXbezViYIf1nXOdDI2hsGgKTf
|
xp+K2QcCtv5F7yqnjVBYbnk0dmC/woAaNMgvpSaC94cv0oFOS1TWivZDgpLkUJL2
|
||||||
NVCocDT1LcT5zebijFHVCWfAAKEPRLdzPZomkFIa3rQQgChgePzE8Oqsaxuwx8sU
|
hu4V1xGflkHVAdz/DlSUIfiJ47sLHOHnjBQXY81ruh10Xwf7Sh0P9TfNod0KITSZ
|
||||||
09NAo3giSq1OmBBwly7h60Lwtm8+XuwmWtEgZoSQy2Hm8UMAJ3guotfYuS8mPQBi
|
aqXljYaomEfMOXHn8t1xxy6mAF/cZf/nSmXn+r3ue+cYHxPD0sHYQQqCCAAsNO/V
|
||||||
55JZpdqVN0D5SdwuWXhHpO4xDodNYAoMMei1NNgrX2zN3FCS8PVi97wD6cQ8xsWM
|
T0Z1NXzjLwc497LwrfXnin0J2EGDyNQf2LKCj8JhICRw72tMrzp8XAHodfxWNQzP
|
||||||
62nByrzIjmPwTfoCb3qP/928FMJMg7b3bYBrUnOrpVWZfAIDs4H7DoP8VLL4rMgB
|
L26k7ZzIGUUmlMn7ku0WcU2BsiGnSXNPlFmeOqOzfdmgmiERbQPd3uzZ3a7pxhWl
|
||||||
5PuWNQ13gtX7y5ZOyLhopiKLnar9XiN8GAMANBdKRI2anGEozrfJoelJ5POXZwSa
|
KGZSakZPEJeZHDEobmm+uBkr4OzIgc/jBNp3xa3wXiPxftzoPB3TpUQdN/mgW/De
|
||||||
tRjbL+nWO3YnBzEunCw1xmMCAwEAAQ==
|
HMS7V56ie3vqYZQG1vUC7rsCAwEAAQ==
|
||||||
-----END rsa public key-----
|
-----END rsa public key-----
|
||||||
@@ -239,8 +239,8 @@ func (l *List[T]) Merge(other *List[T]) *List[T] {
|
|||||||
l1, l2 := len(l.data), len(other.data)
|
l1, l2 := len(l.data), len(other.data)
|
||||||
ml := NewList(make([]T, l1+l2))
|
ml := NewList(make([]T, l1+l2))
|
||||||
|
|
||||||
data := append([]T{}, append(l.data, other.data...)...)
|
copy(ml.data, l.data)
|
||||||
ml.data = data
|
copy(ml.data[l1:], other.data)
|
||||||
|
|
||||||
return ml
|
return ml
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package datastructure
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/duke-git/lancet/v2/internal"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMergePreservesBackingStorage(t *testing.T) {
|
||||||
|
assert := internal.NewAssert(t, "TestMergePreservesBackingStorage")
|
||||||
|
backing := []int{1, 99, 100}
|
||||||
|
left := NewList(backing[:1])
|
||||||
|
merged := left.Merge(NewList([]int{2, 3}))
|
||||||
|
assert.Equal([]int{1, 2, 3}, merged.Data())
|
||||||
|
assert.Equal([]int{1, 99, 100}, backing)
|
||||||
|
merged.UpdateAt(0, 42)
|
||||||
|
assert.Equal([]int{1}, left.Data())
|
||||||
|
}
|
||||||
@@ -136,8 +136,8 @@ func (q *ArrayQueue[T]) Clear() {
|
|||||||
|
|
||||||
// Contain checks if the value is in queue or not
|
// Contain checks if the value is in queue or not
|
||||||
func (q *ArrayQueue[T]) Contain(value T) bool {
|
func (q *ArrayQueue[T]) Contain(value T) bool {
|
||||||
for _, v := range q.data {
|
for i := q.head; i < q.tail; i++ {
|
||||||
if reflect.DeepEqual(v, value) {
|
if reflect.DeepEqual(q.data[i], value) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ func (q *CircularQueue[T]) IsEmpty() bool {
|
|||||||
|
|
||||||
// IsFull checks if queue is full or not
|
// IsFull checks if queue is full or not
|
||||||
func (q *CircularQueue[T]) IsFull() bool {
|
func (q *CircularQueue[T]) IsFull() bool {
|
||||||
return (q.rear+1)%q.capacity == q.front
|
return q.capacity == 0 || (q.rear+1)%q.capacity == q.front
|
||||||
}
|
}
|
||||||
|
|
||||||
// Front return front value of queue
|
// Front return front value of queue
|
||||||
@@ -101,16 +101,15 @@ func (q *CircularQueue[T]) Dequeue() (*T, error) {
|
|||||||
|
|
||||||
// Clear the queue data
|
// Clear the queue data
|
||||||
func (q *CircularQueue[T]) Clear() {
|
func (q *CircularQueue[T]) Clear() {
|
||||||
q.data = []T{}
|
q.data = make([]T, q.capacity)
|
||||||
q.front = 0
|
q.front = 0
|
||||||
q.rear = 0
|
q.rear = 0
|
||||||
q.capacity = 0
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Contain checks if the value is in queue or not
|
// Contain checks if the value is in queue or not
|
||||||
func (q *CircularQueue[T]) Contain(value T) bool {
|
func (q *CircularQueue[T]) Contain(value T) bool {
|
||||||
for _, v := range q.data {
|
for i := q.front; i != q.rear; i = (i + 1) % q.capacity {
|
||||||
if reflect.DeepEqual(v, value) {
|
if reflect.DeepEqual(q.data[i], value) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package datastructure
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestCircularQueueReuseAfterClear(t *testing.T) {
|
||||||
|
queue := NewCircularQueue[int](3)
|
||||||
|
queue.Enqueue(1)
|
||||||
|
queue.Clear()
|
||||||
|
if err := queue.Enqueue(2); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if queue.Size() != 1 || queue.Front() != 2 {
|
||||||
|
t.Error("cleared queue could not be reused")
|
||||||
|
}
|
||||||
|
zero := NewCircularQueue[int](0)
|
||||||
|
if !zero.IsFull() || zero.Enqueue(1) == nil {
|
||||||
|
t.Error("zero-capacity queue should reject an element")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package datastructure
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestQueueContainActiveValues(t *testing.T) {
|
||||||
|
array := NewArrayQueue[int](5)
|
||||||
|
array.Enqueue(1)
|
||||||
|
array.Enqueue(2)
|
||||||
|
array.Dequeue()
|
||||||
|
if array.Contain(1) || !array.Contain(2) {
|
||||||
|
t.Error("array queue includes a dequeued value")
|
||||||
|
}
|
||||||
|
circular := NewCircularQueue[int](4)
|
||||||
|
if circular.Contain(0) {
|
||||||
|
t.Error("empty circular queue contains a zero value")
|
||||||
|
}
|
||||||
|
circular.Enqueue(1)
|
||||||
|
circular.Enqueue(2)
|
||||||
|
circular.Dequeue()
|
||||||
|
circular.Enqueue(3)
|
||||||
|
circular.Enqueue(4)
|
||||||
|
if circular.Contain(0) || circular.Contain(1) || !circular.Contain(4) {
|
||||||
|
t.Error("circular queue did not restrict its search to active values")
|
||||||
|
}
|
||||||
|
}
|
||||||
+11
-12
@@ -207,7 +207,7 @@ func FormatTimeToStr(t time.Time, format string, timezone ...string) string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
if timezone != nil && timezone[0] != "" {
|
if len(timezone) > 0 && timezone[0] != "" {
|
||||||
loc, err := time.LoadLocation(timezone[0])
|
loc, err := time.LoadLocation(timezone[0])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ""
|
return ""
|
||||||
@@ -225,7 +225,7 @@ func FormatStrToTime(str, format string, timezone ...string) (time.Time, error)
|
|||||||
return time.Time{}, fmt.Errorf("format %s not support", format)
|
return time.Time{}, fmt.Errorf("format %s not support", format)
|
||||||
}
|
}
|
||||||
|
|
||||||
if timezone != nil && timezone[0] != "" {
|
if len(timezone) > 0 && timezone[0] != "" {
|
||||||
loc, err := time.LoadLocation(timezone[0])
|
loc, err := time.LoadLocation(timezone[0])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return time.Time{}, err
|
return time.Time{}, err
|
||||||
@@ -343,11 +343,7 @@ func BetweenSeconds(t1 time.Time, t2 time.Time) int64 {
|
|||||||
// DayOfYear returns which day of the year the parameter date `t` is.
|
// DayOfYear returns which day of the year the parameter date `t` is.
|
||||||
// Play: https://go.dev/play/p/0hjqhTwFNlH
|
// Play: https://go.dev/play/p/0hjqhTwFNlH
|
||||||
func DayOfYear(t time.Time) int {
|
func DayOfYear(t time.Time) int {
|
||||||
y, m, d := t.Date()
|
return t.YearDay() - 1
|
||||||
firstDay := time.Date(y, 1, 1, 0, 0, 0, 0, t.Location())
|
|
||||||
nowDate := time.Date(y, m, d, 0, 0, 0, 0, t.Location())
|
|
||||||
|
|
||||||
return int(nowDate.Sub(firstDay).Hours() / 24)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsWeekend checks if passed time is weekend or not.
|
// IsWeekend checks if passed time is weekend or not.
|
||||||
@@ -365,7 +361,7 @@ func NowDateOrTime(format string, timezone ...string) string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
if timezone != nil && timezone[0] != "" {
|
if len(timezone) > 0 && timezone[0] != "" {
|
||||||
loc, err := time.LoadLocation(timezone[0])
|
loc, err := time.LoadLocation(timezone[0])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ""
|
return ""
|
||||||
@@ -382,7 +378,7 @@ func NowDateOrTime(format string, timezone ...string) string {
|
|||||||
func Timestamp(timezone ...string) int64 {
|
func Timestamp(timezone ...string) int64 {
|
||||||
t := time.Now()
|
t := time.Now()
|
||||||
|
|
||||||
if timezone != nil && timezone[0] != "" {
|
if len(timezone) > 0 && timezone[0] != "" {
|
||||||
loc, err := time.LoadLocation(timezone[0])
|
loc, err := time.LoadLocation(timezone[0])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0
|
return 0
|
||||||
@@ -399,7 +395,7 @@ func Timestamp(timezone ...string) int64 {
|
|||||||
func TimestampMilli(timezone ...string) int64 {
|
func TimestampMilli(timezone ...string) int64 {
|
||||||
t := time.Now()
|
t := time.Now()
|
||||||
|
|
||||||
if timezone != nil && timezone[0] != "" {
|
if len(timezone) > 0 && timezone[0] != "" {
|
||||||
loc, err := time.LoadLocation(timezone[0])
|
loc, err := time.LoadLocation(timezone[0])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0
|
return 0
|
||||||
@@ -415,7 +411,7 @@ func TimestampMilli(timezone ...string) int64 {
|
|||||||
func TimestampMicro(timezone ...string) int64 {
|
func TimestampMicro(timezone ...string) int64 {
|
||||||
t := time.Now()
|
t := time.Now()
|
||||||
|
|
||||||
if timezone != nil && timezone[0] != "" {
|
if len(timezone) > 0 && timezone[0] != "" {
|
||||||
loc, err := time.LoadLocation(timezone[0])
|
loc, err := time.LoadLocation(timezone[0])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0
|
return 0
|
||||||
@@ -431,7 +427,7 @@ func TimestampMicro(timezone ...string) int64 {
|
|||||||
func TimestampNano(timezone ...string) int64 {
|
func TimestampNano(timezone ...string) int64 {
|
||||||
t := time.Now()
|
t := time.Now()
|
||||||
|
|
||||||
if timezone != nil && timezone[0] != "" {
|
if len(timezone) > 0 && timezone[0] != "" {
|
||||||
loc, err := time.LoadLocation(timezone[0])
|
loc, err := time.LoadLocation(timezone[0])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0
|
return 0
|
||||||
@@ -495,6 +491,9 @@ func GenerateDatetimesBetween(start, end time.Time, layout string, interval stri
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if duration <= 0 {
|
||||||
|
return nil, fmt.Errorf("interval must be positive")
|
||||||
|
}
|
||||||
|
|
||||||
for current := start; !current.After(end); current = current.Add(duration) {
|
for current := start; !current.After(end); current = current.Add(duration) {
|
||||||
result = append(result, current.Format(layout))
|
result = append(result, current.Format(layout))
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package datetime
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
_ "time/tzdata"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDayOfYearDaylightSaving(t *testing.T) {
|
||||||
|
loc, err := time.LoadLocation("America/New_York")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, month := range []time.Month{time.January, time.July, time.December} {
|
||||||
|
date := time.Date(2024, month, 1, 12, 0, 0, 0, loc)
|
||||||
|
if got, want := DayOfYear(date), date.YearDay()-1; got != want {
|
||||||
|
t.Errorf("%v: got %d, want %d", date, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package datetime
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGenerateDatetimesNonPositiveInterval(t *testing.T) {
|
||||||
|
start := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||||
|
for _, interval := range []string{"0s", "-1h"} {
|
||||||
|
t.Run(interval, func(t *testing.T) {
|
||||||
|
if _, err := GenerateDatetimesBetween(start, start.Add(time.Hour), "2006-01-02", interval); err == nil {
|
||||||
|
t.Error("expected an error for a non-positive interval")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package datetime
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestEmptyTimezoneOptions(t *testing.T) {
|
||||||
|
empty := []string{}
|
||||||
|
now := time.Now()
|
||||||
|
if got := FormatTimeToStr(now, "yyyy-mm-dd", empty...); got != FormatTimeToStr(now, "yyyy-mm-dd") {
|
||||||
|
t.Errorf("unexpected date: %s", got)
|
||||||
|
}
|
||||||
|
if _, err := FormatStrToTime("2026-01-02", "yyyy-mm-dd", empty...); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if NowDateOrTime("yyyy", empty...) == "" {
|
||||||
|
t.Error("empty date")
|
||||||
|
}
|
||||||
|
for _, fn := range []func(...string) int64{Timestamp, TimestampMilli, TimestampMicro, TimestampNano} {
|
||||||
|
if fn(empty...) == 0 {
|
||||||
|
t.Error("empty timestamp")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -114,6 +114,7 @@ export const enConfig: LocaleSpecificConfig<DefaultTheme.Config> = {
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
{ text: 'datetime', link: '/en/api/packages/datetime' },
|
{ text: 'datetime', link: '/en/api/packages/datetime' },
|
||||||
|
{ text: 'enum', link: '/en/api/packages/enum' },
|
||||||
{ text: 'eventbus', link: '/en/api/packages/eventbus' },
|
{ text: 'eventbus', link: '/en/api/packages/eventbus' },
|
||||||
{ text: 'fileutil', link: '/en/api/packages/fileutil' },
|
{ text: 'fileutil', link: '/en/api/packages/fileutil' },
|
||||||
{ text: 'formatter', link: '/en/api/packages/formatter' },
|
{ text: 'formatter', link: '/en/api/packages/formatter' },
|
||||||
@@ -128,9 +129,9 @@ export const enConfig: LocaleSpecificConfig<DefaultTheme.Config> = {
|
|||||||
{ text: 'stream', link: '/en/api/packages/stream' },
|
{ text: 'stream', link: '/en/api/packages/stream' },
|
||||||
{ text: 'struct', link: '/en/api/packages/struct' },
|
{ text: 'struct', link: '/en/api/packages/struct' },
|
||||||
{ text: 'strutil', link: '/en/api/packages/strutil' },
|
{ text: 'strutil', link: '/en/api/packages/strutil' },
|
||||||
{ text: 'system', link: '/en/api/packages/system' },
|
|
||||||
{ text: 'tuple', link: '/en/api/packages/tuple' },
|
{ text: 'tuple', link: '/en/api/packages/tuple' },
|
||||||
{ text: 'validator', link: '/en/api/packages/validator' },
|
{ text: 'validator', link: '/en/api/packages/validator' },
|
||||||
|
{ text: 'system', link: '/en/api/packages/system' },
|
||||||
{ text: 'xerror', link: '/en/api/packages/xerror' },
|
{ text: 'xerror', link: '/en/api/packages/xerror' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -128,7 +128,7 @@ export const zhConfig: LocaleSpecificConfig<DefaultTheme.Config> = {
|
|||||||
},
|
},
|
||||||
{ text: '日期&时间', link: '/api/packages/datetime' },
|
{ text: '日期&时间', link: '/api/packages/datetime' },
|
||||||
{ text: '事件总线', link: '/api/packages/eventbus' },
|
{ text: '事件总线', link: '/api/packages/eventbus' },
|
||||||
{ text: '文件', link: '/api/packages/fileutil' },
|
{ text: '文件处理', link: '/api/packages/fileutil' },
|
||||||
{ text: '格式化工具', link: '/api/packages/formatter' },
|
{ text: '格式化工具', link: '/api/packages/formatter' },
|
||||||
{ text: '函数', link: '/api/packages/function' },
|
{ text: '函数', link: '/api/packages/function' },
|
||||||
{ text: '数学工具', link: '/api/packages/mathutil' },
|
{ text: '数学工具', link: '/api/packages/mathutil' },
|
||||||
@@ -141,9 +141,10 @@ export const zhConfig: LocaleSpecificConfig<DefaultTheme.Config> = {
|
|||||||
{ text: '流', link: '/api/packages/stream' },
|
{ text: '流', link: '/api/packages/stream' },
|
||||||
{ text: '结构体', link: '/api/packages/struct' },
|
{ text: '结构体', link: '/api/packages/struct' },
|
||||||
{ text: '字符串', link: '/api/packages/strutil' },
|
{ text: '字符串', link: '/api/packages/strutil' },
|
||||||
{ text: '系统', link: '/api/packages/system' },
|
{ text: '枚举', link: '/api/packages/enum' },
|
||||||
{ text: '元组', link: '/api/packages/tuple' },
|
{ text: '元组', link: '/api/packages/tuple' },
|
||||||
{ text: '验证器', link: '/api/packages/validator' },
|
{ text: '验证器', link: '/api/packages/validator' },
|
||||||
|
{ text: '系统工具函数', link: '/api/packages/system' },
|
||||||
{ text: '错误处理', link: '/api/packages/xerror' },
|
{ text: '错误处理', link: '/api/packages/xerror' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ outline: deep
|
|||||||
<div class="package-cell">cryptor</div>
|
<div class="package-cell">cryptor</div>
|
||||||
<div class="package-cell">datastructure</div>
|
<div class="package-cell">datastructure</div>
|
||||||
<div class="package-cell">datetime</div>
|
<div class="package-cell">datetime</div>
|
||||||
|
<div class="package-cell">enum</div>
|
||||||
<div class="package-cell">eventbus</div>
|
<div class="package-cell">eventbus</div>
|
||||||
<div class="package-cell">fileutil</div>
|
<div class="package-cell">fileutil</div>
|
||||||
<div class="package-cell">formatter</div>
|
<div class="package-cell">formatter</div>
|
||||||
|
|||||||
@@ -33,6 +33,9 @@ import (
|
|||||||
- [ToJson](#ToJson)
|
- [ToJson](#ToJson)
|
||||||
- [ToMap](#ToMap)
|
- [ToMap](#ToMap)
|
||||||
- [ToPointer](#ToPointer)
|
- [ToPointer](#ToPointer)
|
||||||
|
- [ToPointers](#ToPointers)
|
||||||
|
- [FromPointer](#FromPointer)
|
||||||
|
- [FromPointers](#FromPointers)
|
||||||
- [ToString](#ToString)
|
- [ToString](#ToString)
|
||||||
- [StructToMap](#StructToMap)
|
- [StructToMap](#StructToMap)
|
||||||
- [MapToSlice](#MapToSlice)
|
- [MapToSlice](#MapToSlice)
|
||||||
@@ -456,6 +459,108 @@ func main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### <span id="ToPointers">ToPointers</span>
|
||||||
|
|
||||||
|
<p>将值的切片转换为指针的切片。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func ToPointers[T any](values []T) []*T
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/ZUoXd2i5ZkV)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/convertor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
strs := []string{"a", "b", "c"}
|
||||||
|
pointerStrs := convertor.ToPointers(strs)
|
||||||
|
fmt.Println(*pointerStrs[0])
|
||||||
|
fmt.Println(*pointerStrs[1])
|
||||||
|
fmt.Println(*pointerStrs[2])
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// a
|
||||||
|
// b
|
||||||
|
// c
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="FromPointer">FromPointer</span>
|
||||||
|
|
||||||
|
<p>返回指针所指向的值。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func FromPointer[T any](ptr *T) T
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/wAp90V7Zu6g)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/convertor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
str := "abc"
|
||||||
|
strPtr := &str
|
||||||
|
result := convertor.FromPointer(strPtr)
|
||||||
|
fmt.Println(result)
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// abc
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="FromPointers">FromPointers</span>
|
||||||
|
|
||||||
|
<p>将指针的切片转换为值的切片。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func FromPointers[T any](pointers []*T) []T
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/qIPsyYtNy3Q)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/convertor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
strs := []string{"a", "b", "c"}
|
||||||
|
strPtr := []*string{&strs[0], &strs[1], &strs[2]}
|
||||||
|
|
||||||
|
result := convertor.FromPointers(strPtr)
|
||||||
|
|
||||||
|
fmt.Println(result[0])
|
||||||
|
fmt.Println(result[1])
|
||||||
|
fmt.Println(result[2])
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// a
|
||||||
|
// b
|
||||||
|
// c
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### <span id="ToString">ToString</span>
|
### <span id="ToString">ToString</span>
|
||||||
|
|
||||||
<p>将值转换为字符串,对于数字、字符串、[]byte,将转换为字符串。 对于其他类型(切片、映射、数组、结构体)将调用 json.Marshal</p>
|
<p>将值转换为字符串,对于数字、字符串、[]byte,将转换为字符串。 对于其他类型(切片、映射、数组、结构体)将调用 json.Marshal</p>
|
||||||
@@ -1179,4 +1284,4 @@ func main() {
|
|||||||
// Output:
|
// Output:
|
||||||
// 9876543210
|
// 9876543210
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
# Cryptor
|
# Cryptor
|
||||||
|
|
||||||
cryptor 包包含数据加密和解密功能。支持 base64, md5, hmac, hash, aes, des, rsa。
|
cryptor 包包含数据加密和解密功能。支持 base64, md5, hmac, hash, aes, des, rsa, sm2, sm3, sm4。
|
||||||
|
|
||||||
<div STYLE="page-break-after: always;"></div>
|
<div STYLE="page-break-after: always;"></div>
|
||||||
|
|
||||||
@@ -74,6 +74,14 @@ import (
|
|||||||
- [RsaDecryptOAEP](#RsaDecryptOAEP)
|
- [RsaDecryptOAEP](#RsaDecryptOAEP)
|
||||||
- [RsaSign](#RsaSign)
|
- [RsaSign](#RsaSign)
|
||||||
- [RsaVerifySign](#RsaVerifySign)
|
- [RsaVerifySign](#RsaVerifySign)
|
||||||
|
- [Sm3](#Sm3)
|
||||||
|
- [Sm4EcbEncrypt](#Sm4EcbEncrypt)
|
||||||
|
- [Sm4EcbDecrypt](#Sm4EcbDecrypt)
|
||||||
|
- [Sm4CbcEncrypt](#Sm4CbcEncrypt)
|
||||||
|
- [Sm4CbcDecrypt](#Sm4CbcDecrypt)
|
||||||
|
- [GenerateSm2Key](#GenerateSm2Key)
|
||||||
|
- [Sm2Encrypt](#Sm2Encrypt)
|
||||||
|
- [Sm2Decrypt](#Sm2Decrypt)
|
||||||
|
|
||||||
<div STYLE="page-break-after: always;"></div>
|
<div STYLE="page-break-after: always;"></div>
|
||||||
|
|
||||||
@@ -1829,3 +1837,279 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
### <span id="Sm3">Sm3</span>
|
||||||
|
|
||||||
|
<p>计算 SM3 哈希值(国密SM3密码杂凑算法)。SM3 是中国国家密码管理局发布的密码杂凑算法,用于替代 MD5/SHA-1/SHA-2 等国际算法。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func Sm3(data []byte) []byte
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/zDAQpteAiOc)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/cryptor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
data := []byte("hello world")
|
||||||
|
hash := cryptor.Sm3(data)
|
||||||
|
|
||||||
|
fmt.Println(hex.EncodeToString(hash))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// 44f0061e69fa6fdfc290c494654a05dc0c053da7e5c52b84ef93a9d67d3fff88
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Sm4EcbEncrypt">Sm4EcbEncrypt</span>
|
||||||
|
|
||||||
|
<p>使用 SM4 ECB 模式加密数据(国密SM4分组密码算法)。密钥长度必须为 16 字节。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func Sm4EcbEncrypt(data, key []byte) []byte
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/l5IQxYuuaED)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/cryptor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
key := []byte("1234567890abcdef") // 16 bytes key
|
||||||
|
plaintext := []byte("hello world")
|
||||||
|
|
||||||
|
encrypted := cryptor.Sm4EcbEncrypt(plaintext, key)
|
||||||
|
decrypted := cryptor.Sm4EcbDecrypt(encrypted, key)
|
||||||
|
|
||||||
|
fmt.Println(string(decrypted))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// hello world
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Sm4EcbDecrypt">Sm4EcbDecrypt</span>
|
||||||
|
|
||||||
|
<p>使用 SM4 ECB 模式解密数据。密钥长度必须为 16 字节。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func Sm4EcbDecrypt(encrypted, key []byte) []byte
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/l5IQxYuuaED)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/cryptor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
key := []byte("1234567890abcdef")
|
||||||
|
plaintext := []byte("hello world")
|
||||||
|
|
||||||
|
encrypted := cryptor.Sm4EcbEncrypt(plaintext, key)
|
||||||
|
decrypted := cryptor.Sm4EcbDecrypt(encrypted, key)
|
||||||
|
|
||||||
|
fmt.Println(string(decrypted))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// hello world
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Sm4CbcEncrypt">Sm4CbcEncrypt</span>
|
||||||
|
|
||||||
|
<p>使用 SM4 CBC 模式加密数据。密钥长度必须为 16 字节。返回的密文包含 IV(前 16 字节)。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func Sm4CbcEncrypt(data, key []byte) []byte
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/65Q6iYhLRTa)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/cryptor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
key := []byte("1234567890abcdef")
|
||||||
|
plaintext := []byte("hello world")
|
||||||
|
|
||||||
|
encrypted := cryptor.Sm4CbcEncrypt(plaintext, key)
|
||||||
|
decrypted := cryptor.Sm4CbcDecrypt(encrypted, key)
|
||||||
|
|
||||||
|
fmt.Println(string(decrypted))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// hello world
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Sm4CbcDecrypt">Sm4CbcDecrypt</span>
|
||||||
|
|
||||||
|
<p>使用 SM4 CBC 模式解密数据。密钥长度必须为 16 字节。密文应包含 IV(前 16 字节)。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func Sm4CbcDecrypt(encrypted, key []byte) []byte
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/65Q6iYhLRTa)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/cryptor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
key := []byte("1234567890abcdef")
|
||||||
|
plaintext := []byte("hello world")
|
||||||
|
|
||||||
|
encrypted := cryptor.Sm4CbcEncrypt(plaintext, key)
|
||||||
|
decrypted := cryptor.Sm4CbcDecrypt(encrypted, key)
|
||||||
|
|
||||||
|
fmt.Println(string(decrypted))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// hello world
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="GenerateSm2Key">GenerateSm2Key</span>
|
||||||
|
|
||||||
|
<p>生成 SM2 密钥对(国密SM2椭圆曲线公钥密码算法)。SM2 是基于椭圆曲线的非对称加密算法。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func GenerateSm2Key() (*Sm2PrivateKey, error)
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/bKYMqRLvIx3)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/cryptor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
privateKey, err := cryptor.GenerateSm2Key()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
plaintext := []byte("hello world")
|
||||||
|
|
||||||
|
ciphertext, _ := cryptor.Sm2Encrypt(&privateKey.PublicKey, plaintext)
|
||||||
|
decrypted, _ := cryptor.Sm2Decrypt(privateKey, ciphertext)
|
||||||
|
|
||||||
|
fmt.Println(string(decrypted))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// hello world
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Sm2Encrypt">Sm2Encrypt</span>
|
||||||
|
|
||||||
|
<p>使用 SM2 公钥加密数据。返回的密文格式为:C1(65字节) || C3(32字节) || C2(明文长度)。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func Sm2Encrypt(pub *Sm2PublicKey, plaintext []byte) ([]byte, error)
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/bKYMqRLvIx3)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/cryptor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
privateKey, _ := cryptor.GenerateSm2Key()
|
||||||
|
plaintext := []byte("hello world")
|
||||||
|
|
||||||
|
ciphertext, _ := cryptor.Sm2Encrypt(&privateKey.PublicKey, plaintext)
|
||||||
|
decrypted, _ := cryptor.Sm2Decrypt(privateKey, ciphertext)
|
||||||
|
|
||||||
|
fmt.Println(string(decrypted))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// hello world
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Sm2Decrypt">Sm2Decrypt</span>
|
||||||
|
|
||||||
|
<p>使用 SM2 私钥解密数据。密文格式应为:C1(65字节) || C3(32字节) || C2(明文长度)。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func Sm2Decrypt(priv *Sm2PrivateKey, ciphertext []byte) ([]byte, error)
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/bKYMqRLvIx3)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/cryptor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
privateKey, _ := cryptor.GenerateSm2Key()
|
||||||
|
plaintext := []byte("hello world")
|
||||||
|
|
||||||
|
ciphertext, _ := cryptor.Sm2Encrypt(&privateKey.PublicKey, plaintext)
|
||||||
|
decrypted, _ := cryptor.Sm2Decrypt(privateKey, ciphertext)
|
||||||
|
|
||||||
|
fmt.Println(string(decrypted))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// hello world
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -0,0 +1,850 @@
|
|||||||
|
# Enum
|
||||||
|
|
||||||
|
Enum 实现一个简单枚举工具包。
|
||||||
|
|
||||||
|
<div STYLE="page-break-after: always;"></div>
|
||||||
|
|
||||||
|
## 源码:
|
||||||
|
|
||||||
|
- [https://github.com/duke-git/lancet/blob/main/enum/enum.go](https://github.com/duke-git/lancet/blob/main/enum/enum.go)
|
||||||
|
|
||||||
|
<div STYLE="page-break-after: always;"></div>
|
||||||
|
|
||||||
|
## 用法:
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
<div STYLE="page-break-after: always;"></div>
|
||||||
|
|
||||||
|
## 目录
|
||||||
|
|
||||||
|
- [NewItem](#NewItem)
|
||||||
|
- [NewItemsFromPairs](#NewItemsFromPairs)
|
||||||
|
- [Value](#Value)
|
||||||
|
- [Name](#Name)
|
||||||
|
- [Valid](#Valid)
|
||||||
|
- [MarshalJSON](#MarshalJSON)
|
||||||
|
- [NewRegistry](#NewRegistry)
|
||||||
|
- [Add](#Add)
|
||||||
|
- [Remove](#Remove)
|
||||||
|
- [Update](#Update)
|
||||||
|
- [GetByValue](#GetByValue)
|
||||||
|
- [GetByName](#GetByName)
|
||||||
|
- [Items](#Items)
|
||||||
|
- [Contains](#Contains)
|
||||||
|
- [Size](#Size)
|
||||||
|
- [Range](#Range)
|
||||||
|
- [SortedItems](#SortedItems)
|
||||||
|
- [Filter](#Filter)
|
||||||
|
|
||||||
|
<div STYLE="page-break-after: always;"></div>
|
||||||
|
|
||||||
|
## 文档
|
||||||
|
|
||||||
|
### <span id="NewItem">NewItem</span>
|
||||||
|
|
||||||
|
<p>创建枚举项。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func NewItem[T comparable](value T, name string) *Item[T]
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/8qNsLw01HD5)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
item1 := enum.NewItem(Active, "Active")
|
||||||
|
item2 := enum.NewItem(Inactive, "Inactive")
|
||||||
|
|
||||||
|
fmt.Println(item1.Name(), item1.Value())
|
||||||
|
fmt.Println(item2.Name(), item2.Value())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Active 1
|
||||||
|
// Inactive 2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="NewItemsFromPairs">NewItemsFromPairs</span>
|
||||||
|
|
||||||
|
<p>从Pair结构体的切片创建枚举项。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func NewItemsFromPairs[T comparable](pairs ...Pair[T]) []*Item[T]
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/xKnoGa7gnev)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
items := enum.NewItemsFromPairs(
|
||||||
|
enum.Pair[Status]{Value: Active, Name: "Active"},
|
||||||
|
enum.Pair[Status]{Value: Inactive, Name: "Inactive"},
|
||||||
|
)
|
||||||
|
|
||||||
|
fmt.Println(items[0].Name(), items[0].Value())
|
||||||
|
fmt.Println(items[1].Name(), items[1].Value())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Active 1
|
||||||
|
// Inactive 2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Value">Value</span>
|
||||||
|
|
||||||
|
<p>返回枚举项的值。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (it *Item[T]) Value() T
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/xKnoGa7gnev)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
items := enum.NewItemsFromPairs(
|
||||||
|
enum.Pair[Status]{Value: Active, Name: "Active"},
|
||||||
|
enum.Pair[Status]{Value: Inactive, Name: "Inactive"},
|
||||||
|
)
|
||||||
|
|
||||||
|
fmt.Println(items[0].Name(), items[0].Value())
|
||||||
|
fmt.Println(items[1].Name(), items[1].Value())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Active 1
|
||||||
|
// Inactive 2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Name">Name</span>
|
||||||
|
|
||||||
|
<p>返回枚举项的名称。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (it *Item[T]) Name() string
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/xKnoGa7gnev)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
items := enum.NewItemsFromPairs(
|
||||||
|
enum.Pair[Status]{Value: Active, Name: "Active"},
|
||||||
|
enum.Pair[Status]{Value: Inactive, Name: "Inactive"},
|
||||||
|
)
|
||||||
|
|
||||||
|
fmt.Println(items[0].Name(), items[0].Value())
|
||||||
|
fmt.Println(items[1].Name(), items[1].Value())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Active 1
|
||||||
|
// Inactive 2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Valid">Valid</span>
|
||||||
|
|
||||||
|
<p>检查枚举项是否有效。如果提供了自定义检查函数,将使用该函数验证值。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (it *Item[T]) Valid(checker ...func(T) bool) bool
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/pA3lYY2VSm3)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
item := enum.NewItem(Active, "Active")
|
||||||
|
fmt.Println(item.Valid())
|
||||||
|
|
||||||
|
invalidItem := enum.NewItem(Unknown, "")
|
||||||
|
fmt.Println(invalidItem.Valid())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// true
|
||||||
|
// false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="MarshalJSON">MarshalJSON</span>
|
||||||
|
|
||||||
|
<p>枚举项实现json.Marshaler接口。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (it *Item[T]) MarshalJSON() ([]byte, error)
|
||||||
|
func (it *Item[T]) UnmarshalJSON(data []byte) error
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/zIZEdAnneB5)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
item := enum.NewItem(Active, "Active")
|
||||||
|
data, _ := item.MarshalJSON()
|
||||||
|
fmt.Println(string(data))
|
||||||
|
|
||||||
|
var unmarshaledItem enum.Item[Status]
|
||||||
|
_ = unmarshaledItem.UnmarshalJSON(data)
|
||||||
|
fmt.Println(unmarshaledItem.Name(), unmarshaledItem.Value())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// {"name":"Active","value":1}
|
||||||
|
// Active 1
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="NewRegistry">NewRegistry</span>
|
||||||
|
|
||||||
|
<p>Registry 定义了一个通用的枚举注册表结构体。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func NewRegistry[T comparable](items ...*Item[T]) *Registry[T]
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/ABEXsYfJKMo)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
item1 := enum.NewItem(Active, "Active")
|
||||||
|
item2 := enum.NewItem(Inactive, "Inactive")
|
||||||
|
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
if item, found := registry.GetByValue(Active); found {
|
||||||
|
fmt.Println("Found by value:", item.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
if item, found := registry.GetByName("Inactive"); found {
|
||||||
|
fmt.Println("Found by name:", item.Value())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Found by value: Active
|
||||||
|
// Found by name: 2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Add">Add</span>
|
||||||
|
|
||||||
|
<p>向枚举注册表添加枚举项。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (r *Registry[T]) Add(items ...*Item[T])
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/ABEXsYfJKMo)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
item1 := enum.NewItem(Active, "Active")
|
||||||
|
item2 := enum.NewItem(Inactive, "Inactive")
|
||||||
|
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
if item, found := registry.GetByValue(Active); found {
|
||||||
|
fmt.Println("Found by value:", item.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
if item, found := registry.GetByName("Inactive"); found {
|
||||||
|
fmt.Println("Found by name:", item.Value())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Found by value: Active
|
||||||
|
// Found by name: 2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Remove">Remove</span>
|
||||||
|
|
||||||
|
<p>在枚举注册表中删除枚举项。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (r *Registry[T]) Remove(value T) bool
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/dSG84wQ3TuC)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
item1 := enum.NewItem(Active, "Active")
|
||||||
|
|
||||||
|
registry.Add(item1)
|
||||||
|
fmt.Println("Size before removal:", registry.Size())
|
||||||
|
|
||||||
|
removed := registry.Remove(Active)
|
||||||
|
fmt.Println("Removed:", removed)
|
||||||
|
fmt.Println("Size after removal:", registry.Size())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Size before removal: 1
|
||||||
|
// Removed: true
|
||||||
|
// Size after removal: 0
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Update">Update</span>
|
||||||
|
|
||||||
|
<p>在枚举注册表中更新枚举项。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (r *Registry[T]) Update(value T, newName string) bool
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/Ol0moT1J9Xl)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
item1 := enum.NewItem(Active, "Active")
|
||||||
|
|
||||||
|
registry.Add(item1)
|
||||||
|
updated := registry.Update(Active, "Activated")
|
||||||
|
fmt.Println("Updated:", updated)
|
||||||
|
|
||||||
|
if item, found := registry.GetByValue(Active); found {
|
||||||
|
fmt.Println("New name:", item.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Updated: true
|
||||||
|
// New name: Activated
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="GetByValue">GetByValue</span>
|
||||||
|
|
||||||
|
<p>在枚举注册表中通过值获取枚举项。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (r *Registry[T]) GetByValue(value T) (*Item[T], bool)
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/niJ1U2KlE_m)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
item := enum.NewItem(Active, "Active")
|
||||||
|
|
||||||
|
registry.Add(item)
|
||||||
|
|
||||||
|
if item, found := registry.GetByValue(Active); found {
|
||||||
|
fmt.Println("Found name by value:", item.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Found name by value: Active
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="GetByName">GetByName</span>
|
||||||
|
|
||||||
|
<p>在枚举注册表中通过名称获取枚举项。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (r *Registry[T]) GetByName(name string) (*Item[T], bool)
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/49ie_gpqH0m)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
item := enum.NewItem(Active, "Active")
|
||||||
|
|
||||||
|
registry.Add(item)
|
||||||
|
|
||||||
|
if item, found := registry.GetByName("Active"); found {
|
||||||
|
fmt.Println("Found value by name:", item.Value())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Found value by name: 1
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Items">Items</span>
|
||||||
|
|
||||||
|
<p>返回枚举注册表中的枚举项。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (r *Registry[T]) Items() []*Item[T]
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/lAJFAradbvQ)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
item1 := enum.NewItem(Active, "Active")
|
||||||
|
item2 := enum.NewItem(Inactive, "Inactive")
|
||||||
|
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
for _, item := range registry.Items() {
|
||||||
|
fmt.Println(item.Name(), item.Value())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Active 1
|
||||||
|
// Inactive 2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Contains">Contains</span>
|
||||||
|
|
||||||
|
<p>检查注册表中是否存在具有给定值的枚举项。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (r *Registry[T]) Contains(value T) bool
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/_T-lPYkZn2j)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
item := enum.NewItem(Active, "Active")
|
||||||
|
registry.Add(item)
|
||||||
|
|
||||||
|
fmt.Println(registry.Contains(Active))
|
||||||
|
fmt.Println(registry.Contains(Inactive))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// true
|
||||||
|
// false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Size">Size</span>
|
||||||
|
|
||||||
|
<p>返回注册表中枚举项的数目。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (r *Registry[T]) Size() int
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/TeDArWhlQe2)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
fmt.Println("Initial size:", registry.Size())
|
||||||
|
|
||||||
|
item1 := enum.NewItem(Active, "Active")
|
||||||
|
item2 := enum.NewItem(Inactive, "Inactive")
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
fmt.Println("Size after adding items:", registry.Size())
|
||||||
|
|
||||||
|
registry.Remove(Active)
|
||||||
|
fmt.Println("Size after removing an item:", registry.Size())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Initial size: 0
|
||||||
|
// Size after adding items: 2
|
||||||
|
// Size after removing an item: 1
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Range">Range</span>
|
||||||
|
|
||||||
|
<p>遍历注册表中的所有枚举项,并应用给定的函数。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (r *Registry[T]) Range(fn func(*Item[T]) bool)
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/GPsZbQbefWN)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
item1 := enum.NewItem(Active, "Active")
|
||||||
|
item2 := enum.NewItem(Inactive, "Inactive")
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
registry.Range(func(item *enum.Item[Status]) bool {
|
||||||
|
fmt.Println(item.Name(), item.Value())
|
||||||
|
return true // continue iteration
|
||||||
|
})
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Active 1
|
||||||
|
// Inactive 2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="SortedItems">SortedItems</span>
|
||||||
|
|
||||||
|
<p>返回按给定比较函数排序的所有枚举项的切片。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (r *Registry[T]) SortedItems(less func(*Item[T], *Item[T]) bool) []*Item[T]
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/tN9RE_m_WEI)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
item1 := enum.NewItem(Inactive, "Inactive")
|
||||||
|
item2 := enum.NewItem(Active, "Active")
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
for _, item := range registry.SortedItems(func(i1, i2 *enum.Item[Status]) bool {
|
||||||
|
return i1.Value() < i2.Value()
|
||||||
|
}) {
|
||||||
|
fmt.Println(item.Name(), item.Value())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Active 1
|
||||||
|
// Inactive 2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Filter">Filter</span>
|
||||||
|
|
||||||
|
<p>返回满足给定谓词函数的枚举项切片。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (r *Registry[T]) Filter(predicate func(*Item[T]) bool) []*Item[T]
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/uTUpTdcyoCU)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
item1 := enum.NewItem(Active, "Active")
|
||||||
|
item2 := enum.NewItem(Inactive, "Inactive")
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
activeItems := registry.Filter(func(item *enum.Item[Status]) bool {
|
||||||
|
return item.Value() == Active
|
||||||
|
})
|
||||||
|
|
||||||
|
for _, item := range activeItems {
|
||||||
|
fmt.Println(item.Name(), item.Value())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Active 1
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -8,6 +8,7 @@ formatter 格式化器包含一些数据格式化处理方法。
|
|||||||
|
|
||||||
- [https://github.com/duke-git/lancet/blob/main/formatter/formatter.go](https://github.com/duke-git/lancet/blob/main/formatter/formatter.go)
|
- [https://github.com/duke-git/lancet/blob/main/formatter/formatter.go](https://github.com/duke-git/lancet/blob/main/formatter/formatter.go)
|
||||||
- [https://github.com/duke-git/lancet/blob/main/formatter/byte.go](https://github.com/duke-git/lancet/blob/main/formatter/byte.go)
|
- [https://github.com/duke-git/lancet/blob/main/formatter/byte.go](https://github.com/duke-git/lancet/blob/main/formatter/byte.go)
|
||||||
|
- [https://github.com/duke-git/lancet/blob/main/formatter/address.go](https://github.com/duke-git/lancet/blob/main/formatter/address.go)
|
||||||
|
|
||||||
<div STYLE="page-break-after: always;"></div>
|
<div STYLE="page-break-after: always;"></div>
|
||||||
|
|
||||||
@@ -30,6 +31,8 @@ import (
|
|||||||
- [BinaryBytes](#BinaryBytes)
|
- [BinaryBytes](#BinaryBytes)
|
||||||
- [ParseDecimalBytes](#ParseDecimalBytes)
|
- [ParseDecimalBytes](#ParseDecimalBytes)
|
||||||
- [ParseBinaryBytes](#ParseBinaryBytes)
|
- [ParseBinaryBytes](#ParseBinaryBytes)
|
||||||
|
- [ParseCNAddress](#ParseCNAddress)
|
||||||
|
- [ParsePersonInfo](#ParsePersonInfo)
|
||||||
|
|
||||||
<div STYLE="page-break-after: always;"></div>
|
<div STYLE="page-break-after: always;"></div>
|
||||||
|
|
||||||
@@ -308,3 +311,134 @@ func main() {
|
|||||||
// 12492
|
// 12492
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### <span id="ParseCNAddress">ParseCNAddress</span>
|
||||||
|
|
||||||
|
<p>智能解析中国地址字符串并提取结构化信息。可以解析带或不带用户信息(姓名、电话、身份证等)的地址。当 withUser 为 true 时,从地址字符串中提取用户信息。当 withUser 为 false 时,仅解析位置信息。支持多种地址格式:标准格式、紧凑格式、带关键词格式、县级市格式等。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func ParseCNAddress(str string, withUser bool) *AddressInfo
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/o5l09hQopEV)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/formatter"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// 解析包含用户信息的完整地址
|
||||||
|
result1 := formatter.ParseCNAddress("张三 13800138000 北京市朝阳区建国路1号", true)
|
||||||
|
jsonData1, _ := json.MarshalIndent(result1, "", " ")
|
||||||
|
fmt.Println("示例 1 - 带用户信息:")
|
||||||
|
fmt.Println(string(jsonData1))
|
||||||
|
|
||||||
|
// 仅解析地址,不提取用户信息
|
||||||
|
result2 := formatter.ParseCNAddress("北京市海淀区中关村大街1号", false)
|
||||||
|
fmt.Printf("\n示例 2 - 仅地址:\n")
|
||||||
|
fmt.Printf("省: %s, 市: %s, 区: %s, 街道: %s\n",
|
||||||
|
result2.Province, result2.City, result2.Region, result2.Street)
|
||||||
|
|
||||||
|
// 解析县级市地址
|
||||||
|
result3 := formatter.ParseCNAddress("河北省石家庄市新乐市经济开发区兴工街10号", false)
|
||||||
|
fmt.Printf("\n示例 3 - 县级市:\n")
|
||||||
|
fmt.Printf("省: %s, 市: %s, 区/县: %s, 街道: %s\n",
|
||||||
|
result3.Province, result3.City, result3.Region, result3.Street)
|
||||||
|
|
||||||
|
// 紧凑格式
|
||||||
|
result4 := formatter.ParseCNAddress("马云13593464918陕西省西安市雁塔区丈八沟街道", true)
|
||||||
|
fmt.Printf("\n示例 4 - 紧凑格式:\n")
|
||||||
|
fmt.Printf("姓名: %s, 电话: %s, 地址: %s%s%s%s\n",
|
||||||
|
result4.Name, result4.Mobile, result4.Province, result4.City, result4.Region, result4.Street)
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// 示例 1 - 带用户信息:
|
||||||
|
// {
|
||||||
|
// "name": "张三",
|
||||||
|
// "mobile": "13800138000",
|
||||||
|
// "idn": "",
|
||||||
|
// "postcode": "",
|
||||||
|
// "province": "北京",
|
||||||
|
// "city": "北京市",
|
||||||
|
// "region": "朝阳区",
|
||||||
|
// "street": "建国路1号",
|
||||||
|
// "addr": "北京市朝阳区建国路1号"
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// 示例 2 - 仅地址:
|
||||||
|
// 省: 北京, 市: 北京市, 区: 海淀区, 街道: 中关村大街1号
|
||||||
|
//
|
||||||
|
// 示例 3 - 县级市:
|
||||||
|
// 省: 河北省, 市: 石家庄市, 区/县: 新乐市, 街道: 经济开发区兴工街10号
|
||||||
|
//
|
||||||
|
// 示例 4 - 紧凑格式:
|
||||||
|
// 姓名: 马云, 电话: 13593464918, 地址: 陕西省西安市雁塔区丈八沟街道
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="ParsePersonInfo">ParsePersonInfo</span>
|
||||||
|
|
||||||
|
<p>从地址字符串中提取用户信息(姓名、电话、身份证、邮编)。将个人信息与地址分离,支持带标签格式、紧凑格式、带分隔符格式。返回包含提取的用户信息和清理后地址字符串的 AddressInfo。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func ParsePersonInfo(str string) *AddressInfo
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/JO-uTlJlTy7)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/formatter"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// 提取姓名和手机号
|
||||||
|
result1 := formatter.ParsePersonInfo("张三 13800138000 北京市朝阳区")
|
||||||
|
fmt.Println("示例 1 - 姓名和手机号:")
|
||||||
|
fmt.Printf("姓名: %s, 手机: %s, 地址: %s\n", result1.Name, result1.Mobile, result1.Addr)
|
||||||
|
|
||||||
|
// 提取身份证号
|
||||||
|
result2 := formatter.ParsePersonInfo("李四 110101199001011234 上海市")
|
||||||
|
fmt.Println("\n示例 2 - 身份证号:")
|
||||||
|
fmt.Printf("姓名: %s, 身份证: %s, 地址: %s\n", result2.Name, result2.IDN, result2.Addr)
|
||||||
|
|
||||||
|
// 带标签格式
|
||||||
|
result3 := formatter.ParsePersonInfo("收货人:王五 电话:13900139000 收货地址:天津市河西区友谊路20号")
|
||||||
|
jsonData3, _ := json.MarshalIndent(result3, "", " ")
|
||||||
|
fmt.Println("\n示例 3 - 带标签格式:")
|
||||||
|
fmt.Println(string(jsonData3))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// 示例 1 - 姓名和手机号:
|
||||||
|
// 姓名: 张三, 手机: 13800138000, 地址: 北京市朝阳区
|
||||||
|
//
|
||||||
|
// 示例 2 - 身份证号:
|
||||||
|
// 姓名: 李四, 身份证: 110101199001011234, 地址: 上海市
|
||||||
|
//
|
||||||
|
// 示例 3 - 带标签格式:
|
||||||
|
// {
|
||||||
|
// "name": "王五",
|
||||||
|
// "mobile": "13900139000",
|
||||||
|
// "idn": "",
|
||||||
|
// "postcode": "",
|
||||||
|
// "province": "",
|
||||||
|
// "city": "",
|
||||||
|
// "region": "",
|
||||||
|
// "street": "",
|
||||||
|
// "addr": "天津市河西区友谊路20号"
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -79,6 +79,7 @@ import (
|
|||||||
- [SortByKey](#SortByKey)
|
- [SortByKey](#SortByKey)
|
||||||
- [GetOrDefault](#GetOrDefault)
|
- [GetOrDefault](#GetOrDefault)
|
||||||
- [FindValuesBy](#FindValuesBy)
|
- [FindValuesBy](#FindValuesBy)
|
||||||
|
- [ToMarkdownTable](#ToMarkdownTable)
|
||||||
|
|
||||||
<div STYLE="page-break-after: always;"></div>
|
<div STYLE="page-break-after: always;"></div>
|
||||||
|
|
||||||
@@ -2345,3 +2346,68 @@ func main() {
|
|||||||
// [b d]
|
// [b d]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### <span id="ToMarkdownTable">ToMarkdownTable</span>
|
||||||
|
|
||||||
|
<p>将一个 map 切片数据转换为 Markdown 表格字符串。支持自定义表头显示名称和列的显示顺序。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
编辑
|
||||||
|
func ToMarkdownTable(data []map[string]interface{}, headerMap map[string]string, columnOrder []string) string
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/w_pSLfeyEB5)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/maputil"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// 基本用法:自动从数据中提取列名作为表头
|
||||||
|
data := []map[string]interface{}{
|
||||||
|
{"name": "Alice", "age": 25, "salary": 50000},
|
||||||
|
{"name": "Bob", "age": 30, "salary": 60000},
|
||||||
|
}
|
||||||
|
|
||||||
|
result := maputil.ToMarkdownTable(data, nil, nil)
|
||||||
|
fmt.Println(result)
|
||||||
|
|
||||||
|
// 输出:
|
||||||
|
// |name|age|salary|
|
||||||
|
// |---|---|---|
|
||||||
|
// |Alice|25|50000|
|
||||||
|
// |Bob|30|60000|
|
||||||
|
|
||||||
|
// 自定义表头显示名称
|
||||||
|
headerMap := map[string]string{
|
||||||
|
"name": "姓名",
|
||||||
|
"age": "年龄",
|
||||||
|
"salary": "薪资",
|
||||||
|
}
|
||||||
|
result = maputil.ToMarkdownTable(data, headerMap, nil)
|
||||||
|
fmt.Println(result)
|
||||||
|
|
||||||
|
// 输出:
|
||||||
|
// |姓名|年龄|薪资|
|
||||||
|
// |---|---|---|
|
||||||
|
// |Alice|25|50000|
|
||||||
|
// |Bob|30|60000|
|
||||||
|
|
||||||
|
// 自定义列顺序
|
||||||
|
columnOrder := []string{"salary", "name"}
|
||||||
|
result = maputil.ToMarkdownTable(data, nil, columnOrder)
|
||||||
|
fmt.Println(result)
|
||||||
|
|
||||||
|
// 输出:
|
||||||
|
// |salary|name|
|
||||||
|
// |---|---|
|
||||||
|
// |50000|Alice|
|
||||||
|
// |60000|Bob|
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -27,6 +27,7 @@ import (
|
|||||||
- [Contain](#Contain)
|
- [Contain](#Contain)
|
||||||
- [ContainBy](#ContainBy)
|
- [ContainBy](#ContainBy)
|
||||||
- [ContainSubSlice](#ContainSubSlice)
|
- [ContainSubSlice](#ContainSubSlice)
|
||||||
|
- [ContainAny](#ContainAny)
|
||||||
- [Chunk](#Chunk)
|
- [Chunk](#Chunk)
|
||||||
- [Compact](#Compact)
|
- [Compact](#Compact)
|
||||||
- [Concat](#Concat)
|
- [Concat](#Concat)
|
||||||
@@ -256,6 +257,43 @@ func main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### <span id="ContainAny">ContainAny</span>
|
||||||
|
|
||||||
|
<p>判断slice是否包含targets切片中的任意一个元素</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func ContainAny[T comparable](slice []T, targets []T) bool
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/4xoxhc9XSSw)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/slice"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
result1 := slice.ContainAny([]string{"a", "b", "c"}, []string{"a"})
|
||||||
|
result2 := slice.ContainAny([]string{"a", "b", "c"}, []string{"d", "e"})
|
||||||
|
result3 := slice.ContainAny([]string{"a", "b", "c"}, []string{"d", "a"})
|
||||||
|
result4 := slice.ContainAny([]string{"a", "b", "c"}, []string{})
|
||||||
|
|
||||||
|
fmt.Println(result1)
|
||||||
|
fmt.Println(result2)
|
||||||
|
fmt.Println(result3)
|
||||||
|
fmt.Println(result4)
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// true
|
||||||
|
// false
|
||||||
|
// true
|
||||||
|
// false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### <span id="Chunk">Chunk</span>
|
### <span id="Chunk">Chunk</span>
|
||||||
|
|
||||||
<p>按照size参数均分slice</p>
|
<p>按照size参数均分slice</p>
|
||||||
|
|||||||
+86
-43
@@ -31,6 +31,7 @@ import (
|
|||||||
- [IsStruct](#IsStruct)
|
- [IsStruct](#IsStruct)
|
||||||
- [Tag](#Tag)
|
- [Tag](#Tag)
|
||||||
- [Name](#Name)
|
- [Name](#Name)
|
||||||
|
- [TypeName](#TypeName)
|
||||||
- [Value](#Value)
|
- [Value](#Value)
|
||||||
- [Kind](#Kind)
|
- [Kind](#Kind)
|
||||||
- [IsEmbedded](#IsEmbedded)
|
- [IsEmbedded](#IsEmbedded)
|
||||||
@@ -53,7 +54,7 @@ import (
|
|||||||
func New(value any, tagName ...string) *Struct
|
func New(value any, tagName ...string) *Struct
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>示例:</b>
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/O29l8kk-Z17)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -68,7 +69,11 @@ func main() {
|
|||||||
}
|
}
|
||||||
p1 := &People{Name: "11"}
|
p1 := &People{Name: "11"}
|
||||||
s := structs.New(p1)
|
s := structs.New(p1)
|
||||||
// to do something
|
|
||||||
|
fmt.Println(s.ToMap())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// map[name:11] <nil>
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -88,7 +93,7 @@ func (s *Struct) ToMap() (map[string]any, error)
|
|||||||
func ToMap(v any) (map[string]any, error)
|
func ToMap(v any) (map[string]any, error)
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>示例:</b>
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/qQbLySBgerZ)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -129,7 +134,7 @@ func main() {
|
|||||||
func (s *Struct) Fields() []*Field
|
func (s *Struct) Fields() []*Field
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>示例:</b>
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/w3Kk_CyVY7D)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -161,10 +166,10 @@ func main() {
|
|||||||
<b>函数签名:</b>
|
<b>函数签名:</b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
func (s *Struct) Field(name string) *Field
|
func (s *Struct) Field(name string) (*Field, bool)
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>示例:</b>
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/KocZMSYarza)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -180,12 +185,14 @@ func main() {
|
|||||||
}
|
}
|
||||||
p1 := &People{Name: "11"}
|
p1 := &People{Name: "11"}
|
||||||
s := structs.New(p1)
|
s := structs.New(p1)
|
||||||
f := s.Field("Name")
|
f, found := s.Field("Name")
|
||||||
|
|
||||||
fmt.Println(f.Value())
|
fmt.Println(f.Value())
|
||||||
|
fmt.Println(found)
|
||||||
|
|
||||||
// Output:
|
// Output:
|
||||||
// 11
|
// 11
|
||||||
|
// true
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -199,7 +206,7 @@ func main() {
|
|||||||
func (s *Struct) IsStruct() bool
|
func (s *Struct) IsStruct() bool
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>示例:</b>
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/bU2FSdkbK1C)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -233,7 +240,7 @@ func main() {
|
|||||||
func (f *Field) Tag() *Tag
|
func (f *Field) Tag() *Tag
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>示例:</b>
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/DVrx5HvvUJr)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -254,7 +261,7 @@ func main() {
|
|||||||
tag := n.Tag()
|
tag := n.Tag()
|
||||||
|
|
||||||
fmt.Println(tag.Name)
|
fmt.Println(tag.Name)
|
||||||
|
|
||||||
// Output:
|
// Output:
|
||||||
// name
|
// name
|
||||||
}
|
}
|
||||||
@@ -270,7 +277,7 @@ func main() {
|
|||||||
func (f *Field) Value() any
|
func (f *Field) Value() any
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>示例:</b>
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/qufYEU2o4Oi)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -288,10 +295,10 @@ func main() {
|
|||||||
|
|
||||||
s := structs.New(p1)
|
s := structs.New(p1)
|
||||||
n, _ := s.Field("Name")
|
n, _ := s.Field("Name")
|
||||||
|
|
||||||
fmt.Println(n.Value())
|
fmt.Println(n.Value())
|
||||||
|
|
||||||
// Output:
|
// Output:
|
||||||
// 111
|
// 111
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -306,7 +313,7 @@ func main() {
|
|||||||
func (f *Field) IsEmbedded() bool
|
func (f *Field) IsEmbedded() bool
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>示例:</b>
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/wV2PrbYm3Ec)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -331,11 +338,11 @@ func main() {
|
|||||||
s := structs.New(c1)
|
s := structs.New(c1)
|
||||||
n, _ := s.Field("Name")
|
n, _ := s.Field("Name")
|
||||||
a, _ := s.Field("Age")
|
a, _ := s.Field("Age")
|
||||||
|
|
||||||
fmt.Println(n.IsEmbedded())
|
fmt.Println(n.IsEmbedded())
|
||||||
fmt.Println(a.IsEmbedded())
|
fmt.Println(a.IsEmbedded())
|
||||||
|
|
||||||
// Output:
|
// Output:
|
||||||
// true
|
// true
|
||||||
// false
|
// false
|
||||||
}
|
}
|
||||||
@@ -351,7 +358,7 @@ func main() {
|
|||||||
func (f *Field) IsExported() bool
|
func (f *Field) IsExported() bool
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>示例:</b>
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/csK4AXYaNbJ)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -370,11 +377,11 @@ func main() {
|
|||||||
s := structs.New(p1)
|
s := structs.New(p1)
|
||||||
n, _ := s.Field("Name")
|
n, _ := s.Field("Name")
|
||||||
a, _ := s.Field("age")
|
a, _ := s.Field("age")
|
||||||
|
|
||||||
fmt.Println(n.IsExported())
|
fmt.Println(n.IsExported())
|
||||||
fmt.Println(a.IsExported())
|
fmt.Println(a.IsExported())
|
||||||
|
|
||||||
// Output:
|
// Output:
|
||||||
// true
|
// true
|
||||||
// false
|
// false
|
||||||
}
|
}
|
||||||
@@ -390,7 +397,7 @@ func main() {
|
|||||||
func (f *Field) IsZero() bool
|
func (f *Field) IsZero() bool
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>示例:</b>
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/RzqpGISf87r)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -409,11 +416,11 @@ func main() {
|
|||||||
s := structs.New(p1)
|
s := structs.New(p1)
|
||||||
n, _ := s.Field("Name")
|
n, _ := s.Field("Name")
|
||||||
a, _ := s.Field("Age")
|
a, _ := s.Field("Age")
|
||||||
|
|
||||||
fmt.Println(n.IsZero())
|
fmt.Println(n.IsZero())
|
||||||
fmt.Println(a.IsZero())
|
fmt.Println(a.IsZero())
|
||||||
|
|
||||||
// Output:
|
// Output:
|
||||||
// true
|
// true
|
||||||
// false
|
// false
|
||||||
}
|
}
|
||||||
@@ -429,7 +436,7 @@ func main() {
|
|||||||
func (f *Field) Name() string
|
func (f *Field) Name() string
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>示例:</b>
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/zfIGlqsatee)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -448,11 +455,11 @@ func main() {
|
|||||||
s := structs.New(p1)
|
s := structs.New(p1)
|
||||||
n, _ := s.Field("Name")
|
n, _ := s.Field("Name")
|
||||||
a, _ := s.Field("Age")
|
a, _ := s.Field("Age")
|
||||||
|
|
||||||
fmt.Println(n.Name())
|
fmt.Println(n.Name())
|
||||||
fmt.Println(a.Name())
|
fmt.Println(a.Name())
|
||||||
|
|
||||||
// Output:
|
// Output:
|
||||||
// Name
|
// Name
|
||||||
// Age
|
// Age
|
||||||
}
|
}
|
||||||
@@ -468,7 +475,7 @@ func main() {
|
|||||||
func (f *Field) Kind() reflect.Kind
|
func (f *Field) Kind() reflect.Kind
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>示例:</b>
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/wg4NlcUNG5o)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -487,16 +494,52 @@ func main() {
|
|||||||
s := structs.New(p1)
|
s := structs.New(p1)
|
||||||
n, _ := s.Field("Name")
|
n, _ := s.Field("Name")
|
||||||
a, _ := s.Field("Age")
|
a, _ := s.Field("Age")
|
||||||
|
|
||||||
fmt.Println(n.Kind())
|
fmt.Println(n.Kind())
|
||||||
fmt.Println(a.Kind())
|
fmt.Println(a.Kind())
|
||||||
|
|
||||||
// Output:
|
// Output:
|
||||||
// string
|
// string
|
||||||
// int
|
// int
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### <span id="TypeName">TypeName</span>
|
||||||
|
|
||||||
|
<p>获取结构体类型名。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (s *Struct) TypeName() string
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/SWLWd0XBaBb)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/structs"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
type Parent struct {
|
||||||
|
Name string
|
||||||
|
Age int
|
||||||
|
}
|
||||||
|
|
||||||
|
p := &Parent{Age: 11}
|
||||||
|
s := structs.New(p)
|
||||||
|
|
||||||
|
fmt.Println(s.TypeName())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Parent
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### <span id="IsSlice">IsSlice</span>
|
### <span id="IsSlice">IsSlice</span>
|
||||||
|
|
||||||
<p>判断属性是否是切片</p>
|
<p>判断属性是否是切片</p>
|
||||||
@@ -507,7 +550,7 @@ func main() {
|
|||||||
func (f *Field) IsSlice() bool
|
func (f *Field) IsSlice() bool
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>示例:</b>
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/MKz4CgBIUrU)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -526,10 +569,10 @@ func main() {
|
|||||||
p1 := &Parent{arr: []int{1, 2, 3}}
|
p1 := &Parent{arr: []int{1, 2, 3}}
|
||||||
s := structs.New(p1)
|
s := structs.New(p1)
|
||||||
a, _ := s.Field("arr")
|
a, _ := s.Field("arr")
|
||||||
|
|
||||||
fmt.Println(a.IsSlice())
|
fmt.Println(a.IsSlice())
|
||||||
|
|
||||||
// Output:
|
// Output:
|
||||||
// true
|
// true
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -544,7 +587,7 @@ func main() {
|
|||||||
func (f *Field) IsTargetType(targetType reflect.Kind) bool
|
func (f *Field) IsTargetType(targetType reflect.Kind) bool
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>示例:</b>
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/Ig75P-agN39)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -565,12 +608,12 @@ func main() {
|
|||||||
s := structs.New(p1)
|
s := structs.New(p1)
|
||||||
n, _ := s.Field("Name")
|
n, _ := s.Field("Name")
|
||||||
a, _ := s.Field("arr")
|
a, _ := s.Field("arr")
|
||||||
|
|
||||||
fmt.Println(n.IsTargetType(reflect.String))
|
fmt.Println(n.IsTargetType(reflect.String))
|
||||||
fmt.Println(a.IsTargetType(reflect.Slice))
|
fmt.Println(a.IsTargetType(reflect.Slice))
|
||||||
|
|
||||||
// Output:
|
// Output:
|
||||||
// true
|
// true
|
||||||
// true
|
// true
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -27,6 +27,7 @@ import (
|
|||||||
- [Before](#Before)
|
- [Before](#Before)
|
||||||
- [BeforeLast](#BeforeLast)
|
- [BeforeLast](#BeforeLast)
|
||||||
- [CamelCase](#CamelCase)
|
- [CamelCase](#CamelCase)
|
||||||
|
- [UpperCamelCase](#UpperCamelCase)
|
||||||
- [Capitalize](#Capitalize)
|
- [Capitalize](#Capitalize)
|
||||||
- [IsString](#IsString)
|
- [IsString](#IsString)
|
||||||
- [KebabCase](#KebabCase)
|
- [KebabCase](#KebabCase)
|
||||||
@@ -232,7 +233,7 @@ func main() {
|
|||||||
|
|
||||||
### <span id="CamelCase">CamelCase</span>
|
### <span id="CamelCase">CamelCase</span>
|
||||||
|
|
||||||
<p>将字符串转换为驼峰式字符串, 非字母和数字会被忽略。</p>
|
<p>将字符串转换为驼峰式字符串,首字母小写, 非字母和数字会被忽略。</p>
|
||||||
|
|
||||||
<b>函数签名:</b>
|
<b>函数签名:</b>
|
||||||
|
|
||||||
@@ -265,6 +266,40 @@ func main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### <span id="UpperCamelCase">UpperCamelCase</span>
|
||||||
|
|
||||||
|
<p>将字符串转换为大写驼峰式字符串,首字母大写写, 非字母和数字会被忽略。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func UpperCamelCase(s string) string
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/65Q6iYhLRTa)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/strutil"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
strings := []string{"", "foobar", "&FOO:BAR$BAZ", "$foo%", "Foo-#1😄$_%^&*(1bar"}
|
||||||
|
|
||||||
|
for _, v := range strings {
|
||||||
|
s := strutil.UpperCamelCase(v)
|
||||||
|
fmt.Println(s)
|
||||||
|
}
|
||||||
|
// Output:
|
||||||
|
//
|
||||||
|
// Foobar
|
||||||
|
// FooBarBaz
|
||||||
|
// Foo
|
||||||
|
// Foo11Bar
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### <span id="KebabCase">KebabCase</span>
|
### <span id="KebabCase">KebabCase</span>
|
||||||
|
|
||||||
<p>将字符串转换为kebab-case, 非字母和数字会被忽略。</p>
|
<p>将字符串转换为kebab-case, 非字母和数字会被忽略。</p>
|
||||||
|
|||||||
+112
-14
@@ -65,6 +65,8 @@ import (
|
|||||||
- [IsAmericanExpress](#IsAmericanExpress)
|
- [IsAmericanExpress](#IsAmericanExpress)
|
||||||
- [IsUnionPay](#IsUnionPay)
|
- [IsUnionPay](#IsUnionPay)
|
||||||
- [IsChinaUnionPay](#IsChinaUnionPay)
|
- [IsChinaUnionPay](#IsChinaUnionPay)
|
||||||
|
- [IsPassport](#IsPassport)
|
||||||
|
- [IsChineseHMPassport](#IsChineseHMPassport)
|
||||||
|
|
||||||
<div STYLE="page-break-after: always;"></div>
|
<div STYLE="page-break-after: always;"></div>
|
||||||
|
|
||||||
@@ -547,7 +549,7 @@ func main() {
|
|||||||
func IsEmail(email string) bool
|
func IsEmail(email string) bool
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>示例:<span style="float:right;display:inline-block">[运行](https://go.dev/play/p/Os9VaFlT33G)</span></b>
|
<b>示例:<span style="float:right;display:inline-block">[运行](https://go.dev/play/p/HVQ5LAe-vFz)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import (
|
import (
|
||||||
@@ -557,13 +559,28 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
result1 := validator.IsEmail("abc@xyz.com")
|
result1 := validator.IsEmail("abc@xyz.com")
|
||||||
result2 := validator.IsEmail("a.b@@com")
|
result2 := validator.IsEmail("user@domain.co")
|
||||||
|
result3 := validator.IsEmail("test.user@example.org")
|
||||||
|
result4 := validator.IsEmail("@abc@xyz.com")
|
||||||
|
result5 := validator.IsEmail("a.b@@com")
|
||||||
|
result6 := validator.IsEmail("a.b@com")
|
||||||
|
result7 := validator.IsEmail("test@example")
|
||||||
|
|
||||||
fmt.Println(result1)
|
fmt.Println(result1)
|
||||||
fmt.Println(result2)
|
fmt.Println(result2)
|
||||||
|
fmt.Println(result3)
|
||||||
|
fmt.Println(result4)
|
||||||
|
fmt.Println(result5)
|
||||||
|
fmt.Println(result6)
|
||||||
|
fmt.Println(result7)
|
||||||
|
|
||||||
// Output:
|
// Output:
|
||||||
// true
|
// true
|
||||||
|
// true
|
||||||
|
// true
|
||||||
|
// false
|
||||||
|
// false
|
||||||
|
// false
|
||||||
// false
|
// false
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -844,20 +861,20 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
result1 := validator.IsAlphaNumeric("ABC")
|
result1 := validator.IsAlphaNumeric("ABC")
|
||||||
result2 := validator.IsAlphaNumeric("123")
|
result2 := validator.IsAlphaNumeric("123")
|
||||||
result3 := validator.IsAlphaNumeric("abc123")
|
result3 := validator.IsAlphaNumeric("abc123")
|
||||||
result4 := validator.IsAlphaNumeric("abc123@#$")
|
result4 := validator.IsAlphaNumeric("abc123@#$")
|
||||||
|
|
||||||
fmt.Println(result1)
|
fmt.Println(result1)
|
||||||
fmt.Println(result2)
|
fmt.Println(result2)
|
||||||
fmt.Println(result3)
|
fmt.Println(result3)
|
||||||
fmt.Println(result4)
|
fmt.Println(result4)
|
||||||
|
|
||||||
// Output:
|
// Output:
|
||||||
// true
|
// true
|
||||||
// true
|
// true
|
||||||
// true
|
// true
|
||||||
// false
|
// false
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -1550,6 +1567,8 @@ func IsChinaUnionPay(v string) bool
|
|||||||
<b>示例:<span style="float:right;display:inline-block">[运行](https://go.dev/play/p/yafpdxLiymu)</span></b>
|
<b>示例:<span style="float:right;display:inline-block">[运行](https://go.dev/play/p/yafpdxLiymu)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/duke-git/lancet/v2/validator"
|
"github.com/duke-git/lancet/v2/validator"
|
||||||
@@ -1567,3 +1586,82 @@ func main() {
|
|||||||
// false
|
// false
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### <span id="IsPassport">IsPassport</span>
|
||||||
|
|
||||||
|
<p>判断护照(正则判断)。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func IsPassport(passport, country string) bool
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block">[运行](https://go.dev/play/p/dvOiV2BW7Aw)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/validator"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
result1 := validator.IsPassport("P123456789", "CN")
|
||||||
|
result2 := validator.IsPassport("123456789", "US")
|
||||||
|
result3 := validator.IsPassport("AB1234567", "RU")
|
||||||
|
result4 := validator.IsPassport("123456789", "CN")
|
||||||
|
|
||||||
|
fmt.Println(result1)
|
||||||
|
fmt.Println(result2)
|
||||||
|
fmt.Println(result3)
|
||||||
|
fmt.Println(result4)
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// true
|
||||||
|
// true
|
||||||
|
// true
|
||||||
|
// false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="IsChineseHMPassport">IsChineseHMPassport</span>
|
||||||
|
|
||||||
|
<p>判断港澳台通行证(正则判断)。</p>
|
||||||
|
|
||||||
|
<b>函数签名:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func IsChineseHMPassport(hmPassport string) bool
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>示例:<span style="float:right;display:inline-block">[运行](https://go.dev/play/p/xKG6spQTcY0)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/validator"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
result1 := validator.IsChineseHMPassport("C12345678")
|
||||||
|
result2 := validator.IsChineseHMPassport("C00000000")
|
||||||
|
result3 := validator.IsChineseHMPassport("M12345678")
|
||||||
|
result4 := validator.IsChineseHMPassport("c12345678")
|
||||||
|
result5 := validator.IsChineseHMPassport("C1234567")
|
||||||
|
|
||||||
|
fmt.Println(result1)
|
||||||
|
fmt.Println(result2)
|
||||||
|
fmt.Println(result3)
|
||||||
|
fmt.Println(result4)
|
||||||
|
fmt.Println(result5)
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// true
|
||||||
|
// true
|
||||||
|
// true
|
||||||
|
// false
|
||||||
|
// false
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -46,6 +46,7 @@ outline: deep
|
|||||||
<div class="package-cell">cryptor</div>
|
<div class="package-cell">cryptor</div>
|
||||||
<div class="package-cell">datastructure</div>
|
<div class="package-cell">datastructure</div>
|
||||||
<div class="package-cell">datetime</div>
|
<div class="package-cell">datetime</div>
|
||||||
|
<div class="package-cell">enum</div>
|
||||||
<div class="package-cell">eventbus</div>
|
<div class="package-cell">eventbus</div>
|
||||||
<div class="package-cell">fileutil</div>
|
<div class="package-cell">fileutil</div>
|
||||||
<div class="package-cell">formatter</div>
|
<div class="package-cell">formatter</div>
|
||||||
|
|||||||
@@ -33,6 +33,9 @@ import (
|
|||||||
- [ToJson](#ToJson)
|
- [ToJson](#ToJson)
|
||||||
- [ToMap](#ToMap)
|
- [ToMap](#ToMap)
|
||||||
- [ToPointer](#ToPointer)
|
- [ToPointer](#ToPointer)
|
||||||
|
- [ToPointers](#ToPointers)
|
||||||
|
- [FromPointer](#FromPointer)
|
||||||
|
- [FromPointers](#FromPointers)
|
||||||
- [ToString](#ToString)
|
- [ToString](#ToString)
|
||||||
- [StructToMap](#StructToMap)
|
- [StructToMap](#StructToMap)
|
||||||
- [MapToSlice](#MapToSlice)
|
- [MapToSlice](#MapToSlice)
|
||||||
@@ -456,6 +459,108 @@ func main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### <span id="ToPointers">ToPointers</span>
|
||||||
|
|
||||||
|
<p>Convert a slice of values to a slice of pointers.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func ToPointers[T any](values []T) []*T
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/ZUoXd2i5ZkV)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/convertor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
strs := []string{"a", "b", "c"}
|
||||||
|
pointerStrs := convertor.ToPointers(strs)
|
||||||
|
fmt.Println(*pointerStrs[0])
|
||||||
|
fmt.Println(*pointerStrs[1])
|
||||||
|
fmt.Println(*pointerStrs[2])
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// a
|
||||||
|
// b
|
||||||
|
// c
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="FromPointer">FromPointer</span>
|
||||||
|
|
||||||
|
<p>Returns the value pointed to by the pointer.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func FromPointer[T any](ptr *T) T
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/wAp90V7Zu6g)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/convertor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
str := "abc"
|
||||||
|
strPtr := &str
|
||||||
|
result := convertor.FromPointer(strPtr)
|
||||||
|
fmt.Println(result)
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// abc
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="FromPointers">FromPointers</span>
|
||||||
|
|
||||||
|
<p>Convert a slice of pointers to a slice of values.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func FromPointers[T any](pointers []*T) []T
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/qIPsyYtNy3Q)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/convertor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
strs := []string{"a", "b", "c"}
|
||||||
|
strPtr := []*string{&strs[0], &strs[1], &strs[2]}
|
||||||
|
|
||||||
|
result := convertor.FromPointers(strPtr)
|
||||||
|
|
||||||
|
fmt.Println(result[0])
|
||||||
|
fmt.Println(result[1])
|
||||||
|
fmt.Println(result[2])
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// a
|
||||||
|
// b
|
||||||
|
// c
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### <span id="ToString">ToString</span>
|
### <span id="ToString">ToString</span>
|
||||||
|
|
||||||
<p>ToString convert value to string, for number, string, []byte, will convert to string. For other type (slice, map, array, struct) will call json.Marshal</p>
|
<p>ToString convert value to string, for number, string, []byte, will convert to string. For other type (slice, map, array, struct) will call json.Marshal</p>
|
||||||
@@ -572,7 +677,6 @@ func main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
### <span id="EncodeByte">EncodeByte</span>
|
### <span id="EncodeByte">EncodeByte</span>
|
||||||
|
|
||||||
<p>Encode data to byte slice.</p>
|
<p>Encode data to byte slice.</p>
|
||||||
@@ -638,7 +742,6 @@ func main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
### <span id="CopyProperties">CopyProperties</span>
|
### <span id="CopyProperties">CopyProperties</span>
|
||||||
|
|
||||||
<p>Copies each field from the source struct into the destination struct. Use json.Marshal/Unmarshal, so json tag should be set for fields of dst and src struct.</p>
|
<p>Copies each field from the source struct into the destination struct. Use json.Marshal/Unmarshal, so json tag should be set for fields of dst and src struct.</p>
|
||||||
@@ -748,7 +851,7 @@ func main() {
|
|||||||
|
|
||||||
// Output:
|
// Output:
|
||||||
// true
|
// true
|
||||||
// true
|
// true
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -781,7 +884,7 @@ func main() {
|
|||||||
|
|
||||||
// Output:
|
// Output:
|
||||||
// true
|
// true
|
||||||
// hello
|
// hello
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -857,8 +960,6 @@ func main() {
|
|||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
### <span id="ToUrlBase64">ToUrlBase64</span>
|
### <span id="ToUrlBase64">ToUrlBase64</span>
|
||||||
|
|
||||||
<p>Convert a value to a string encoded in url Base64. Error data of type "error" will also be encoded, and complex structures will be converted to a JSON formatted string.</p>
|
<p>Convert a value to a string encoded in url Base64. Error data of type "error" will also be encoded, and complex structures will be converted to a JSON formatted string.</p>
|
||||||
@@ -1147,4 +1248,4 @@ func main() {
|
|||||||
// Output:
|
// Output:
|
||||||
// 9876543210
|
// 9876543210
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
# Cryptor
|
# Cryptor
|
||||||
|
|
||||||
Package cryptor contains some functions for data encryption and decryption. Support base64, md5, hmac, aes, des, rsa.
|
Package cryptor contains some functions for data encryption and decryption. Support base64, md5, hmac, aes, des, rsa, sm2, sm3, sm4.
|
||||||
|
|
||||||
<div STYLE="page-break-after: always;"></div>
|
<div STYLE="page-break-after: always;"></div>
|
||||||
|
|
||||||
@@ -76,6 +76,14 @@ import (
|
|||||||
- [RsaDecryptOAEP](#RsaDecryptOAEP)
|
- [RsaDecryptOAEP](#RsaDecryptOAEP)
|
||||||
- [RsaSign](#RsaSign)
|
- [RsaSign](#RsaSign)
|
||||||
- [RsaVerifySign](#RsaVerifySign)
|
- [RsaVerifySign](#RsaVerifySign)
|
||||||
|
- [Sm3](#Sm3)
|
||||||
|
- [Sm4EcbEncrypt](#Sm4EcbEncrypt)
|
||||||
|
- [Sm4EcbDecrypt](#Sm4EcbDecrypt)
|
||||||
|
- [Sm4CbcEncrypt](#Sm4CbcEncrypt)
|
||||||
|
- [Sm4CbcDecrypt](#Sm4CbcDecrypt)
|
||||||
|
- [GenerateSm2Key](#GenerateSm2Key)
|
||||||
|
- [Sm2Encrypt](#Sm2Encrypt)
|
||||||
|
- [Sm2Decrypt](#Sm2Decrypt)
|
||||||
|
|
||||||
<div STYLE="page-break-after: always;"></div>
|
<div STYLE="page-break-after: always;"></div>
|
||||||
|
|
||||||
@@ -1831,3 +1839,278 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### <span id="Sm3">Sm3</span>
|
||||||
|
|
||||||
|
<p>Calculate SM3 hash (Chinese National Cryptography SM3 Hash Algorithm). SM3 is a cryptographic hash algorithm published by the Chinese State Cryptography Administration, designed to replace MD5/SHA-1/SHA-2.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func Sm3(data []byte) []byte
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/zDAQpteAiOc)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/cryptor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
data := []byte("hello world")
|
||||||
|
hash := cryptor.Sm3(data)
|
||||||
|
|
||||||
|
fmt.Println(hex.EncodeToString(hash))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// 44f0061e69fa6fdfc290c494654a05dc0c053da7e5c52b84ef93a9d67d3fff88
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Sm4EcbEncrypt">Sm4EcbEncrypt</span>
|
||||||
|
|
||||||
|
<p>Encrypt data using SM4 ECB mode (Chinese National Cryptography SM4 Block Cipher Algorithm). Key length must be 16 bytes.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func Sm4EcbEncrypt(data, key []byte) []byte
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/l5IQxYuuaED)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/cryptor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
key := []byte("1234567890abcdef") // 16 bytes key
|
||||||
|
plaintext := []byte("hello world")
|
||||||
|
|
||||||
|
encrypted := cryptor.Sm4EcbEncrypt(plaintext, key)
|
||||||
|
decrypted := cryptor.Sm4EcbDecrypt(encrypted, key)
|
||||||
|
|
||||||
|
fmt.Println(string(decrypted))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// hello world
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Sm4EcbDecrypt">Sm4EcbDecrypt</span>
|
||||||
|
|
||||||
|
<p>Decrypt data using SM4 ECB mode. Key length must be 16 bytes.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func Sm4EcbDecrypt(encrypted, key []byte) []byte
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/l5IQxYuuaED)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/cryptor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
key := []byte("1234567890abcdef")
|
||||||
|
plaintext := []byte("hello world")
|
||||||
|
|
||||||
|
encrypted := cryptor.Sm4EcbEncrypt(plaintext, key)
|
||||||
|
decrypted := cryptor.Sm4EcbDecrypt(encrypted, key)
|
||||||
|
|
||||||
|
fmt.Println(string(decrypted))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// hello world
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Sm4CbcEncrypt">Sm4CbcEncrypt</span>
|
||||||
|
|
||||||
|
<p>Encrypt data using SM4 CBC mode. Key length must be 16 bytes. The returned ciphertext contains IV (first 16 bytes).</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func Sm4CbcEncrypt(data, key []byte) []byte
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/65Q6iYhLRTa)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/cryptor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
key := []byte("1234567890abcdef")
|
||||||
|
plaintext := []byte("hello world")
|
||||||
|
|
||||||
|
encrypted := cryptor.Sm4CbcEncrypt(plaintext, key)
|
||||||
|
decrypted := cryptor.Sm4CbcDecrypt(encrypted, key)
|
||||||
|
|
||||||
|
fmt.Println(string(decrypted))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// hello world
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Sm4CbcDecrypt">Sm4CbcDecrypt</span>
|
||||||
|
|
||||||
|
<p>Decrypt data using SM4 CBC mode. Key length must be 16 bytes. The ciphertext should contain IV (first 16 bytes).</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func Sm4CbcDecrypt(encrypted, key []byte) []byte
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/65Q6iYhLRTa)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/cryptor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
key := []byte("1234567890abcdef")
|
||||||
|
plaintext := []byte("hello world")
|
||||||
|
|
||||||
|
encrypted := cryptor.Sm4CbcEncrypt(plaintext, key)
|
||||||
|
decrypted := cryptor.Sm4CbcDecrypt(encrypted, key)
|
||||||
|
|
||||||
|
fmt.Println(string(decrypted))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// hello world
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="GenerateSm2Key">GenerateSm2Key</span>
|
||||||
|
|
||||||
|
<p>Generate SM2 key pair (Chinese National Cryptography SM2 Elliptic Curve Public Key Algorithm). SM2 is an asymmetric encryption algorithm based on elliptic curve cryptography.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func GenerateSm2Key() (*Sm2PrivateKey, error)
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/bKYMqRLvIx3)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/cryptor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
privateKey, err := cryptor.GenerateSm2Key()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
plaintext := []byte("hello world")
|
||||||
|
|
||||||
|
ciphertext, _ := cryptor.Sm2Encrypt(&privateKey.PublicKey, plaintext)
|
||||||
|
decrypted, _ := cryptor.Sm2Decrypt(privateKey, ciphertext)
|
||||||
|
|
||||||
|
fmt.Println(string(decrypted))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// hello world
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Sm2Encrypt">Sm2Encrypt</span>
|
||||||
|
|
||||||
|
<p>Encrypt data using SM2 public key. The returned ciphertext format is: C1(65 bytes) || C3(32 bytes) || C2(plaintext length).</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func Sm2Encrypt(pub *Sm2PublicKey, plaintext []byte) ([]byte, error)
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/bKYMqRLvIx3)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/cryptor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
privateKey, _ := cryptor.GenerateSm2Key()
|
||||||
|
plaintext := []byte("hello world")
|
||||||
|
|
||||||
|
ciphertext, _ := cryptor.Sm2Encrypt(&privateKey.PublicKey, plaintext)
|
||||||
|
decrypted, _ := cryptor.Sm2Decrypt(privateKey, ciphertext)
|
||||||
|
|
||||||
|
fmt.Println(string(decrypted))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// hello world
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Sm2Decrypt">Sm2Decrypt</span>
|
||||||
|
|
||||||
|
<p>Decrypt data using SM2 private key. The ciphertext format should be: C1(65 bytes) || C3(32 bytes) || C2(plaintext length).</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func Sm2Decrypt(priv *Sm2PrivateKey, ciphertext []byte) ([]byte, error)
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/bKYMqRLvIx3)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/cryptor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
privateKey, _ := cryptor.GenerateSm2Key()
|
||||||
|
plaintext := []byte("hello world")
|
||||||
|
|
||||||
|
ciphertext, _ := cryptor.Sm2Encrypt(&privateKey.PublicKey, plaintext)
|
||||||
|
decrypted, _ := cryptor.Sm2Decrypt(privateKey, ciphertext)
|
||||||
|
|
||||||
|
fmt.Println(string(decrypted))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// hello world
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -0,0 +1,850 @@
|
|||||||
|
# Enum
|
||||||
|
|
||||||
|
Package enum provides a simple enum implementation.
|
||||||
|
|
||||||
|
<div STYLE="page-break-after: always;"></div>
|
||||||
|
|
||||||
|
## Source:
|
||||||
|
|
||||||
|
- [https://github.com/duke-git/lancet/blob/main/enum/enum.go](https://github.com/duke-git/lancet/blob/main/enum/enum.go)
|
||||||
|
|
||||||
|
<div STYLE="page-break-after: always;"></div>
|
||||||
|
|
||||||
|
## Usage:
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
<div STYLE="page-break-after: always;"></div>
|
||||||
|
|
||||||
|
## Index
|
||||||
|
|
||||||
|
- [NewItem](#NewItem)
|
||||||
|
- [NewItemsFromPairs](#NewItemsFromPairs)
|
||||||
|
- [Value](#Value)
|
||||||
|
- [Name](#Name)
|
||||||
|
- [Valid](#Valid)
|
||||||
|
- [MarshalJSON](#MarshalJSON)
|
||||||
|
- [NewRegistry](#NewRegistry)
|
||||||
|
- [Add](#Add)
|
||||||
|
- [Remove](#Remove)
|
||||||
|
- [Update](#Update)
|
||||||
|
- [GetByValue](#GetByValue)
|
||||||
|
- [GetByName](#GetByName)
|
||||||
|
- [Items](#Items)
|
||||||
|
- [Contains](#Contains)
|
||||||
|
- [Size](#Size)
|
||||||
|
- [Range](#Range)
|
||||||
|
- [SortedItems](#SortedItems)
|
||||||
|
- [Filter](#Filter)
|
||||||
|
|
||||||
|
<div STYLE="page-break-after: always;"></div>
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
### <span id="NewItem">NewItem</span>
|
||||||
|
|
||||||
|
<p>Creates a new enum item.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func NewItem[T comparable](value T, name string) *Item[T]
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/8qNsLw01HD5)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
item1 := enum.NewItem(Active, "Active")
|
||||||
|
item2 := enum.NewItem(Inactive, "Inactive")
|
||||||
|
|
||||||
|
fmt.Println(item1.Name(), item1.Value())
|
||||||
|
fmt.Println(item2.Name(), item2.Value())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Active 1
|
||||||
|
// Inactive 2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="NewItemsFromPairs">NewItemsFromPairs</span>
|
||||||
|
|
||||||
|
<p>Creates enum items from a slice of Pair structs.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func NewItemsFromPairs[T comparable](pairs ...Pair[T]) []*Item[T]
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/xKnoGa7gnev)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
items := enum.NewItemsFromPairs(
|
||||||
|
enum.Pair[Status]{Value: Active, Name: "Active"},
|
||||||
|
enum.Pair[Status]{Value: Inactive, Name: "Inactive"},
|
||||||
|
)
|
||||||
|
|
||||||
|
fmt.Println(items[0].Name(), items[0].Value())
|
||||||
|
fmt.Println(items[1].Name(), items[1].Value())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Active 1
|
||||||
|
// Inactive 2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Value">Value</span>
|
||||||
|
|
||||||
|
<p>Returns the value of the enum item.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (it *Item[T]) Value() T
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/xKnoGa7gnev)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
items := enum.NewItemsFromPairs(
|
||||||
|
enum.Pair[Status]{Value: Active, Name: "Active"},
|
||||||
|
enum.Pair[Status]{Value: Inactive, Name: "Inactive"},
|
||||||
|
)
|
||||||
|
|
||||||
|
fmt.Println(items[0].Name(), items[0].Value())
|
||||||
|
fmt.Println(items[1].Name(), items[1].Value())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Active 1
|
||||||
|
// Inactive 2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Name">Name</span>
|
||||||
|
|
||||||
|
<p>Returns the name of the enum item.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (it *Item[T]) Name() string
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/xKnoGa7gnev)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
items := enum.NewItemsFromPairs(
|
||||||
|
enum.Pair[Status]{Value: Active, Name: "Active"},
|
||||||
|
enum.Pair[Status]{Value: Inactive, Name: "Inactive"},
|
||||||
|
)
|
||||||
|
|
||||||
|
fmt.Println(items[0].Name(), items[0].Value())
|
||||||
|
fmt.Println(items[1].Name(), items[1].Value())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Active 1
|
||||||
|
// Inactive 2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Valid">Valid</span>
|
||||||
|
|
||||||
|
<p>Checks if the enum item is valid. If a custom check function is provided, it will be used to validate the value.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (it *Item[T]) Valid(checker ...func(T) bool) bool
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/pA3lYY2VSm3)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
item := enum.NewItem(Active, "Active")
|
||||||
|
fmt.Println(item.Valid())
|
||||||
|
|
||||||
|
invalidItem := enum.NewItem(Unknown, "")
|
||||||
|
fmt.Println(invalidItem.Valid())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// true
|
||||||
|
// false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="MarshalJSON">MarshalJSON</span>
|
||||||
|
|
||||||
|
<p>Implementation of json.Marshaler interface.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (it *Item[T]) MarshalJSON() ([]byte, error)
|
||||||
|
func (it *Item[T]) UnmarshalJSON(data []byte) error
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/zIZEdAnneB5)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
item := enum.NewItem(Active, "Active")
|
||||||
|
data, _ := item.MarshalJSON()
|
||||||
|
fmt.Println(string(data))
|
||||||
|
|
||||||
|
var unmarshaledItem enum.Item[Status]
|
||||||
|
_ = unmarshaledItem.UnmarshalJSON(data)
|
||||||
|
fmt.Println(unmarshaledItem.Name(), unmarshaledItem.Value())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// {"name":"Active","value":1}
|
||||||
|
// Active 1
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="NewRegistry">NewRegistry</span>
|
||||||
|
|
||||||
|
<p>Creates a new enum registry.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func NewRegistry[T comparable](items ...*Item[T]) *Registry[T]
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/ABEXsYfJKMo)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
item1 := enum.NewItem(Active, "Active")
|
||||||
|
item2 := enum.NewItem(Inactive, "Inactive")
|
||||||
|
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
if item, found := registry.GetByValue(Active); found {
|
||||||
|
fmt.Println("Found by value:", item.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
if item, found := registry.GetByName("Inactive"); found {
|
||||||
|
fmt.Println("Found by name:", item.Value())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Found by value: Active
|
||||||
|
// Found by name: 2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Add">Add</span>
|
||||||
|
|
||||||
|
<p>Adds enum items to the registry.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (r *Registry[T]) Add(items ...*Item[T])
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/ABEXsYfJKMo)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
item1 := enum.NewItem(Active, "Active")
|
||||||
|
item2 := enum.NewItem(Inactive, "Inactive")
|
||||||
|
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
if item, found := registry.GetByValue(Active); found {
|
||||||
|
fmt.Println("Found by value:", item.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
if item, found := registry.GetByName("Inactive"); found {
|
||||||
|
fmt.Println("Found by name:", item.Value())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Found by value: Active
|
||||||
|
// Found by name: 2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Remove">Remove</span>
|
||||||
|
|
||||||
|
<p>Removes an enum item from the registry by its value.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (r *Registry[T]) Remove(value T) bool
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/dSG84wQ3TuC)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
item1 := enum.NewItem(Active, "Active")
|
||||||
|
|
||||||
|
registry.Add(item1)
|
||||||
|
fmt.Println("Size before removal:", registry.Size())
|
||||||
|
|
||||||
|
removed := registry.Remove(Active)
|
||||||
|
fmt.Println("Removed:", removed)
|
||||||
|
fmt.Println("Size after removal:", registry.Size())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Size before removal: 1
|
||||||
|
// Removed: true
|
||||||
|
// Size after removal: 0
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Update">Update</span>
|
||||||
|
|
||||||
|
<p>Updates the name of an enum item in the registry by its value.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (r *Registry[T]) Update(value T, newName string) bool
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/Ol0moT1J9Xl)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
item1 := enum.NewItem(Active, "Active")
|
||||||
|
|
||||||
|
registry.Add(item1)
|
||||||
|
updated := registry.Update(Active, "Activated")
|
||||||
|
fmt.Println("Updated:", updated)
|
||||||
|
|
||||||
|
if item, found := registry.GetByValue(Active); found {
|
||||||
|
fmt.Println("New name:", item.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Updated: true
|
||||||
|
// New name: Activated
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="GetByValue">GetByValue</span>
|
||||||
|
|
||||||
|
<p>Retrieves an enum item by its value.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (r *Registry[T]) GetByValue(value T) (*Item[T], bool)
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/niJ1U2KlE_m)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
item := enum.NewItem(Active, "Active")
|
||||||
|
|
||||||
|
registry.Add(item)
|
||||||
|
|
||||||
|
if item, found := registry.GetByValue(Active); found {
|
||||||
|
fmt.Println("Found name by value:", item.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Found name by value: Active
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="GetByName">GetByName</span>
|
||||||
|
|
||||||
|
<p>Retrieves an enum item by its name.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (r *Registry[T]) GetByName(name string) (*Item[T], bool)
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/49ie_gpqH0m)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
item := enum.NewItem(Active, "Active")
|
||||||
|
|
||||||
|
registry.Add(item)
|
||||||
|
|
||||||
|
if item, found := registry.GetByName("Active"); found {
|
||||||
|
fmt.Println("Found value by name:", item.Value())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Found value by name: 1
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Items">Items</span>
|
||||||
|
|
||||||
|
<p>Returns a slice of all enum items in the registry.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (r *Registry[T]) Items() []*Item[T]
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/lAJFAradbvQ)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
item1 := enum.NewItem(Active, "Active")
|
||||||
|
item2 := enum.NewItem(Inactive, "Inactive")
|
||||||
|
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
for _, item := range registry.Items() {
|
||||||
|
fmt.Println(item.Name(), item.Value())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Active 1
|
||||||
|
// Inactive 2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Contains">Contains</span>
|
||||||
|
|
||||||
|
<p>Checks if an enum item with the given value exists in the registry.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (r *Registry[T]) Contains(value T) bool
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/_T-lPYkZn2j)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
item := enum.NewItem(Active, "Active")
|
||||||
|
registry.Add(item)
|
||||||
|
|
||||||
|
fmt.Println(registry.Contains(Active))
|
||||||
|
fmt.Println(registry.Contains(Inactive))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// true
|
||||||
|
// false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Size">Size</span>
|
||||||
|
|
||||||
|
<p>Returns the number of enum items in the registry.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (r *Registry[T]) Size() int
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/TeDArWhlQe2)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
fmt.Println("Initial size:", registry.Size())
|
||||||
|
|
||||||
|
item1 := enum.NewItem(Active, "Active")
|
||||||
|
item2 := enum.NewItem(Inactive, "Inactive")
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
fmt.Println("Size after adding items:", registry.Size())
|
||||||
|
|
||||||
|
registry.Remove(Active)
|
||||||
|
fmt.Println("Size after removing an item:", registry.Size())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Initial size: 0
|
||||||
|
// Size after adding items: 2
|
||||||
|
// Size after removing an item: 1
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Range">Range</span>
|
||||||
|
|
||||||
|
<p>Iterates over all enum items in the registry and applies the given function.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (r *Registry[T]) Range(fn func(*Item[T]) bool)
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/GPsZbQbefWN)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
item1 := enum.NewItem(Active, "Active")
|
||||||
|
item2 := enum.NewItem(Inactive, "Inactive")
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
registry.Range(func(item *enum.Item[Status]) bool {
|
||||||
|
fmt.Println(item.Name(), item.Value())
|
||||||
|
return true // continue iteration
|
||||||
|
})
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Active 1
|
||||||
|
// Inactive 2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="SortedItems">SortedItems</span>
|
||||||
|
|
||||||
|
<p>Returns a slice of all enum items sorted by the given less function.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (r *Registry[T]) SortedItems(less func(*Item[T], *Item[T]) bool) []*Item[T]
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/tN9RE_m_WEI)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
item1 := enum.NewItem(Inactive, "Inactive")
|
||||||
|
item2 := enum.NewItem(Active, "Active")
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
for _, item := range registry.SortedItems(func(i1, i2 *enum.Item[Status]) bool {
|
||||||
|
return i1.Value() < i2.Value()
|
||||||
|
}) {
|
||||||
|
fmt.Println(item.Name(), item.Value())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Active 1
|
||||||
|
// Inactive 2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="Filter">Filter</span>
|
||||||
|
|
||||||
|
<p>Returns a slice of enum items that satisfy the given predicate function.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (r *Registry[T]) Filter(predicate func(*Item[T]) bool) []*Item[T]
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/uTUpTdcyoCU)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/enum"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
registry := enum.NewRegistry[Status]()
|
||||||
|
item1 := enum.NewItem(Active, "Active")
|
||||||
|
item2 := enum.NewItem(Inactive, "Inactive")
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
activeItems := registry.Filter(func(item *enum.Item[Status]) bool {
|
||||||
|
return item.Value() == Active
|
||||||
|
})
|
||||||
|
|
||||||
|
for _, item := range activeItems {
|
||||||
|
fmt.Println(item.Name(), item.Value())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Active 1
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -8,6 +8,7 @@ formatter contains some functions for data formatting.
|
|||||||
|
|
||||||
- [https://github.com/duke-git/lancet/blob/main/formatter/formatter.go](https://github.com/duke-git/lancet/blob/main/formatter/formatter.go)
|
- [https://github.com/duke-git/lancet/blob/main/formatter/formatter.go](https://github.com/duke-git/lancet/blob/main/formatter/formatter.go)
|
||||||
- [https://github.com/duke-git/lancet/blob/main/formatter/byte.go](https://github.com/duke-git/lancet/blob/main/formatter/byte.go)
|
- [https://github.com/duke-git/lancet/blob/main/formatter/byte.go](https://github.com/duke-git/lancet/blob/main/formatter/byte.go)
|
||||||
|
- [https://github.com/duke-git/lancet/blob/main/formatter/address.go](https://github.com/duke-git/lancet/blob/main/formatter/address.go)
|
||||||
|
|
||||||
<div STYLE="page-break-after: always;"></div>
|
<div STYLE="page-break-after: always;"></div>
|
||||||
|
|
||||||
@@ -30,6 +31,8 @@ import (
|
|||||||
- [BinaryBytes](#BinaryBytes)
|
- [BinaryBytes](#BinaryBytes)
|
||||||
- [ParseDecimalBytes](#ParseDecimalBytes)
|
- [ParseDecimalBytes](#ParseDecimalBytes)
|
||||||
- [ParseBinaryBytes](#ParseBinaryBytes)
|
- [ParseBinaryBytes](#ParseBinaryBytes)
|
||||||
|
- [ParseCNAddress](#ParseCNAddress)
|
||||||
|
- [ParsePersonInfo](#ParsePersonInfo)
|
||||||
|
|
||||||
<div STYLE="page-break-after: always;"></div>
|
<div STYLE="page-break-after: always;"></div>
|
||||||
|
|
||||||
@@ -308,3 +311,134 @@ func main() {
|
|||||||
// 12492
|
// 12492
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### <span id="ParseCNAddress">ParseCNAddress</span>
|
||||||
|
|
||||||
|
<p>Parses a Chinese address string intelligently and extracts structured information. It can parse addresses with or without user information (name, phone, ID card, etc.). When withUser is true, it extracts user information from the address string. When withUser is false, it only parses the location information. Supports various address formats: standard format, compact format, labeled format, county-level cities format, etc.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func ParseCNAddress(str string, withUser bool) *AddressInfo
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/o5l09hQopEV)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/formatter"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Parse complete address with user information
|
||||||
|
result1 := formatter.ParseCNAddress("张三 13800138000 北京市朝阳区建国路1号", true)
|
||||||
|
jsonData1, _ := json.MarshalIndent(result1, "", " ")
|
||||||
|
fmt.Println("Example 1 - With user info:")
|
||||||
|
fmt.Println(string(jsonData1))
|
||||||
|
|
||||||
|
// Parse address only, without extracting user information
|
||||||
|
result2 := formatter.ParseCNAddress("北京市海淀区中关村大街1号", false)
|
||||||
|
fmt.Printf("\nExample 2 - Address only:\n")
|
||||||
|
fmt.Printf("Province: %s, City: %s, Region: %s, Street: %s\n",
|
||||||
|
result2.Province, result2.City, result2.Region, result2.Street)
|
||||||
|
|
||||||
|
// Parse county-level city address
|
||||||
|
result3 := formatter.ParseCNAddress("河北省石家庄市新乐市经济开发区兴工街10号", false)
|
||||||
|
fmt.Printf("\nExample 3 - County-level city:\n")
|
||||||
|
fmt.Printf("Province: %s, City: %s, Region: %s, Street: %s\n",
|
||||||
|
result3.Province, result3.City, result3.Region, result3.Street)
|
||||||
|
|
||||||
|
// Compact format
|
||||||
|
result4 := formatter.ParseCNAddress("马云13593464918陕西省西安市雁塔区丈八沟街道", true)
|
||||||
|
fmt.Printf("\nExample 4 - Compact format:\n")
|
||||||
|
fmt.Printf("Name: %s, Phone: %s, Address: %s%s%s%s\n",
|
||||||
|
result4.Name, result4.Mobile, result4.Province, result4.City, result4.Region, result4.Street)
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Example 1 - With user info:
|
||||||
|
// {
|
||||||
|
// "name": "张三",
|
||||||
|
// "mobile": "13800138000",
|
||||||
|
// "idn": "",
|
||||||
|
// "postcode": "",
|
||||||
|
// "province": "北京",
|
||||||
|
// "city": "北京市",
|
||||||
|
// "region": "朝阳区",
|
||||||
|
// "street": "建国路1号",
|
||||||
|
// "addr": "北京市朝阳区建国路1号"
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// Example 2 - Address only:
|
||||||
|
// Province: 北京, City: 北京市, Region: 海淀区, Street: 中关村大街1号
|
||||||
|
//
|
||||||
|
// Example 3 - County-level city:
|
||||||
|
// Province: 河北省, City: 石家庄市, Region: 新乐市, Street: 经济开发区兴工街10号
|
||||||
|
//
|
||||||
|
// Example 4 - Compact format:
|
||||||
|
// Name: 马云, Phone: 13593464918, Address: 陕西省西安市雁塔区丈八沟街道
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="ParsePersonInfo">ParsePersonInfo</span>
|
||||||
|
|
||||||
|
<p>Extracts user information (name, phone, ID card, postal code) from an address string. It separates personal information from the address, supporting labeled format, compact format, and formats with separators. Returns an AddressInfo with extracted user information and cleaned address string.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func ParsePersonInfo(str string) *AddressInfo
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/JO-uTlJlTy7)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/formatter"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Extract name and phone
|
||||||
|
result1 := formatter.ParsePersonInfo("张三 13800138000 北京市朝阳区")
|
||||||
|
fmt.Println("Example 1 - Name and phone:")
|
||||||
|
fmt.Printf("Name: %s, Phone: %s, Address: %s\n", result1.Name, result1.Mobile, result1.Addr)
|
||||||
|
|
||||||
|
// Extract ID card number
|
||||||
|
result2 := formatter.ParsePersonInfo("李四 110101199001011234 上海市")
|
||||||
|
fmt.Println("\nExample 2 - ID card number:")
|
||||||
|
fmt.Printf("Name: %s, ID Card: %s, Address: %s\n", result2.Name, result2.IDN, result2.Addr)
|
||||||
|
|
||||||
|
// Labeled format
|
||||||
|
result3 := formatter.ParsePersonInfo("收货人:王五 电话:13900139000 收货地址:天津市河西区友谊路20号")
|
||||||
|
jsonData3, _ := json.MarshalIndent(result3, "", " ")
|
||||||
|
fmt.Println("\nExample 3 - Labeled format:")
|
||||||
|
fmt.Println(string(jsonData3))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Example 1 - Name and phone:
|
||||||
|
// Name: 张三, Phone: 13800138000, Address: 北京市朝阳区
|
||||||
|
//
|
||||||
|
// Example 2 - ID card number:
|
||||||
|
// Name: 李四, ID Card: 110101199001011234, Address: 上海市
|
||||||
|
//
|
||||||
|
// Example 3 - Labeled format:
|
||||||
|
// {
|
||||||
|
// "name": "王五",
|
||||||
|
// "mobile": "13900139000",
|
||||||
|
// "idn": "",
|
||||||
|
// "postcode": "",
|
||||||
|
// "province": "",
|
||||||
|
// "city": "",
|
||||||
|
// "region": "",
|
||||||
|
// "street": "",
|
||||||
|
// "addr": "天津市河西区友谊路20号"
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -620,7 +620,7 @@ func main() {
|
|||||||
|
|
||||||
### <span id="Nand">Nand</span>
|
### <span id="Nand">Nand</span>
|
||||||
|
|
||||||
<p>Returns a composed predicate that represents the logical NAND of a list of predicates. It evaluates to true only if all predicates evaluate to false for the given value.</p>
|
<p>Returns a composed predicate that represents the logical NAND of a list of predicates. It evaluates to false only if all predicates evaluate to true for the given value.</p>
|
||||||
|
|
||||||
<b>Signature:</b>
|
<b>Signature:</b>
|
||||||
|
|
||||||
@@ -650,7 +650,7 @@ func main() {
|
|||||||
|
|
||||||
// Output:
|
// Output:
|
||||||
// false
|
// false
|
||||||
// false
|
// true
|
||||||
// true
|
// true
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -79,6 +79,7 @@ import (
|
|||||||
- [SortByKey](#SortByKey)
|
- [SortByKey](#SortByKey)
|
||||||
- [GetOrDefault](#GetOrDefault)
|
- [GetOrDefault](#GetOrDefault)
|
||||||
- [FindValuesBy](#FindValuesBy)
|
- [FindValuesBy](#FindValuesBy)
|
||||||
|
- [ToMarkdownTable](#ToMarkdownTable)
|
||||||
|
|
||||||
<div STYLE="page-break-after: always;"></div>
|
<div STYLE="page-break-after: always;"></div>
|
||||||
|
|
||||||
@@ -2363,3 +2364,69 @@ func main() {
|
|||||||
// [b d]
|
// [b d]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### <span id="ToMarkdownTable">ToMarkdownTable</span>
|
||||||
|
|
||||||
|
<p>Convert a map slice data to a Markdown table string. It supports custom header display names and column display order.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
编辑
|
||||||
|
func ToMarkdownTable(data []map[string]interface{}, headerMap map[string]string, columnOrder []string) string
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/w_pSLfeyEB5)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/maputil"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// basic usage: automatically extract column names from data as table headers
|
||||||
|
|
||||||
|
data := []map[string]interface{}{
|
||||||
|
{"name": "Alice", "age": 25, "salary": 50000},
|
||||||
|
{"name": "Bob", "age": 30, "salary": 60000},
|
||||||
|
}
|
||||||
|
|
||||||
|
result := maputil.ToMarkdownTable(data, nil, nil)
|
||||||
|
fmt.Println(result)
|
||||||
|
|
||||||
|
// output:
|
||||||
|
// |name|age|salary|
|
||||||
|
// |---|---|---|
|
||||||
|
// |Alice|25|50000|
|
||||||
|
// |Bob|30|60000|
|
||||||
|
|
||||||
|
// custom header name
|
||||||
|
headerMap := map[string]string{
|
||||||
|
"name": "n",
|
||||||
|
"age": "a",
|
||||||
|
"salary": "s",
|
||||||
|
}
|
||||||
|
result = maputil.ToMarkdownTable(data, headerMap, nil)
|
||||||
|
fmt.Println(result)
|
||||||
|
|
||||||
|
// ouput:
|
||||||
|
// |m|a|s|
|
||||||
|
// |---|---|---|
|
||||||
|
// |Alice|25|50000|
|
||||||
|
// |Bob|30|60000|
|
||||||
|
|
||||||
|
// custom column display order
|
||||||
|
columnOrder := []string{"salary", "name"}
|
||||||
|
result = maputil.ToMarkdownTable(data, nil, columnOrder)
|
||||||
|
fmt.Println(result)
|
||||||
|
|
||||||
|
// output:
|
||||||
|
// |salary|name|
|
||||||
|
// |---|---|
|
||||||
|
// |50000|Alice|
|
||||||
|
// |60000|Bob|
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -27,6 +27,7 @@ import (
|
|||||||
- [Contain](#Contain)
|
- [Contain](#Contain)
|
||||||
- [ContainBy](#ContainBy)
|
- [ContainBy](#ContainBy)
|
||||||
- [ContainSubSlice](#ContainSubSlice)
|
- [ContainSubSlice](#ContainSubSlice)
|
||||||
|
- [ContainAny](#ContainAny)
|
||||||
- [Chunk](#Chunk)
|
- [Chunk](#Chunk)
|
||||||
- [Compact](#Compact)
|
- [Compact](#Compact)
|
||||||
- [Concat](#Concat)
|
- [Concat](#Concat)
|
||||||
@@ -256,6 +257,43 @@ func main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### <span id="ContainAny">ContainAny</span>
|
||||||
|
|
||||||
|
<p>Check if the slice contains any element from the targets slice.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func ContainAny[T comparable](slice []T, targets []T) bool
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/4xoxhc9XSSw)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/slice"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
result1 := slice.ContainAny([]string{"a", "b", "c"}, []string{"a"})
|
||||||
|
result2 := slice.ContainAny([]string{"a", "b", "c"}, []string{"d", "e"})
|
||||||
|
result3 := slice.ContainAny([]string{"a", "b", "c"}, []string{"d", "a"})
|
||||||
|
result4 := slice.ContainAny([]string{"a", "b", "c"}, []string{})
|
||||||
|
|
||||||
|
fmt.Println(result1)
|
||||||
|
fmt.Println(result2)
|
||||||
|
fmt.Println(result3)
|
||||||
|
fmt.Println(result4)
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// true
|
||||||
|
// false
|
||||||
|
// true
|
||||||
|
// false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### <span id="Chunk">Chunk</span>
|
### <span id="Chunk">Chunk</span>
|
||||||
|
|
||||||
<p>Creates an slice of elements split into groups the length of `size`.</p>
|
<p>Creates an slice of elements split into groups the length of `size`.</p>
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ import (
|
|||||||
- [IsStruct](#IsStruct)
|
- [IsStruct](#IsStruct)
|
||||||
- [Tag](#Tag)
|
- [Tag](#Tag)
|
||||||
- [Name](#Name)
|
- [Name](#Name)
|
||||||
|
- [TypeName](#TypeName)
|
||||||
- [Value](#Value)
|
- [Value](#Value)
|
||||||
- [Kind](#Kind)
|
- [Kind](#Kind)
|
||||||
- [IsEmbedded](#IsEmbedded)
|
- [IsEmbedded](#IsEmbedded)
|
||||||
@@ -53,12 +54,13 @@ import (
|
|||||||
func New(value any, tagName ...string) *Struct
|
func New(value any, tagName ...string) *Struct
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>Example:</b>
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/O29l8kk-Z17)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"github.com/duke-git/lancet/v2/structs"
|
"github.com/duke-git/lancet/v2/structs"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -68,7 +70,11 @@ func main() {
|
|||||||
}
|
}
|
||||||
p1 := &People{Name: "11"}
|
p1 := &People{Name: "11"}
|
||||||
s := structs.New(p1)
|
s := structs.New(p1)
|
||||||
// to do something
|
|
||||||
|
fmt.Println(s.ToMap())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// map[name:11] <nil>
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -88,7 +94,7 @@ func (s *Struct) ToMap() (map[string]any, error)
|
|||||||
func ToMap(v any) (map[string]any, error)
|
func ToMap(v any) (map[string]any, error)
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>Example:</b>
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/qQbLySBgerZ)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -130,7 +136,7 @@ func main() {
|
|||||||
func (s *Struct) Fields() []*Field
|
func (s *Struct) Fields() []*Field
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>Example:</b>
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/w3Kk_CyVY7D)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -162,10 +168,10 @@ func main() {
|
|||||||
<b>Signature:</b>
|
<b>Signature:</b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
func (s *Struct) Field(name string) *Field
|
func (s *Struct) Field(name string) (*Field, bool)
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>Example:</b>
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/KocZMSYarza)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -181,12 +187,14 @@ func main() {
|
|||||||
}
|
}
|
||||||
p1 := &People{Name: "11"}
|
p1 := &People{Name: "11"}
|
||||||
s := structs.New(p1)
|
s := structs.New(p1)
|
||||||
f := s.Field("Name")
|
f, found := s.Field("Name")
|
||||||
|
|
||||||
fmt.Println(f.Value())
|
fmt.Println(f.Value())
|
||||||
|
fmt.Println(found)
|
||||||
|
|
||||||
// Output:
|
// Output:
|
||||||
// 11
|
// 11
|
||||||
|
// true
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -200,7 +208,7 @@ func main() {
|
|||||||
func (s *Struct) IsStruct() bool
|
func (s *Struct) IsStruct() bool
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>Example:</b>
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/bU2FSdkbK1C)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -234,7 +242,7 @@ func main() {
|
|||||||
func (f *Field) Tag() *Tag
|
func (f *Field) Tag() *Tag
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>Example:</b>
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/DVrx5HvvUJr)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -271,7 +279,7 @@ func main() {
|
|||||||
func (f *Field) Value() any
|
func (f *Field) Value() any
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>Example:</b>
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/qufYEU2o4Oi)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -307,7 +315,7 @@ func main() {
|
|||||||
func (f *Field) IsEmbedded() bool
|
func (f *Field) IsEmbedded() bool
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>Example:</b>
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/wV2PrbYm3Ec)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -352,7 +360,7 @@ func main() {
|
|||||||
func (f *Field) IsExported() bool
|
func (f *Field) IsExported() bool
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>Example:</b>
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/csK4AXYaNbJ)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -391,7 +399,7 @@ func main() {
|
|||||||
func (f *Field) IsZero() bool
|
func (f *Field) IsZero() bool
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>Example:</b>
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/RzqpGISf87r)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -430,7 +438,7 @@ func main() {
|
|||||||
func (f *Field) Name() string
|
func (f *Field) Name() string
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>Example:</b>
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/zfIGlqsatee)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -469,7 +477,7 @@ func main() {
|
|||||||
func (f *Field) Kind() reflect.Kind
|
func (f *Field) Kind() reflect.Kind
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>Example:</b>
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/wg4NlcUNG5o)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -498,6 +506,42 @@ func main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### <span id="TypeName">TypeName</span>
|
||||||
|
|
||||||
|
<p>Return struct type name.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (s *Struct) TypeName() string
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/SWLWd0XBaBb)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/structs"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
type Parent struct {
|
||||||
|
Name string
|
||||||
|
Age int
|
||||||
|
}
|
||||||
|
|
||||||
|
p := &Parent{Age: 11}
|
||||||
|
s := structs.New(p)
|
||||||
|
|
||||||
|
fmt.Println(s.TypeName())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Parent
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### <span id="IsSlice">IsSlice</span>
|
### <span id="IsSlice">IsSlice</span>
|
||||||
|
|
||||||
<p>Check if the field is a slice</p>
|
<p>Check if the field is a slice</p>
|
||||||
@@ -508,7 +552,7 @@ func main() {
|
|||||||
func (f *Field) IsSlice() bool
|
func (f *Field) IsSlice() bool
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>Example:</b>
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/MKz4CgBIUrU)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -545,7 +589,7 @@ func main() {
|
|||||||
func (f *Field) IsTargetType(targetType reflect.Kind) bool
|
func (f *Field) IsTargetType(targetType reflect.Kind) bool
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>Example:</b>
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/Ig75P-agN39)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -566,12 +610,12 @@ func main() {
|
|||||||
s := structs.New(p1)
|
s := structs.New(p1)
|
||||||
n, _ := s.Field("Name")
|
n, _ := s.Field("Name")
|
||||||
a, _ := s.Field("arr")
|
a, _ := s.Field("arr")
|
||||||
|
|
||||||
fmt.Println(n.IsTargetType(reflect.String))
|
fmt.Println(n.IsTargetType(reflect.String))
|
||||||
fmt.Println(a.IsTargetType(reflect.Slice))
|
fmt.Println(a.IsTargetType(reflect.Slice))
|
||||||
|
|
||||||
// Output:
|
// Output:
|
||||||
// true
|
// true
|
||||||
// true
|
// true
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -27,6 +27,7 @@ import (
|
|||||||
- [Before](#Before)
|
- [Before](#Before)
|
||||||
- [BeforeLast](#BeforeLast)
|
- [BeforeLast](#BeforeLast)
|
||||||
- [CamelCase](#CamelCase)
|
- [CamelCase](#CamelCase)
|
||||||
|
- [UpperCamelCase](#UpperCamelCase)
|
||||||
- [Capitalize](#Capitalize)
|
- [Capitalize](#Capitalize)
|
||||||
- [IsString](#IsString)
|
- [IsString](#IsString)
|
||||||
- [KebabCase](#KebabCase)
|
- [KebabCase](#KebabCase)
|
||||||
@@ -265,6 +266,40 @@ func main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### <span id="UpperCamelCase">UpperCamelCase</span>
|
||||||
|
|
||||||
|
<p>Coverts string to CamelCase string, non letters and numbers will be ignored.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func UpperCamelCase(s string) string
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/vPHszjTXSFp)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/strutil"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
strings := []string{"", "foobar", "&FOO:BAR$BAZ", "$foo%", "Foo-#1😄$_%^&*(1bar"}
|
||||||
|
|
||||||
|
for _, v := range strings {
|
||||||
|
s := strutil.UpperCamelCase(v)
|
||||||
|
fmt.Println(s)
|
||||||
|
}
|
||||||
|
// Output:
|
||||||
|
//
|
||||||
|
// Foobar
|
||||||
|
// FooBarBaz
|
||||||
|
// Foo
|
||||||
|
// Foo11Bar
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### <span id="KebabCase">KebabCase</span>
|
### <span id="KebabCase">KebabCase</span>
|
||||||
|
|
||||||
<p>KebabCase covert string to kebab-case, non letters and numbers will be ignored.</p>
|
<p>KebabCase covert string to kebab-case, non letters and numbers will be ignored.</p>
|
||||||
|
|||||||
@@ -65,6 +65,8 @@ import (
|
|||||||
- [IsAmericanExpress](#IsAmericanExpress)
|
- [IsAmericanExpress](#IsAmericanExpress)
|
||||||
- [IsUnionPay](#IsUnionPay)
|
- [IsUnionPay](#IsUnionPay)
|
||||||
- [IsChinaUnionPay](#IsChinaUnionPay)
|
- [IsChinaUnionPay](#IsChinaUnionPay)
|
||||||
|
- [IsPassport](#IsPassport)
|
||||||
|
- [IsChineseHMPassport](#IsChineseHMPassport)
|
||||||
|
|
||||||
<div STYLE="page-break-after: always;"></div>
|
<div STYLE="page-break-after: always;"></div>
|
||||||
|
|
||||||
@@ -549,7 +551,7 @@ func main() {
|
|||||||
func IsEmail(email string) bool
|
func IsEmail(email string) bool
|
||||||
```
|
```
|
||||||
|
|
||||||
<b>Example:<span style="float:right;display:inline-block">[Run](https://go.dev/play/p/Os9VaFlT33G)</span></b>
|
<b>Example:<span style="float:right;display:inline-block">[Run](https://go.dev/play/p/HVQ5LAe-vFz)</span></b>
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import (
|
import (
|
||||||
@@ -559,13 +561,28 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
result1 := validator.IsEmail("abc@xyz.com")
|
result1 := validator.IsEmail("abc@xyz.com")
|
||||||
result2 := validator.IsEmail("a.b@@com")
|
result2 := validator.IsEmail("user@domain.co")
|
||||||
|
result3 := validator.IsEmail("test.user@example.org")
|
||||||
|
result4 := validator.IsEmail("@abc@xyz.com")
|
||||||
|
result5 := validator.IsEmail("a.b@@com")
|
||||||
|
result6 := validator.IsEmail("a.b@com")
|
||||||
|
result7 := validator.IsEmail("test@example")
|
||||||
|
|
||||||
fmt.Println(result1)
|
fmt.Println(result1)
|
||||||
fmt.Println(result2)
|
fmt.Println(result2)
|
||||||
|
fmt.Println(result3)
|
||||||
|
fmt.Println(result4)
|
||||||
|
fmt.Println(result5)
|
||||||
|
fmt.Println(result6)
|
||||||
|
fmt.Println(result7)
|
||||||
|
|
||||||
// Output:
|
// Output:
|
||||||
// true
|
// true
|
||||||
|
// true
|
||||||
|
// true
|
||||||
|
// false
|
||||||
|
// false
|
||||||
|
// false
|
||||||
// false
|
// false
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -1569,3 +1586,80 @@ func main() {
|
|||||||
// false
|
// false
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### <span id="IsPassport">IsPassport</span>
|
||||||
|
|
||||||
|
<p>Passport validation(using regex).</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func IsPassport(passport, country string) bool
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block">[Run](https://go.dev/play/p/dvOiV2BW7Aw)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/validator"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
result1 := validator.IsPassport("P123456789", "CN")
|
||||||
|
result2 := validator.IsPassport("123456789", "US")
|
||||||
|
result3 := validator.IsPassport("AB1234567", "RU")
|
||||||
|
result4 := validator.IsPassport("123456789", "CN")
|
||||||
|
|
||||||
|
fmt.Println(result1)
|
||||||
|
fmt.Println(result2)
|
||||||
|
fmt.Println(result3)
|
||||||
|
fmt.Println(result4)
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// true
|
||||||
|
// true
|
||||||
|
// true
|
||||||
|
// false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### <span id="IsChineseHMPassport">IsChineseHMPassport</span>
|
||||||
|
|
||||||
|
<p>Mainland travel permit for Hong Kong, Macao validation (using regex). </p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func IsChineseHMPassport(hmPassport string) bool
|
||||||
|
```
|
||||||
|
|
||||||
|
<b>Example:<span style="float:right;display:inline-block">[Run](https://go.dev/play/p/xKG6spQTcY0)</span></b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/duke-git/lancet/v2/validator"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
result1 := validator.IsChineseHMPassport("C12345678")
|
||||||
|
result2 := validator.IsChineseHMPassport("C00000000")
|
||||||
|
result3 := validator.IsChineseHMPassport("M12345678")
|
||||||
|
result4 := validator.IsChineseHMPassport("c12345678")
|
||||||
|
result5 := validator.IsChineseHMPassport("C1234567")
|
||||||
|
|
||||||
|
fmt.Println(result1)
|
||||||
|
fmt.Println(result2)
|
||||||
|
fmt.Println(result3)
|
||||||
|
fmt.Println(result4)
|
||||||
|
fmt.Println(result5)
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// true
|
||||||
|
// true
|
||||||
|
// true
|
||||||
|
// false
|
||||||
|
// false
|
||||||
|
}
|
||||||
|
```
|
||||||
Generated
+334
-192
File diff suppressed because it is too large.
Load diff
+317
@@ -0,0 +1,317 @@
|
|||||||
|
// Copyright 2025 dudaodong@gmail.com. All rights resulterved.
|
||||||
|
// Use of this source code is governed by MIT license
|
||||||
|
|
||||||
|
// Package enum provides a simple enum implementation.
|
||||||
|
package enum
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"reflect"
|
||||||
|
"sort"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Enum defines a common enum interface.
|
||||||
|
type Enum[T comparable] interface {
|
||||||
|
Value() T
|
||||||
|
String() string
|
||||||
|
Name() string
|
||||||
|
Valid(checker ...func(T) bool) bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Item defines a common enum item struct implement Enum interface.
|
||||||
|
type Item[T comparable] struct {
|
||||||
|
value T
|
||||||
|
name string
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewItem creates a new enum item.
|
||||||
|
// Play: https://go.dev/play/p/8qNsLw01HD5
|
||||||
|
func NewItem[T comparable](value T, name string) *Item[T] {
|
||||||
|
return &Item[T]{value: value, name: name}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pair represents a value-name pair for creating enum items
|
||||||
|
type Pair[T comparable] struct {
|
||||||
|
Value T
|
||||||
|
Name string
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewItemsFromPairs creates enum items from a slice of Pair structs.
|
||||||
|
// Play: https://go.dev/play/p/xKnoGa7gnev
|
||||||
|
func NewItemsFromPairs[T comparable](pairs ...Pair[T]) []*Item[T] {
|
||||||
|
if len(pairs) == 0 {
|
||||||
|
return []*Item[T]{}
|
||||||
|
}
|
||||||
|
|
||||||
|
items := make([]*Item[T], 0, len(pairs))
|
||||||
|
for _, pair := range pairs {
|
||||||
|
items = append(items, &Item[T]{value: pair.Value, name: pair.Name})
|
||||||
|
}
|
||||||
|
|
||||||
|
return items
|
||||||
|
}
|
||||||
|
|
||||||
|
// Value returns the value of the enum item.
|
||||||
|
// Play: https://go.dev/play/p/xKnoGa7gnev
|
||||||
|
func (it *Item[T]) Value() T {
|
||||||
|
return it.value
|
||||||
|
}
|
||||||
|
|
||||||
|
// Name returns the name of the enum item.
|
||||||
|
// Play: https://go.dev/play/p/xKnoGa7gnev
|
||||||
|
func (it *Item[T]) Name() string {
|
||||||
|
return it.name
|
||||||
|
}
|
||||||
|
|
||||||
|
// String returns the string representation of the enum item.
|
||||||
|
func (it *Item[T]) String() string {
|
||||||
|
return it.name
|
||||||
|
}
|
||||||
|
|
||||||
|
// Valid checks if the enum item is valid. If a custom check function is provided, it will be used to validate the value.
|
||||||
|
// Play: https://go.dev/play/p/pA3lYY2VSm3
|
||||||
|
func (it *Item[T]) Valid(checker ...func(T) bool) bool {
|
||||||
|
if len(checker) > 0 {
|
||||||
|
return checker[0](it.value) && it.name != ""
|
||||||
|
}
|
||||||
|
var zero T
|
||||||
|
return it.value != zero && it.name != ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalJSON implements the json.Marshaler interface.
|
||||||
|
// Play: https://go.dev/play/p/zIZEdAnneB5
|
||||||
|
func (it *Item[T]) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(map[string]any{
|
||||||
|
"value": it.value,
|
||||||
|
"name": it.name,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnmarshalJSON implements the json.Unmarshaler interface.
|
||||||
|
// Play: https://go.dev/play/p/zIZEdAnneB5
|
||||||
|
func (it *Item[T]) UnmarshalJSON(data []byte) error {
|
||||||
|
type alias struct {
|
||||||
|
Value any `json:"value"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
var temp alias
|
||||||
|
if err := json.Unmarshal(data, &temp); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var v T
|
||||||
|
rv := reflect.TypeOf(v)
|
||||||
|
switch rv.Kind() {
|
||||||
|
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||||
|
val, ok := temp.Value.(float64)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("invalid type for value, want int family")
|
||||||
|
}
|
||||||
|
converted := reflect.ValueOf(int64(val)).Convert(rv)
|
||||||
|
it.value = converted.Interface().(T)
|
||||||
|
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||||
|
val, ok := temp.Value.(float64)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("invalid type for value, want uint family")
|
||||||
|
}
|
||||||
|
converted := reflect.ValueOf(uint64(val)).Convert(rv)
|
||||||
|
it.value = converted.Interface().(T)
|
||||||
|
case reflect.Float32, reflect.Float64:
|
||||||
|
val, ok := temp.Value.(float64)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("invalid type for value, want float family")
|
||||||
|
}
|
||||||
|
converted := reflect.ValueOf(val).Convert(rv)
|
||||||
|
it.value = converted.Interface().(T)
|
||||||
|
case reflect.String:
|
||||||
|
val, ok := temp.Value.(string)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("invalid type for value, want string")
|
||||||
|
}
|
||||||
|
it.value = any(val).(T)
|
||||||
|
case reflect.Bool:
|
||||||
|
val, ok := temp.Value.(bool)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("invalid type for value, want bool")
|
||||||
|
}
|
||||||
|
it.value = any(val).(T)
|
||||||
|
default:
|
||||||
|
val, ok := temp.Value.(float64)
|
||||||
|
if ok {
|
||||||
|
converted := reflect.ValueOf(int64(val)).Convert(rv)
|
||||||
|
it.value = converted.Interface().(T)
|
||||||
|
} else {
|
||||||
|
val2, ok2 := temp.Value.(T)
|
||||||
|
if !ok2 {
|
||||||
|
return fmt.Errorf("invalid type for value")
|
||||||
|
}
|
||||||
|
it.value = val2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
it.name = temp.Name
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Registry defines a common enum registry struct.
|
||||||
|
type Registry[T comparable] struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
values map[T]*Item[T]
|
||||||
|
names map[string]*Item[T]
|
||||||
|
items []*Item[T]
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewRegistry creates a new enum registry.
|
||||||
|
// Play: https://go.dev/play/p/ABEXsYfJKMo
|
||||||
|
func NewRegistry[T comparable](items ...*Item[T]) *Registry[T] {
|
||||||
|
r := &Registry[T]{
|
||||||
|
values: make(map[T]*Item[T]),
|
||||||
|
names: make(map[string]*Item[T]),
|
||||||
|
items: make([]*Item[T], 0, len(items)),
|
||||||
|
}
|
||||||
|
|
||||||
|
r.Add(items...)
|
||||||
|
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add adds enum items to the registry.
|
||||||
|
// Play: https://go.dev/play/p/ABEXsYfJKMo
|
||||||
|
func (r *Registry[T]) Add(items ...*Item[T]) {
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
|
||||||
|
for _, item := range items {
|
||||||
|
if _, exists := r.values[item.value]; exists {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, exists := r.names[item.name]; exists {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
r.values[item.value] = item
|
||||||
|
r.names[item.name] = item
|
||||||
|
r.items = append(r.items, item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove removes an enum item from the registry by its value.
|
||||||
|
// Play: https://go.dev/play/p/dSG84wQ3TuC
|
||||||
|
func (r *Registry[T]) Remove(value T) bool {
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
item, ok := r.values[value]
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
delete(r.values, value)
|
||||||
|
delete(r.names, item.name)
|
||||||
|
for i, it := range r.items {
|
||||||
|
if it.value == value {
|
||||||
|
r.items = append(r.items[:i], r.items[i+1:]...)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update updates the name of an enum item in the registry by its value.
|
||||||
|
// Play: https://go.dev/play/p/Ol0moT1J9Xl
|
||||||
|
func (r *Registry[T]) Update(value T, newName string) bool {
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
item, ok := r.values[value]
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
delete(r.names, item.name)
|
||||||
|
item.name = newName
|
||||||
|
r.names[newName] = item
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetByValue retrieves an enum item by its value.
|
||||||
|
// Play: https://go.dev/play/p/niJ1U2KlE_m
|
||||||
|
func (r *Registry[T]) GetByValue(value T) (*Item[T], bool) {
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
|
||||||
|
item, ok := r.values[value]
|
||||||
|
return item, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetByName retrieves an enum item by its name.
|
||||||
|
// Play: https://go.dev/play/p/49ie_gpqH0m
|
||||||
|
func (r *Registry[T]) GetByName(name string) (*Item[T], bool) {
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
|
||||||
|
item, ok := r.names[name]
|
||||||
|
return item, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// Items returns a slice of all enum items in the registry.
|
||||||
|
// Play: https://go.dev/play/p/lAJFAradbvQ
|
||||||
|
func (r *Registry[T]) Items() []*Item[T] {
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
|
||||||
|
result := make([]*Item[T], len(r.items))
|
||||||
|
copy(result, r.items)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// Contains checks if an enum item with the given value exists in the registry.
|
||||||
|
// Play: https://go.dev/play/p/_T-lPYkZn2j
|
||||||
|
func (r *Registry[T]) Contains(value T) bool {
|
||||||
|
_, ok := r.GetByValue(value)
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// Size returns the number of enum items in the registry.
|
||||||
|
// Play: https://go.dev/play/p/TeDArWhlQe2
|
||||||
|
func (r *Registry[T]) Size() int {
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
|
||||||
|
return len(r.items)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Range iterates over all enum items in the registry and applies the given function.
|
||||||
|
// Play: https://go.dev/play/p/GPsZbQbefWN
|
||||||
|
func (r *Registry[T]) Range(fn func(*Item[T]) bool) {
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
|
||||||
|
for _, item := range r.items {
|
||||||
|
if !fn(item) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SortedItems returns a slice of all enum items sorted by the given less function.
|
||||||
|
// Play: https://go.dev/play/p/tN9RE_m_WEI
|
||||||
|
func (r *Registry[T]) SortedItems(less func(*Item[T], *Item[T]) bool) []*Item[T] {
|
||||||
|
items := r.Items()
|
||||||
|
sort.Slice(items, func(i, j int) bool {
|
||||||
|
return less(items[i], items[j])
|
||||||
|
})
|
||||||
|
return items
|
||||||
|
}
|
||||||
|
|
||||||
|
// Filter returns a slice of enum items that satisfy the given predicate function.
|
||||||
|
// Play: https://go.dev/play/p/uTUpTdcyoCU
|
||||||
|
func (r *Registry[T]) Filter(predicate func(*Item[T]) bool) []*Item[T] {
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
|
||||||
|
var result []*Item[T]
|
||||||
|
for _, item := range r.items {
|
||||||
|
if predicate(item) {
|
||||||
|
result = append(result, item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
package enum
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
func ExampleNewItem() {
|
||||||
|
item1 := NewItem(Active, "Active")
|
||||||
|
item2 := NewItem(Inactive, "Inactive")
|
||||||
|
|
||||||
|
fmt.Println(item1.Name(), item1.Value())
|
||||||
|
fmt.Println(item2.Name(), item2.Value())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Active 1
|
||||||
|
// Inactive 2
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleNewItemsFromPairs() {
|
||||||
|
items := NewItemsFromPairs(
|
||||||
|
Pair[Status]{Value: Active, Name: "Active"},
|
||||||
|
Pair[Status]{Value: Inactive, Name: "Inactive"},
|
||||||
|
)
|
||||||
|
|
||||||
|
fmt.Println(items[0].Name(), items[0].Value())
|
||||||
|
fmt.Println(items[1].Name(), items[1].Value())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Active 1
|
||||||
|
// Inactive 2
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleItem_Valid() {
|
||||||
|
item := NewItem(Active, "Active")
|
||||||
|
fmt.Println(item.Valid())
|
||||||
|
|
||||||
|
invalidItem := NewItem(Unknown, "")
|
||||||
|
fmt.Println(invalidItem.Valid())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// true
|
||||||
|
// false
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleItem_MarshalJSON() {
|
||||||
|
item := NewItem(Active, "Active")
|
||||||
|
data, _ := item.MarshalJSON()
|
||||||
|
fmt.Println(string(data))
|
||||||
|
|
||||||
|
var unmarshaledItem Item[Status]
|
||||||
|
_ = unmarshaledItem.UnmarshalJSON(data)
|
||||||
|
fmt.Println(unmarshaledItem.Name(), unmarshaledItem.Value())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// {"name":"Active","value":1}
|
||||||
|
// Active 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleRegistry_Add() {
|
||||||
|
registry := NewRegistry[Status]()
|
||||||
|
item1 := NewItem(Active, "Active")
|
||||||
|
item2 := NewItem(Inactive, "Inactive")
|
||||||
|
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
if item, found := registry.GetByValue(Active); found {
|
||||||
|
fmt.Println("Found by value:", item.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
if item, found := registry.GetByName("Inactive"); found {
|
||||||
|
fmt.Println("Found by name:", item.Value())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Found by value: Active
|
||||||
|
// Found by name: 2
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleRegistry_Remove() {
|
||||||
|
registry := NewRegistry[Status]()
|
||||||
|
item1 := NewItem(Active, "Active")
|
||||||
|
|
||||||
|
registry.Add(item1)
|
||||||
|
fmt.Println("Size before removal:", registry.Size())
|
||||||
|
|
||||||
|
removed := registry.Remove(Active)
|
||||||
|
fmt.Println("Removed:", removed)
|
||||||
|
fmt.Println("Size after removal:", registry.Size())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Size before removal: 1
|
||||||
|
// Removed: true
|
||||||
|
// Size after removal: 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleRegistry_Update() {
|
||||||
|
registry := NewRegistry[Status]()
|
||||||
|
item1 := NewItem(Active, "Active")
|
||||||
|
|
||||||
|
registry.Add(item1)
|
||||||
|
updated := registry.Update(Active, "Activated")
|
||||||
|
fmt.Println("Updated:", updated)
|
||||||
|
|
||||||
|
if item, found := registry.GetByValue(Active); found {
|
||||||
|
fmt.Println("New name:", item.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Updated: true
|
||||||
|
// New name: Activated
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleRegistry_Items() {
|
||||||
|
registry := NewRegistry[Status]()
|
||||||
|
item1 := NewItem(Active, "Active")
|
||||||
|
item2 := NewItem(Inactive, "Inactive")
|
||||||
|
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
for _, item := range registry.Items() {
|
||||||
|
fmt.Println(item.Name(), item.Value())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Active 1
|
||||||
|
// Inactive 2
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleRegistry_Contains() {
|
||||||
|
registry := NewRegistry[Status]()
|
||||||
|
item := NewItem(Active, "Active")
|
||||||
|
registry.Add(item)
|
||||||
|
|
||||||
|
fmt.Println(registry.Contains(Active))
|
||||||
|
fmt.Println(registry.Contains(Inactive))
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// true
|
||||||
|
// false
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleRegistry_Size() {
|
||||||
|
registry := NewRegistry[Status]()
|
||||||
|
fmt.Println("Initial size:", registry.Size())
|
||||||
|
|
||||||
|
item1 := NewItem(Active, "Active")
|
||||||
|
item2 := NewItem(Inactive, "Inactive")
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
fmt.Println("Size after adding items:", registry.Size())
|
||||||
|
|
||||||
|
registry.Remove(Active)
|
||||||
|
fmt.Println("Size after removing an item:", registry.Size())
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Initial size: 0
|
||||||
|
// Size after adding items: 2
|
||||||
|
// Size after removing an item: 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleRegistry_Range() {
|
||||||
|
registry := NewRegistry[Status]()
|
||||||
|
item1 := NewItem(Active, "Active")
|
||||||
|
item2 := NewItem(Inactive, "Inactive")
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
registry.Range(func(item *Item[Status]) bool {
|
||||||
|
fmt.Println(item.Name(), item.Value())
|
||||||
|
return true // continue iteration
|
||||||
|
})
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Active 1
|
||||||
|
// Inactive 2
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleRegistry_SortedItems() {
|
||||||
|
registry := NewRegistry[Status]()
|
||||||
|
item1 := NewItem(Inactive, "Inactive")
|
||||||
|
item2 := NewItem(Active, "Active")
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
for _, item := range registry.SortedItems(func(i1, i2 *Item[Status]) bool {
|
||||||
|
return i1.value < i2.value
|
||||||
|
}) {
|
||||||
|
fmt.Println(item.Name(), item.Value())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Active 1
|
||||||
|
// Inactive 2
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleRegistry_Filter() {
|
||||||
|
registry := NewRegistry[Status]()
|
||||||
|
item1 := NewItem(Active, "Active")
|
||||||
|
item2 := NewItem(Inactive, "Inactive")
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
activeItems := registry.Filter(func(item *Item[Status]) bool {
|
||||||
|
return item.Value() == Active
|
||||||
|
})
|
||||||
|
|
||||||
|
for _, item := range activeItems {
|
||||||
|
fmt.Println(item.Name(), item.Value())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Active 1
|
||||||
|
}
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
// Copyright 2025 dudaodong@gmail.com. All rights resulterved.
|
||||||
|
// Use of this source code is governed by MIT license
|
||||||
|
|
||||||
|
package enum
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/duke-git/lancet/v2/internal"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Unknown Status = iota
|
||||||
|
Active
|
||||||
|
Inactive
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestNewItemsFromPairs(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
assert := internal.NewAssert(t, "TestNewItemsFromPairs")
|
||||||
|
|
||||||
|
items := NewItemsFromPairs(
|
||||||
|
Pair[Status]{Value: Active, Name: "Active"},
|
||||||
|
Pair[Status]{Value: Inactive, Name: "Inactive"},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert.Equal(2, len(items))
|
||||||
|
assert.Equal(Active, items[0].Value())
|
||||||
|
assert.Equal("Active", items[0].Name())
|
||||||
|
assert.Equal(Inactive, items[1].Value())
|
||||||
|
assert.Equal("Inactive", items[1].Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestItem_Valid(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
assert := internal.NewAssert(t, "TestItem_Valid")
|
||||||
|
|
||||||
|
item := NewItem(Active, "Active")
|
||||||
|
assert.Equal(true, item.Valid())
|
||||||
|
|
||||||
|
invalidItem := NewItem(Unknown, "")
|
||||||
|
assert.Equal(false, invalidItem.Valid())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestItem_MarshalJSON(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
assert := internal.NewAssert(t, "TestItem_MarshalJSON")
|
||||||
|
|
||||||
|
item := NewItem(Active, "Active")
|
||||||
|
data, err := item.MarshalJSON()
|
||||||
|
assert.IsNil(err)
|
||||||
|
assert.Equal("{\"name\":\"Active\",\"value\":1}", string(data))
|
||||||
|
|
||||||
|
var unmarshaledItem Item[Status]
|
||||||
|
err = unmarshaledItem.UnmarshalJSON(data)
|
||||||
|
assert.IsNil(err)
|
||||||
|
assert.Equal(item.Value(), unmarshaledItem.Value())
|
||||||
|
assert.Equal(item.Name(), unmarshaledItem.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistry_AddAndGet(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
assert := internal.NewAssert(t, "TestRegistry_AddAndGet")
|
||||||
|
|
||||||
|
registry := NewRegistry[Status]()
|
||||||
|
item1 := NewItem(Active, "Active")
|
||||||
|
item2 := NewItem(Inactive, "Inactive")
|
||||||
|
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
assert.Equal(2, registry.Size())
|
||||||
|
|
||||||
|
item, ok := registry.GetByValue(Active)
|
||||||
|
assert.Equal(true, ok)
|
||||||
|
assert.Equal("Active", item.Name())
|
||||||
|
|
||||||
|
item, ok = registry.GetByName("Inactive")
|
||||||
|
assert.Equal(true, ok)
|
||||||
|
assert.Equal(Inactive, item.Value())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistry_Remove(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
assert := internal.NewAssert(t, "TestRegistry_Remove")
|
||||||
|
|
||||||
|
registry := NewRegistry[Status]()
|
||||||
|
item1 := NewItem(Active, "Active")
|
||||||
|
item2 := NewItem(Inactive, "Inactive")
|
||||||
|
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
assert.Equal(2, registry.Size())
|
||||||
|
|
||||||
|
removed := registry.Remove(Active)
|
||||||
|
assert.Equal(true, removed)
|
||||||
|
assert.Equal(1, registry.Size())
|
||||||
|
|
||||||
|
_, ok := registry.GetByValue(Active)
|
||||||
|
assert.Equal(false, ok)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistry_Update(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
assert := internal.NewAssert(t, "TestRegistry_Update")
|
||||||
|
|
||||||
|
registry := NewRegistry[Status]()
|
||||||
|
item1 := NewItem(Active, "Active")
|
||||||
|
registry.Add(item1)
|
||||||
|
|
||||||
|
updated := registry.Update(Active, "Activated")
|
||||||
|
assert.Equal(true, updated)
|
||||||
|
|
||||||
|
item, ok := registry.GetByValue(Active)
|
||||||
|
assert.Equal(true, ok)
|
||||||
|
assert.Equal("Activated", item.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistry_Contains(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
assert := internal.NewAssert(t, "TestRegistry_Contains")
|
||||||
|
|
||||||
|
registry := NewRegistry[Status]()
|
||||||
|
item1 := NewItem(Active, "Active")
|
||||||
|
registry.Add(item1)
|
||||||
|
|
||||||
|
assert.Equal(true, registry.Contains(Active))
|
||||||
|
assert.Equal(false, registry.Contains(Inactive))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistry_Range(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
assert := internal.NewAssert(t, "TestRegistry_Range")
|
||||||
|
|
||||||
|
registry := NewRegistry[Status]()
|
||||||
|
item1 := NewItem(Active, "Active")
|
||||||
|
item2 := NewItem(Inactive, "Inactive")
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
var values []Status
|
||||||
|
registry.Range(func(item *Item[Status]) bool {
|
||||||
|
values = append(values, item.Value())
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
|
||||||
|
assert.Equal(2, len(values))
|
||||||
|
assert.Equal(Active, values[0])
|
||||||
|
assert.Equal(Inactive, values[1])
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistry_SortedItems(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
assert := internal.NewAssert(t, "TestRegistry_SortedItems")
|
||||||
|
|
||||||
|
registry := NewRegistry[Status]()
|
||||||
|
item1 := NewItem(Inactive, "Inactive")
|
||||||
|
item2 := NewItem(Active, "Active")
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
sortedItems := registry.SortedItems(func(i1, i2 *Item[Status]) bool {
|
||||||
|
return i1.value < i2.value
|
||||||
|
})
|
||||||
|
|
||||||
|
assert.Equal(2, len(sortedItems))
|
||||||
|
assert.Equal(Active, sortedItems[0].Value())
|
||||||
|
assert.Equal(Inactive, sortedItems[1].Value())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistry_Filter(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
assert := internal.NewAssert(t, "TestRegistry_Filter")
|
||||||
|
|
||||||
|
registry := NewRegistry[Status]()
|
||||||
|
item1 := NewItem(Active, "Active")
|
||||||
|
item2 := NewItem(Inactive, "Inactive")
|
||||||
|
registry.Add(item1, item2)
|
||||||
|
|
||||||
|
filteredItems := registry.Filter(func(item *Item[Status]) bool {
|
||||||
|
return item.Value() == Active
|
||||||
|
})
|
||||||
|
|
||||||
|
assert.Equal(1, len(filteredItems))
|
||||||
|
assert.Equal(Active, filteredItems[0].Value())
|
||||||
|
}
|
||||||
@@ -21,7 +21,7 @@ type EventBus[T any] struct {
|
|||||||
// listeners map[string][]*EventListener[T]
|
// listeners map[string][]*EventListener[T]
|
||||||
listeners sync.Map
|
listeners sync.Map
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
errorHandler func(err error)
|
errorHandler func(topic string, err error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// EventListener is the struct that holds the listener function and its priority.
|
// EventListener is the struct that holds the listener function and its priority.
|
||||||
@@ -117,7 +117,7 @@ func (eb *EventBus[T]) Publish(event Event[T]) {
|
|||||||
func (eb *EventBus[T]) publishToListener(listener *EventListener[T], event Event[T]) {
|
func (eb *EventBus[T]) publishToListener(listener *EventListener[T], event Event[T]) {
|
||||||
defer func() {
|
defer func() {
|
||||||
if r := recover(); r != nil && eb.errorHandler != nil {
|
if r := recover(); r != nil && eb.errorHandler != nil {
|
||||||
eb.errorHandler(fmt.Errorf("%v", r))
|
eb.errorHandler(event.Topic, fmt.Errorf("%v", r))
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
@@ -126,7 +126,7 @@ func (eb *EventBus[T]) publishToListener(listener *EventListener[T], event Event
|
|||||||
|
|
||||||
// SetErrorHandler sets the error handler function.
|
// SetErrorHandler sets the error handler function.
|
||||||
// Play: https://go.dev/play/p/gmB0gnFe5mc
|
// Play: https://go.dev/play/p/gmB0gnFe5mc
|
||||||
func (eb *EventBus[T]) SetErrorHandler(handler func(err error)) {
|
func (eb *EventBus[T]) SetErrorHandler(handler func(topic string, err error)) {
|
||||||
eb.errorHandler = handler
|
eb.errorHandler = handler
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -189,8 +189,8 @@ func ExampleEventBus_GetListenersCount() {
|
|||||||
func ExampleEventBus_SetErrorHandler() {
|
func ExampleEventBus_SetErrorHandler() {
|
||||||
eb := NewEventBus[int]()
|
eb := NewEventBus[int]()
|
||||||
|
|
||||||
eb.SetErrorHandler(func(err error) {
|
eb.SetErrorHandler(func(topic string, err error) {
|
||||||
fmt.Println(err)
|
fmt.Println(topic, err)
|
||||||
})
|
})
|
||||||
|
|
||||||
eb.Subscribe("event1", func(eventData int) {
|
eb.Subscribe("event1", func(eventData int) {
|
||||||
@@ -200,7 +200,7 @@ func ExampleEventBus_SetErrorHandler() {
|
|||||||
eb.Publish(Event[int]{Topic: "event1", Payload: 1})
|
eb.Publish(Event[int]{Topic: "event1", Payload: 1})
|
||||||
|
|
||||||
// Output:
|
// Output:
|
||||||
// error
|
// event1 error
|
||||||
}
|
}
|
||||||
|
|
||||||
func ExampleEventBus_GetAllListenersCount() {
|
func ExampleEventBus_GetAllListenersCount() {
|
||||||
|
|||||||
@@ -114,7 +114,8 @@ func TestEventBus_ErrorHandler(t *testing.T) {
|
|||||||
|
|
||||||
eb := NewEventBus[string]()
|
eb := NewEventBus[string]()
|
||||||
|
|
||||||
eb.SetErrorHandler(func(err error) {
|
eb.SetErrorHandler(func(topic string, err error) {
|
||||||
|
assert.Equal("event1", topic)
|
||||||
assert.Equal("error", err.Error())
|
assert.Equal("error", err.Error())
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
+18
-31
@@ -24,9 +24,10 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/duke-git/lancet/v2/validator"
|
|
||||||
"golang.org/x/text/encoding/simplifiedchinese"
|
"golang.org/x/text/encoding/simplifiedchinese"
|
||||||
"golang.org/x/text/transform"
|
"golang.org/x/text/transform"
|
||||||
|
|
||||||
|
"github.com/duke-git/lancet/v2/validator"
|
||||||
)
|
)
|
||||||
|
|
||||||
// FileReader is a reader supporting offset seeking and reading one
|
// FileReader is a reader supporting offset seeking and reading one
|
||||||
@@ -228,6 +229,13 @@ func CopyFile(srcPath string, dstPath string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer srcFile.Close()
|
defer srcFile.Close()
|
||||||
|
srcInfo, err := srcFile.Stat()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if dstInfo, err := os.Stat(dstPath); err == nil && os.SameFile(srcInfo, dstInfo) {
|
||||||
|
return errors.New("source and destination are the same file")
|
||||||
|
}
|
||||||
|
|
||||||
distFile, err := os.Create(dstPath)
|
distFile, err := os.Create(dstPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -283,21 +291,18 @@ func ReadFileByLine(path string) ([]string, error) {
|
|||||||
}
|
}
|
||||||
defer f.Close()
|
defer f.Close()
|
||||||
|
|
||||||
|
scanner := bufio.NewScanner(f)
|
||||||
result := make([]string, 0)
|
result := make([]string, 0)
|
||||||
buf := bufio.NewReader(f)
|
|
||||||
|
|
||||||
for {
|
for scanner.Scan() {
|
||||||
line, _, err := buf.ReadLine()
|
l := scanner.Text()
|
||||||
l := string(line)
|
|
||||||
if err == io.EOF {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
result = append(result, l)
|
result = append(result, l)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := scanner.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -756,6 +761,8 @@ func WriteCsvFile(filepath string, records [][]string, append bool, delimiter ..
|
|||||||
|
|
||||||
if append {
|
if append {
|
||||||
flag = flag | os.O_APPEND
|
flag = flag | os.O_APPEND
|
||||||
|
} else {
|
||||||
|
flag = flag | os.O_TRUNC
|
||||||
}
|
}
|
||||||
|
|
||||||
f, err := os.OpenFile(filepath, flag, 0644)
|
f, err := os.OpenFile(filepath, flag, 0644)
|
||||||
@@ -773,13 +780,6 @@ func WriteCsvFile(filepath string, records [][]string, append bool, delimiter ..
|
|||||||
writer.Comma = ','
|
writer.Comma = ','
|
||||||
}
|
}
|
||||||
|
|
||||||
// 遍历所有记录并处理包含分隔符或双引号的单元格
|
|
||||||
for i := range records {
|
|
||||||
for j := range records[i] {
|
|
||||||
records[i][j] = escapeCSVField(records[i][j], writer.Comma)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return writer.WriteAll(records)
|
return writer.WriteAll(records)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -838,19 +838,6 @@ func ReadFile(path string) (reader io.ReadCloser, closeFn func(), err error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// escapeCSVField 处理单元格内容,如果包含分隔符,则用双引号包裹
|
|
||||||
func escapeCSVField(field string, delimiter rune) string {
|
|
||||||
// 替换所有的双引号为两个双引号
|
|
||||||
escapedField := strings.ReplaceAll(field, "\"", "\"\"")
|
|
||||||
|
|
||||||
// 如果字段包含分隔符、双引号或换行符,用双引号包裹整个字段
|
|
||||||
if strings.ContainsAny(escapedField, string(delimiter)+"\"\n") {
|
|
||||||
escapedField = fmt.Sprintf("\"%s\"", escapedField)
|
|
||||||
}
|
|
||||||
|
|
||||||
return escapedField
|
|
||||||
}
|
|
||||||
|
|
||||||
// WriteMapsToCsv write slice of map to csv file.
|
// WriteMapsToCsv write slice of map to csv file.
|
||||||
// Play: https://go.dev/play/p/umAIomZFV1c
|
// Play: https://go.dev/play/p/umAIomZFV1c
|
||||||
// filepath: Path to the CSV file.
|
// filepath: Path to the CSV file.
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
"os"
|
"os"
|
||||||
"runtime"
|
"runtime"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -430,7 +432,12 @@ func ExampleWriteBytesToFile() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func ExampleReadFile() {
|
func ExampleReadFile() {
|
||||||
reader, fn, err := ReadFile("https://httpbin.org/robots.txt")
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fmt.Fprint(w, "User-agent: *\nDisallow: /deny\n")
|
||||||
|
}))
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
reader, fn, err := ReadFile(ts.URL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
+68
-2
@@ -1,7 +1,10 @@
|
|||||||
package fileutil
|
package fileutil
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"runtime"
|
"runtime"
|
||||||
@@ -136,6 +139,34 @@ func TestCopyFile(t *testing.T) {
|
|||||||
os.Remove(destFile)
|
os.Remove(destFile)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCopyFilePreservesSource(t *testing.T) {
|
||||||
|
for _, mode := range []string{"same", "hardlink", "different"} {
|
||||||
|
t.Run(mode, func(t *testing.T) {
|
||||||
|
assert := internal.NewAssert(t, "TestCopyFilePreservesSource")
|
||||||
|
src := filepath.Join(t.TempDir(), "source.txt")
|
||||||
|
assert.IsNil(os.WriteFile(src, []byte("keep this content"), 0600))
|
||||||
|
dst := src + ".copy"
|
||||||
|
if mode == "same" {
|
||||||
|
dst = src
|
||||||
|
} else if mode == "hardlink" {
|
||||||
|
if err := os.Link(src, dst); err != nil {
|
||||||
|
t.Skipf("hard links unavailable: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
err := CopyFile(src, dst)
|
||||||
|
if (err != nil) != (mode != "different") {
|
||||||
|
t.Errorf("unexpected copy result: %v", err)
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(src)
|
||||||
|
assert.IsNil(err)
|
||||||
|
assert.Equal("keep this content", string(data))
|
||||||
|
data, err = os.ReadFile(dst)
|
||||||
|
assert.IsNil(err)
|
||||||
|
assert.Equal("keep this content", string(data))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestReadFileToString(t *testing.T) {
|
func TestReadFileToString(t *testing.T) {
|
||||||
assert := internal.NewAssert(t, "TestReadFileToString")
|
assert := internal.NewAssert(t, "TestReadFileToString")
|
||||||
|
|
||||||
@@ -415,6 +446,36 @@ func TestWriteCsvFile(t *testing.T) {
|
|||||||
// RemoveFile(csvFilePath)
|
// RemoveFile(csvFilePath)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestWriteCsvFileRoundTrip(t *testing.T) {
|
||||||
|
for _, delimiter := range []rune{',', ';'} {
|
||||||
|
t.Run(string(delimiter), func(t *testing.T) {
|
||||||
|
assert := internal.NewAssert(t, "TestWriteCsvFileRoundTrip")
|
||||||
|
path := filepath.Join(t.TempDir(), "quoted.csv")
|
||||||
|
want := [][]string{{"a,b;c", "\"quoted\"", "two\nlines"}}
|
||||||
|
records := [][]string{append([]string(nil), want[0]...)}
|
||||||
|
assert.IsNil(WriteCsvFile(path, records, false, delimiter))
|
||||||
|
got, err := ReadCsvFile(path, delimiter)
|
||||||
|
assert.IsNil(err)
|
||||||
|
assert.Equal(want, got)
|
||||||
|
assert.Equal(want, records)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWriteCsvFileOverwriteAndAppend(t *testing.T) {
|
||||||
|
assert := internal.NewAssert(t, "TestWriteCsvFileOverwriteAndAppend")
|
||||||
|
path := filepath.Join(t.TempDir(), "overwrite.csv")
|
||||||
|
assert.IsNil(os.WriteFile(path, []byte(strings.Repeat("old,value\n", 10)), 0600))
|
||||||
|
assert.IsNil(WriteCsvFile(path, [][]string{{"new", "row"}}, false))
|
||||||
|
got, err := ReadCsvFile(path)
|
||||||
|
assert.IsNil(err)
|
||||||
|
assert.Equal([][]string{{"new", "row"}}, got)
|
||||||
|
assert.IsNil(WriteCsvFile(path, [][]string{{"appended", "row"}}, true))
|
||||||
|
got, err = ReadCsvFile(path)
|
||||||
|
assert.IsNil(err)
|
||||||
|
assert.Equal([][]string{{"new", "row"}, {"appended", "row"}}, got)
|
||||||
|
}
|
||||||
|
|
||||||
func TestWriteMapsToCsv(t *testing.T) {
|
func TestWriteMapsToCsv(t *testing.T) {
|
||||||
assert := internal.NewAssert(t, "TestWriteMapsToCSV")
|
assert := internal.NewAssert(t, "TestWriteMapsToCSV")
|
||||||
|
|
||||||
@@ -516,9 +577,14 @@ func TestWriteBytesToFile(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestReadFile(t *testing.T) {
|
func TestReadFile(t *testing.T) {
|
||||||
reader, close, err := ReadFile("https://httpbin.org/robots.txt")
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fmt.Fprint(w, "User-agent: *\nDisallow: /deny\n")
|
||||||
|
}))
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
reader, close, err := ReadFile(ts.URL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fail()
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
defer close()
|
defer close()
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,494 @@
|
|||||||
|
// Package formatter implements some functions to format string, struct.
|
||||||
|
package formatter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AddressInfo represents the parsed address information including user details and location.
|
||||||
|
// AddressInfo 表示解析后的地址信息,包括用户详细信息和位置信息
|
||||||
|
type AddressInfo struct {
|
||||||
|
Name string `json:"name"` // Name of the recipient / 姓名
|
||||||
|
Mobile string `json:"mobile"` // Mobile phone number or landline / 手机号或座机
|
||||||
|
IDN string `json:"idn"` // ID card number / 身份证号
|
||||||
|
Postcode string `json:"postcode"` // Postal code / 邮编
|
||||||
|
Province string `json:"province"` // Province / 省
|
||||||
|
City string `json:"city"` // City / 市
|
||||||
|
Region string `json:"region"` // District or county / 区/县
|
||||||
|
Street string `json:"street"` // Street address / 街道详细地址
|
||||||
|
Addr string `json:"addr"` // Original address string / 原始地址字符串
|
||||||
|
}
|
||||||
|
|
||||||
|
// fuzzyResult represents the result of fuzzy address parsing.
|
||||||
|
// fuzzyResult 表示模糊地址解析的结果
|
||||||
|
type fuzzyResult struct {
|
||||||
|
A1 string // Province level / 省级
|
||||||
|
A2 string // City level / 市级
|
||||||
|
A3 string // District/County level / 区/县级
|
||||||
|
Street string // Street address / 街道地址
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseCNAddress parses a Chinese address string intelligently and extracts structured information.
|
||||||
|
// It can parse addresses with or without user information (name, phone, ID card, etc.).
|
||||||
|
// When withUser is true, it extracts user information from the address string.
|
||||||
|
// When withUser is false, it only parses the location information.
|
||||||
|
// The function handles various address formats including:
|
||||||
|
// - Standard format: "Province City District Street"
|
||||||
|
// - Compact format: "Name Phone Province City District Street"
|
||||||
|
// - With keywords: "Name: xxx Phone: xxx Address: xxx"
|
||||||
|
// - County-level cities: "Province City CountyCity District" (e.g., "河北省石家庄市新乐市")
|
||||||
|
// ParseCNAddress 智能解析中国地址字符串并提取结构化信息。
|
||||||
|
// 可以解析带或不带用户信息(姓名、电话、身份证等)的地址。
|
||||||
|
// 当 withUser 为 true 时,从地址字符串中提取用户信息。
|
||||||
|
// 当 withUser 为 false 时,仅解析位置信息。
|
||||||
|
// 该函数处理多种地址格式,包括:
|
||||||
|
// - 标准格式:"省 市 区 街道"
|
||||||
|
// - 紧凑格式:"姓名 电话 省 市 区 街道"
|
||||||
|
// - 带关键词:"姓名:xxx 电话:xxx 地址:xxx"
|
||||||
|
// - 县级市:"省 市 县级市 区"(如"河北省石家庄市新乐市")
|
||||||
|
func ParseCNAddress(str string, withUser bool) *AddressInfo {
|
||||||
|
result := &AddressInfo{}
|
||||||
|
|
||||||
|
if withUser {
|
||||||
|
ParsePersonInfo := ParsePersonInfo(str)
|
||||||
|
result = ParsePersonInfo
|
||||||
|
} else {
|
||||||
|
result.Addr = str
|
||||||
|
}
|
||||||
|
|
||||||
|
fuzz := fuzz(result.Addr)
|
||||||
|
parse := parse(fuzz.A1, fuzz.A2, fuzz.A3)
|
||||||
|
|
||||||
|
result.Province = parse.Province
|
||||||
|
result.City = parse.City
|
||||||
|
result.Region = parse.Region
|
||||||
|
|
||||||
|
// 提取街道地址:从原始地址中找到区/县的位置,提取后面的内容
|
||||||
|
if result.Region != "" && result.Addr != "" {
|
||||||
|
// 在原始地址中查找区/县的位置(转换为rune数组以正确处理中文)
|
||||||
|
addrRunes := []rune(result.Addr)
|
||||||
|
regionRunes := []rune(result.Region)
|
||||||
|
regionPos := mbStrpos(result.Addr, result.Region)
|
||||||
|
|
||||||
|
if regionPos != -1 {
|
||||||
|
// 提取区/县后面的内容作为街道地址
|
||||||
|
streetStart := regionPos + len(regionRunes)
|
||||||
|
if streetStart < len(addrRunes) {
|
||||||
|
result.Street = string(addrRunes[streetStart:])
|
||||||
|
}
|
||||||
|
} else if fuzz.Street != "" {
|
||||||
|
// 如果没找到区/县,使用fuzz返回的街道
|
||||||
|
result.Street = fuzz.Street
|
||||||
|
}
|
||||||
|
} else if fuzz.Street != "" {
|
||||||
|
result.Street = fuzz.Street
|
||||||
|
}
|
||||||
|
|
||||||
|
// 清理街道地址中的重复省市区信息(可能存在部分匹配的残留)
|
||||||
|
result.Street = strings.ReplaceAll(result.Street, result.Region, "")
|
||||||
|
result.Street = strings.ReplaceAll(result.Street, result.City, "")
|
||||||
|
result.Street = strings.ReplaceAll(result.Street, result.Province, "")
|
||||||
|
// 清理街道地址中的残留片段(如"自治区直辖县级市"被替换后的残留)
|
||||||
|
result.Street = strings.ReplaceAll(result.Street, "自治区直辖县级市", "")
|
||||||
|
result.Street = strings.ReplaceAll(result.Street, "直辖县级市", "")
|
||||||
|
result.Street = strings.TrimSpace(result.Street)
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParsePersonInfo extracts user information (name, phone, ID card, postal code) from an address string.
|
||||||
|
// It separates personal information from the address, supporting various formats:
|
||||||
|
// - Labeled format: "Name: xxx Phone: xxx Address: xxx"
|
||||||
|
// - Compact format: "Name Phone Address" (e.g., "张三13800138000北京市朝阳区")
|
||||||
|
// - With separators: using colons, commas, newlines as delimiters
|
||||||
|
// Returns an AddressInfo with extracted user information and cleaned address string in Addr field.
|
||||||
|
// ParsePersonInfo 从地址字符串中提取用户信息(姓名、电话、身份证、邮编)。
|
||||||
|
// 将个人信息与地址分离,支持多种格式:
|
||||||
|
// - 带标签格式:"姓名:xxx 电话:xxx 地址:xxx"
|
||||||
|
// - 紧凑格式:"姓名 电话 地址"(如"张三13800138000北京市朝阳区")
|
||||||
|
// - 带分隔符:使用冒号、逗号、换行符作为分隔符
|
||||||
|
// 返回包含提取的用户信息和清理后地址字符串(在 Addr 字段中)的 AddressInfo。
|
||||||
|
func ParsePersonInfo(str string) *AddressInfo {
|
||||||
|
compose := &AddressInfo{}
|
||||||
|
|
||||||
|
// 先尝试提取带标签的信息
|
||||||
|
// 提取姓名 (支持: 姓名:xxx, 收货人:xxx, 收件人:xxx)
|
||||||
|
nameRe := regexp.MustCompile(`(?:姓名|收货人|收件人)[::]\s*([^\s\d\n]+)`)
|
||||||
|
if match := nameRe.FindStringSubmatch(str); len(match) > 1 {
|
||||||
|
compose.Name = strings.TrimSpace(match[1])
|
||||||
|
str = nameRe.ReplaceAllString(str, " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 提取手机号或座机号 (支持: 电话:xxx, 手机:xxx, 联系电话:xxx)
|
||||||
|
phoneRe := regexp.MustCompile(`(?:电话|手机号码|手机|联系电话)[::]\s*([\d\-]+)`)
|
||||||
|
if match := phoneRe.FindStringSubmatch(str); len(match) > 1 {
|
||||||
|
compose.Mobile = strings.TrimSpace(match[1])
|
||||||
|
str = phoneRe.ReplaceAllString(str, " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 提取所在地区 (支持: 所在地区:xxx)
|
||||||
|
regionRe := regexp.MustCompile(`所在地区[::]\s*([^\n]+)`)
|
||||||
|
if match := regionRe.FindStringSubmatch(str); len(match) > 1 {
|
||||||
|
// 将所在地区保留在字符串中,不删除
|
||||||
|
// str 保持不变,让后续的地址解析处理
|
||||||
|
}
|
||||||
|
|
||||||
|
// 提取详细地址 (支持: 详细地址:xxx, 收货地址:xxx, 地址:xxx)
|
||||||
|
addrRe := regexp.MustCompile(`(?:详细地址|收货地址|地址)[::]\s*([^\n]+)`)
|
||||||
|
if match := addrRe.FindStringSubmatch(str); len(match) > 1 {
|
||||||
|
// 保留详细地址在字符串中
|
||||||
|
str = addrRe.ReplaceAllString(str, " "+match[1])
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果还没有提取到姓名和手机号,尝试识别紧凑格式 (如: 马云13593464918陕西省...)
|
||||||
|
if compose.Name == "" && compose.Mobile == "" {
|
||||||
|
// 匹配: 2-4个汉字 + 7-12位数字 + 剩余内容
|
||||||
|
compactRe := regexp.MustCompile(`^([\x{4e00}-\x{9fa5}]{2,4})(\d{7,12})(.*)$`)
|
||||||
|
if match := compactRe.FindStringSubmatch(str); len(match) > 3 {
|
||||||
|
compose.Name = match[1]
|
||||||
|
compose.Mobile = match[2]
|
||||||
|
str = match[3] // 保留剩余的地址部分
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 替换常见的地址关键词为空格
|
||||||
|
replacements := map[string]string{
|
||||||
|
"收货地址": " ", "详细地址": " ", "地址": " ", "收货人": " ",
|
||||||
|
"收件人": " ", "收货": " ", "所在地区": " ", "邮编": " ",
|
||||||
|
"电话": " ", "手机号码": " ", "身份证号码": " ", "身份证号": " ",
|
||||||
|
"身份证": " ", "姓名": " ", "联系电话": " ", "手机": " ",
|
||||||
|
":": " ", ":": " ", ";": " ", ";": " ",
|
||||||
|
",": " ", ",": " ", "。": " ", "\n": " ", "\r": " ",
|
||||||
|
}
|
||||||
|
|
||||||
|
for old, new := range replacements {
|
||||||
|
str = strings.ReplaceAll(str, old, new)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 将多个空格合并为一个
|
||||||
|
spaceRe := regexp.MustCompile(`\s{1,}`)
|
||||||
|
str = spaceRe.ReplaceAllString(str, " ")
|
||||||
|
|
||||||
|
// 处理座机号格式 (如: 800-8585222)
|
||||||
|
telRe := regexp.MustCompile(`(\d{3,4})-(\d{6,8})`)
|
||||||
|
str = telRe.ReplaceAllString(str, "$1$2")
|
||||||
|
|
||||||
|
// 提取身份证号 (18位或17位+X)
|
||||||
|
idnRe := regexp.MustCompile(`\d{18}|\d{17}[Xx]`)
|
||||||
|
if match := idnRe.FindString(str); match != "" {
|
||||||
|
compose.IDN = strings.ToUpper(match)
|
||||||
|
str = strings.ReplaceAll(str, match, "")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果之前没有提取到手机号,现在提取
|
||||||
|
if compose.Mobile == "" {
|
||||||
|
mobileRe := regexp.MustCompile(`\d{7,12}`)
|
||||||
|
if match := mobileRe.FindString(str); match != "" {
|
||||||
|
compose.Mobile = match
|
||||||
|
str = strings.ReplaceAll(str, match, "")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 已经提取过手机号,从字符串中删除
|
||||||
|
str = strings.ReplaceAll(str, compose.Mobile, "")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 提取邮编
|
||||||
|
postcodeRe := regexp.MustCompile(`\d{6}`)
|
||||||
|
if match := postcodeRe.FindString(str); match != "" {
|
||||||
|
compose.Postcode = match
|
||||||
|
str = strings.ReplaceAll(str, match, "")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 清理多余空格
|
||||||
|
str = strings.TrimSpace(spaceRe.ReplaceAllString(str, " "))
|
||||||
|
|
||||||
|
// 如果之前没有提取到姓名,现在提取
|
||||||
|
if compose.Name == "" {
|
||||||
|
// 提取姓名(取最短的词作为姓名,排除空字符串)
|
||||||
|
splitArr := strings.Split(str, " ")
|
||||||
|
if len(splitArr) > 0 {
|
||||||
|
for _, value := range splitArr {
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
if value == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if compose.Name == "" {
|
||||||
|
compose.Name = value
|
||||||
|
} else if utf8.RuneCountInString(value) < utf8.RuneCountInString(compose.Name) && utf8.RuneCountInString(value) >= 2 {
|
||||||
|
compose.Name = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if compose.Name != "" {
|
||||||
|
str = strings.TrimSpace(strings.ReplaceAll(str, compose.Name, ""))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 已经提取过姓名,从字符串中删除
|
||||||
|
str = strings.TrimSpace(strings.ReplaceAll(str, compose.Name, ""))
|
||||||
|
}
|
||||||
|
|
||||||
|
compose.Addr = str
|
||||||
|
return compose
|
||||||
|
}
|
||||||
|
|
||||||
|
// fuzz 根据统计规律分析出二三级地址
|
||||||
|
func fuzz(addr string) *fuzzyResult {
|
||||||
|
addrOrigin := addr
|
||||||
|
addr = strings.ReplaceAll(addr, " ", "")
|
||||||
|
addr = strings.ReplaceAll(addr, ",", "")
|
||||||
|
// 先替换"自治区直辖县级市"为"市",避免后续"自治区"替换时产生问题
|
||||||
|
addr = strings.ReplaceAll(addr, "自治区直辖县级市", "市")
|
||||||
|
addr = strings.ReplaceAll(addr, "自治区", "省")
|
||||||
|
addr = strings.ReplaceAll(addr, "自治州", "州")
|
||||||
|
addr = strings.ReplaceAll(addr, "小区", "")
|
||||||
|
addr = strings.ReplaceAll(addr, "校区", "")
|
||||||
|
// 过滤"市辖区" - 这是一个行政术语占位符,不是真正的区名
|
||||||
|
addr = strings.ReplaceAll(addr, "市辖区", "")
|
||||||
|
|
||||||
|
a1 := ""
|
||||||
|
a2 := ""
|
||||||
|
a3 := ""
|
||||||
|
street := ""
|
||||||
|
|
||||||
|
deep3KeywordPos := -1
|
||||||
|
|
||||||
|
// 判断是否包含县/区/旗
|
||||||
|
countyPos := mbStrpos(addr, "县")
|
||||||
|
districtPos := mbStrpos(addr, "区")
|
||||||
|
bannerPos := mbStrpos(addr, "旗")
|
||||||
|
|
||||||
|
// 只要存在这些关键词就处理,不再限制位置
|
||||||
|
hasEarlyCounty := countyPos != -1
|
||||||
|
hasEarlyDistrict := districtPos != -1
|
||||||
|
hasEarlyBanner := bannerPos != -1
|
||||||
|
|
||||||
|
if hasEarlyCounty || hasEarlyDistrict || hasEarlyBanner {
|
||||||
|
// 优先检查是否存在县级市(如"新乐市")
|
||||||
|
// 如果同时存在"XX市"和"XX区"/"XX县",优先处理"市"
|
||||||
|
hasCountyLevelCity := false
|
||||||
|
if mbStrstr(addr, "市") {
|
||||||
|
// 查找所有"市"的位置
|
||||||
|
cityCount := mbSubstrCount(addr, "市")
|
||||||
|
if cityCount >= 2 {
|
||||||
|
// 找到第二个"市"的位置(可能是县级市)
|
||||||
|
firstCityPos := mbStrpos(addr, "市")
|
||||||
|
// 从第一个"市"之后继续查找
|
||||||
|
addrAfterFirstCity := mbSubstr(addr, firstCityPos+1, utf8.RuneCountInString(addr)-firstCityPos-1)
|
||||||
|
secondCityPos := mbStrpos(addrAfterFirstCity, "市")
|
||||||
|
if secondCityPos != -1 {
|
||||||
|
secondCityAbsPos := firstCityPos + 1 + secondCityPos
|
||||||
|
// 检查第二个"市"后面是否存在"区"或"县"
|
||||||
|
addrAfterSecondCity := mbSubstr(addr, secondCityAbsPos+1, utf8.RuneCountInString(addr)-secondCityAbsPos-1)
|
||||||
|
if mbStrstr(addrAfterSecondCity, "区") || mbStrstr(addrAfterSecondCity, "县") {
|
||||||
|
// 提取两个"市"之间的内容
|
||||||
|
betweenCities := mbSubstr(addr, firstCityPos+1, secondCityAbsPos-firstCityPos)
|
||||||
|
// 检查是否是重复的地名(如"北京市北京市"或"杭州市西湖区杭州市")
|
||||||
|
// 如果两个"市"之间包含"区"或"县",说明不是县级市,而是重复地名
|
||||||
|
if !mbStrstr(betweenCities, "区") && !mbStrstr(betweenCities, "县") {
|
||||||
|
// 第一个"市"及之前的内容
|
||||||
|
firstCityFull := mbSubstr(addr, 0, firstCityPos+1)
|
||||||
|
if betweenCities != firstCityFull {
|
||||||
|
// 不是重复地名,这是县级市
|
||||||
|
a3 = betweenCities
|
||||||
|
deep3KeywordPos = secondCityAbsPos
|
||||||
|
hasCountyLevelCity = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !hasCountyLevelCity {
|
||||||
|
// 处理旗
|
||||||
|
if mbStrstr(addr, "旗") {
|
||||||
|
deep3KeywordPos = mbStrpos(addr, "旗")
|
||||||
|
a3 = mbSubstr(addr, deep3KeywordPos-1, 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理区
|
||||||
|
if mbStrstr(addr, "区") {
|
||||||
|
// 使用第一个"区"(避免重复地名干扰,如"西湖区杭州市西湖区")
|
||||||
|
deep3KeywordPos = mbStrpos(addr, "区")
|
||||||
|
|
||||||
|
if mbStrstr(addr, "市") {
|
||||||
|
// 策略:找到"区"之前的最后一个"市"
|
||||||
|
// 这样可以避免详细地址中的"市"字干扰(如"农贸市场")
|
||||||
|
zonePos := deep3KeywordPos
|
||||||
|
// 从开头到"区"的子串中,查找最后一个"市"
|
||||||
|
addrBeforeZone := mbSubstr(addr, 0, zonePos)
|
||||||
|
cityPos := mbStrripos(addrBeforeZone, "市")
|
||||||
|
if cityPos != -1 {
|
||||||
|
a3 = mbSubstr(addr, cityPos+1, zonePos-cityPos)
|
||||||
|
} else {
|
||||||
|
// 没有找到"市",使用默认逻辑
|
||||||
|
a3 = mbSubstr(addr, deep3KeywordPos-2, 3)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
a3 = mbSubstr(addr, deep3KeywordPos-2, 3)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理县
|
||||||
|
if mbStrstr(addr, "县") {
|
||||||
|
// 使用第一个"县"(避免重复地名干扰)
|
||||||
|
deep3KeywordPos = mbStrpos(addr, "县")
|
||||||
|
if mbStrstr(addr, "市") {
|
||||||
|
// 从开头到"县"的子串中,查找最后一个"市"
|
||||||
|
addrBeforeCounty := mbSubstr(addr, 0, deep3KeywordPos)
|
||||||
|
cityPos := mbStrripos(addrBeforeCounty, "市")
|
||||||
|
if cityPos != -1 {
|
||||||
|
a3 = mbSubstr(addr, cityPos+1, deep3KeywordPos-cityPos)
|
||||||
|
} else {
|
||||||
|
if mbStrstr(addr, "自治县") {
|
||||||
|
a3 = mbSubstr(addr, deep3KeywordPos-6, 7)
|
||||||
|
firstChar := mbSubstr(a3, 0, 1)
|
||||||
|
if firstChar == "省" || firstChar == "市" || firstChar == "州" {
|
||||||
|
a3 = mbSubstr(a3, 1, utf8.RuneCountInString(a3)-1)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
a3 = mbSubstr(addr, deep3KeywordPos-2, 3)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if mbStrstr(addr, "自治县") {
|
||||||
|
a3 = mbSubstr(addr, deep3KeywordPos-6, 7)
|
||||||
|
firstChar := mbSubstr(a3, 0, 1)
|
||||||
|
if firstChar == "省" || firstChar == "市" || firstChar == "州" {
|
||||||
|
a3 = mbSubstr(a3, 1, utf8.RuneCountInString(a3)-1)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
a3 = mbSubstr(addr, deep3KeywordPos-2, 3)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if deep3KeywordPos != -1 {
|
||||||
|
street = mbSubstr(addrOrigin, deep3KeywordPos+1, utf8.RuneCountInString(addrOrigin)-deep3KeywordPos-1)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 处理市
|
||||||
|
if mbStrripos(addr, "市") != -1 {
|
||||||
|
cityCount := mbSubstrCount(addr, "市")
|
||||||
|
if cityCount == 1 {
|
||||||
|
deep3KeywordPos = mbStrripos(addr, "市")
|
||||||
|
a3 = mbSubstr(addr, deep3KeywordPos-2, 3)
|
||||||
|
street = mbSubstr(addrOrigin, deep3KeywordPos+1, utf8.RuneCountInString(addrOrigin)-deep3KeywordPos-1)
|
||||||
|
} else if cityCount >= 2 {
|
||||||
|
deep3KeywordPos = mbStrripos(addr, "市")
|
||||||
|
a3 = mbSubstr(addr, deep3KeywordPos-2, 3)
|
||||||
|
street = mbSubstr(addrOrigin, deep3KeywordPos+1, utf8.RuneCountInString(addrOrigin)-deep3KeywordPos-1)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
a3 = ""
|
||||||
|
street = addr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 提取市级地址
|
||||||
|
if mbStrpos(addr, "市") != -1 || mbStrstr(addr, "盟") || mbStrstr(addr, "州") {
|
||||||
|
tmpPos := -1
|
||||||
|
if tmpPos = mbStrpos(addr, "市"); tmpPos != -1 {
|
||||||
|
// 使用第一个"市"(避免重复地名干扰,如"杭州市西湖区杭州市")
|
||||||
|
// 向前查找省的位置,如果有省就从省后开始,否则从开头开始
|
||||||
|
addrBeforeCity := mbSubstr(addr, 0, tmpPos)
|
||||||
|
provincePos := mbStrripos(addrBeforeCity, "省")
|
||||||
|
startPos := 0
|
||||||
|
if provincePos != -1 {
|
||||||
|
startPos = provincePos + 1
|
||||||
|
}
|
||||||
|
a2 = mbSubstr(addr, startPos, tmpPos-startPos+1)
|
||||||
|
} else if tmpPos = mbStrpos(addr, "盟"); tmpPos != -1 {
|
||||||
|
a2 = mbSubstr(addr, tmpPos-2, 3)
|
||||||
|
} else if mbStrpos(addr, "州") != -1 {
|
||||||
|
if tmpPos = mbStrpos(addr, "自治州"); tmpPos != -1 {
|
||||||
|
a2 = mbSubstr(addr, tmpPos-4, 5)
|
||||||
|
} else {
|
||||||
|
tmpPos = mbStrpos(addr, "州")
|
||||||
|
a2 = mbSubstr(addr, tmpPos-2, 3)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return &fuzzyResult{
|
||||||
|
A1: a1,
|
||||||
|
A2: a2,
|
||||||
|
A3: a3,
|
||||||
|
Street: street,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// parse 智能解析出省市区
|
||||||
|
func parse(a1, a2, a3 string) *AddressInfo {
|
||||||
|
r := &AddressInfo{}
|
||||||
|
|
||||||
|
if a3 == "" {
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
// 在三级地址数据中查找匹配
|
||||||
|
area3Matches := make(map[int]*Region)
|
||||||
|
for id, v := range A3Data {
|
||||||
|
if mbStrpos(v.Name, a3) != -1 {
|
||||||
|
area3Matches[id] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 多个匹配项,需要通过二级地址筛选
|
||||||
|
if len(area3Matches) > 1 {
|
||||||
|
if a2 != "" {
|
||||||
|
area2Matches := make(map[int]*Region)
|
||||||
|
for id, v := range A2Data {
|
||||||
|
if mbStrpos(v.Name, a2) != -1 {
|
||||||
|
area2Matches[id] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(area2Matches) > 0 {
|
||||||
|
for _, v := range area3Matches {
|
||||||
|
if city, ok := area2Matches[v.PID]; ok {
|
||||||
|
r.City = city.Name
|
||||||
|
r.Region = v.Name
|
||||||
|
if province, ok := A1Data[city.PID]; ok {
|
||||||
|
r.Province = province.Name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
r.Province = ""
|
||||||
|
r.City = ""
|
||||||
|
r.Region = a3
|
||||||
|
}
|
||||||
|
} else if len(area3Matches) == 1 {
|
||||||
|
// 唯一匹配
|
||||||
|
for _, v := range area3Matches {
|
||||||
|
r.Region = v.Name
|
||||||
|
if city, ok := A2Data[v.PID]; ok {
|
||||||
|
r.City = city.Name
|
||||||
|
if province, ok := A1Data[city.PID]; ok {
|
||||||
|
r.Province = province.Name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if len(area3Matches) == 0 && a2 == a3 {
|
||||||
|
// 没有匹配到三级地址,但二级地址等于三级地址,可能是直辖市
|
||||||
|
shengID := 0
|
||||||
|
for _, v := range A2Data {
|
||||||
|
if mbStrpos(v.Name, a2) != -1 {
|
||||||
|
r.City = v.Name
|
||||||
|
shengID = v.PID
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if province, ok := A1Data[shengID]; ok {
|
||||||
|
r.Province = province.Name
|
||||||
|
}
|
||||||
|
r.Region = ""
|
||||||
|
}
|
||||||
|
|
||||||
|
return r
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,75 @@
|
|||||||
|
package formatter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
)
|
||||||
|
|
||||||
|
// mbStrpos 返回字符串首次出现的位置(UTF-8字符计数)
|
||||||
|
func mbStrpos(haystack, needle string) int {
|
||||||
|
if needle == "" {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
idx := strings.Index(haystack, needle)
|
||||||
|
if idx == -1 {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
return utf8.RuneCountInString(haystack[:idx])
|
||||||
|
}
|
||||||
|
|
||||||
|
// mbStrripos 返回字符串最后出现的位置(UTF-8字符计数)
|
||||||
|
func mbStrripos(haystack, needle string) int {
|
||||||
|
if needle == "" {
|
||||||
|
return utf8.RuneCountInString(haystack)
|
||||||
|
}
|
||||||
|
idx := strings.LastIndex(haystack, needle)
|
||||||
|
if idx == -1 {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
return utf8.RuneCountInString(haystack[:idx])
|
||||||
|
}
|
||||||
|
|
||||||
|
// mbStrstr 检查字符串是否包含子串
|
||||||
|
func mbStrstr(haystack, needle string) bool {
|
||||||
|
return strings.Contains(haystack, needle)
|
||||||
|
}
|
||||||
|
|
||||||
|
// mbSubstr 截取字符串(UTF-8字符计数)
|
||||||
|
// start: 起始位置(从0开始)
|
||||||
|
// length: 截取长度(字符数)
|
||||||
|
func mbSubstr(str string, start, length int) string {
|
||||||
|
runes := []rune(str)
|
||||||
|
strLen := len(runes)
|
||||||
|
|
||||||
|
// 处理负数起始位置
|
||||||
|
if start < 0 {
|
||||||
|
start = strLen + start
|
||||||
|
if start < 0 {
|
||||||
|
start = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 起始位置超出字符串长度
|
||||||
|
if start >= strLen {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算结束位置
|
||||||
|
end := start + length
|
||||||
|
if end > strLen {
|
||||||
|
end = strLen
|
||||||
|
}
|
||||||
|
if end < start {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
return string(runes[start:end])
|
||||||
|
}
|
||||||
|
|
||||||
|
// mbSubstrCount 统计子串出现次数
|
||||||
|
func mbSubstrCount(haystack, needle string) int {
|
||||||
|
if needle == "" {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return strings.Count(haystack, needle)
|
||||||
|
}
|
||||||
@@ -0,0 +1,360 @@
|
|||||||
|
package formatter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestParseCNAddress(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
input string
|
||||||
|
withUser bool
|
||||||
|
want *AddressInfo
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "完整地址信息",
|
||||||
|
input: "张三 13800138000 北京市朝阳区建国路1号",
|
||||||
|
withUser: true,
|
||||||
|
want: &AddressInfo{
|
||||||
|
Name: "张三",
|
||||||
|
Mobile: "13800138000",
|
||||||
|
Province: "北京",
|
||||||
|
City: "北京市",
|
||||||
|
Region: "朝阳区",
|
||||||
|
Street: "建国路1号",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "带身份证和邮编",
|
||||||
|
input: "李四 18612345678 110101199001011234 100000 上海市浦东新区世纪大道100号",
|
||||||
|
withUser: true,
|
||||||
|
want: &AddressInfo{
|
||||||
|
Name: "李四",
|
||||||
|
Mobile: "18612345678",
|
||||||
|
IDN: "110101199001011234",
|
||||||
|
Postcode: "100000",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "仅地址不含用户信息",
|
||||||
|
input: "北京市海淀区中关村大街1号",
|
||||||
|
withUser: false,
|
||||||
|
want: &AddressInfo{
|
||||||
|
Province: "北京",
|
||||||
|
City: "北京市",
|
||||||
|
Region: "海淀区",
|
||||||
|
Street: "中关村大街1号",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "带收货关键词",
|
||||||
|
input: "收货人:王五 电话:13900139000 收货地址:天津市河西区友谊路20号",
|
||||||
|
withUser: true,
|
||||||
|
want: &AddressInfo{
|
||||||
|
Name: "王五",
|
||||||
|
Mobile: "13900139000",
|
||||||
|
Province: "天津",
|
||||||
|
City: "天津市",
|
||||||
|
Region: "河西区",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "紧凑格式地址",
|
||||||
|
input: "马云13593464918陕西省西安市雁塔区丈八沟街道高新四路南江国际",
|
||||||
|
withUser: true,
|
||||||
|
want: &AddressInfo{
|
||||||
|
Name: "马云",
|
||||||
|
Mobile: "13593464918",
|
||||||
|
Province: "陕西省",
|
||||||
|
City: "西安市",
|
||||||
|
Region: "雁塔区",
|
||||||
|
Street: "丈八沟街道高新四路南江国际",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "带座机号格式",
|
||||||
|
input: "姓名:马云\n联系电话:800-8585222\n所在地区:河北省石家庄市新华区\n详细地址:中华北大街68号鹿城商务中心6号楼1413室",
|
||||||
|
withUser: true,
|
||||||
|
want: &AddressInfo{
|
||||||
|
Name: "马云",
|
||||||
|
Mobile: "800-8585222",
|
||||||
|
Province: "河北省",
|
||||||
|
City: "石家庄市",
|
||||||
|
Region: "新华区",
|
||||||
|
Street: "中华北大街68号鹿城商务中心6号楼1413室",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "北京市重复格式",
|
||||||
|
input: "北京市北京市市辖区东城区",
|
||||||
|
withUser: false,
|
||||||
|
want: &AddressInfo{
|
||||||
|
Province: "北京",
|
||||||
|
City: "北京市",
|
||||||
|
Region: "东城区",
|
||||||
|
Street: "",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "河北省新乐市地址",
|
||||||
|
input: "河北省石家庄市新乐市经济开发区兴工街10号来优品仓库",
|
||||||
|
withUser: false,
|
||||||
|
want: &AddressInfo{
|
||||||
|
Province: "河北省",
|
||||||
|
City: "石家庄市",
|
||||||
|
Region: "新乐市",
|
||||||
|
Street: "经济开发区兴工街10号来优品仓库",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "江苏仪征市地址",
|
||||||
|
input: "江苏省扬州市仪征市真州镇解放东路99号",
|
||||||
|
withUser: false,
|
||||||
|
want: &AddressInfo{
|
||||||
|
Province: "江苏省",
|
||||||
|
City: "扬州市",
|
||||||
|
Region: "仪征市",
|
||||||
|
Street: "真州镇解放东路99号",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "新疆石河子市地址",
|
||||||
|
input: "新疆石河子市北三路25小区",
|
||||||
|
withUser: false,
|
||||||
|
want: &AddressInfo{
|
||||||
|
Province: "新疆维吾尔自治区",
|
||||||
|
City: "自治区直辖县级市",
|
||||||
|
Region: "石河子市",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "新疆石河子市-简化格式省+县级市",
|
||||||
|
input: "新疆维吾尔自治区石河子市",
|
||||||
|
withUser: false,
|
||||||
|
want: &AddressInfo{
|
||||||
|
Province: "新疆维吾尔自治区",
|
||||||
|
City: "自治区直辖县级市",
|
||||||
|
Region: "石河子市",
|
||||||
|
Street: "",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "新疆石河子市-完整行政区划表述",
|
||||||
|
input: "新疆维吾尔自治区自治区直辖县级市石河子市",
|
||||||
|
withUser: false,
|
||||||
|
want: &AddressInfo{
|
||||||
|
Province: "新疆维吾尔自治区",
|
||||||
|
City: "自治区直辖县级市",
|
||||||
|
Region: "石河子市",
|
||||||
|
Street: "",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "浙江杭州西湖区重复地址",
|
||||||
|
input: "浙江省杭州市西湖区杭州市西湖区人民政府109号",
|
||||||
|
withUser: false,
|
||||||
|
want: &AddressInfo{
|
||||||
|
Province: "浙江省",
|
||||||
|
City: "杭州市",
|
||||||
|
Region: "西湖区",
|
||||||
|
Street: "人民政府109号",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "湖南长沙市重复地址",
|
||||||
|
input: "湖南省长沙市岳麓区银盆岭街道长沙市人民政府长沙市政府大楼",
|
||||||
|
withUser: false,
|
||||||
|
want: &AddressInfo{
|
||||||
|
Province: "湖南省",
|
||||||
|
City: "长沙市",
|
||||||
|
Region: "岳麓区",
|
||||||
|
Street: "银盆岭街道人民政府政府大楼",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got := ParseCNAddress(tt.input, tt.withUser)
|
||||||
|
|
||||||
|
// 打印结果便于调试
|
||||||
|
jsonData, _ := json.MarshalIndent(got, "", " ")
|
||||||
|
t.Logf("Result: %s", jsonData)
|
||||||
|
|
||||||
|
// 验证主要字段
|
||||||
|
if tt.want.Name != "" && got.Name != tt.want.Name {
|
||||||
|
t.Errorf("Name = %v, want %v", got.Name, tt.want.Name)
|
||||||
|
}
|
||||||
|
if tt.want.Mobile != "" && got.Mobile != tt.want.Mobile {
|
||||||
|
t.Errorf("Mobile = %v, want %v", got.Mobile, tt.want.Mobile)
|
||||||
|
}
|
||||||
|
if tt.want.Province != "" && got.Province != tt.want.Province {
|
||||||
|
t.Errorf("Province = %v, want %v", got.Province, tt.want.Province)
|
||||||
|
}
|
||||||
|
if tt.want.City != "" && got.City != tt.want.City {
|
||||||
|
t.Errorf("City = %v, want %v", got.City, tt.want.City)
|
||||||
|
}
|
||||||
|
if tt.want.Region != "" && got.Region != tt.want.Region {
|
||||||
|
t.Errorf("Region = %v, want %v", got.Region, tt.want.Region)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParsePersonInfo(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
input string
|
||||||
|
verify func(*testing.T, *AddressInfo)
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "提取姓名和手机号",
|
||||||
|
input: "张三 13800138000 北京市朝阳区",
|
||||||
|
verify: func(t *testing.T, got *AddressInfo) {
|
||||||
|
if got.Name != "张三" {
|
||||||
|
t.Errorf("Name = %v, want 张三", got.Name)
|
||||||
|
}
|
||||||
|
if got.Mobile != "13800138000" {
|
||||||
|
t.Errorf("Mobile = %v, want 13800138000", got.Mobile)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "提取身份证号",
|
||||||
|
input: "李四 110101199001011234 上海市",
|
||||||
|
verify: func(t *testing.T, got *AddressInfo) {
|
||||||
|
if got.Name != "李四" {
|
||||||
|
t.Errorf("Name = %v, want 李四", got.Name)
|
||||||
|
}
|
||||||
|
if got.IDN != "110101199001011234" {
|
||||||
|
t.Errorf("IDN = %v, want 110101199001011234", got.IDN)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "提取邮编",
|
||||||
|
input: "王五 100000 天津市",
|
||||||
|
verify: func(t *testing.T, got *AddressInfo) {
|
||||||
|
if got.Name != "王五" {
|
||||||
|
t.Errorf("Name = %v, want 王五", got.Name)
|
||||||
|
}
|
||||||
|
if got.Postcode != "100000" {
|
||||||
|
t.Errorf("Postcode = %v, want 100000", got.Postcode)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got := ParsePersonInfo(tt.input)
|
||||||
|
jsonData, _ := json.MarshalIndent(got, "", " ")
|
||||||
|
t.Logf("Result: %s", jsonData)
|
||||||
|
tt.verify(t, got)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFuzz(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
input string
|
||||||
|
want *fuzzyResult
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "包含区",
|
||||||
|
input: "北京市朝阳区建国路1号",
|
||||||
|
want: &fuzzyResult{
|
||||||
|
A2: "北京市",
|
||||||
|
A3: "朝阳区",
|
||||||
|
Street: "建国路1号",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "包含县",
|
||||||
|
input: "河北省石家庄市正定县",
|
||||||
|
want: &fuzzyResult{
|
||||||
|
A2: "石家庄市",
|
||||||
|
A3: "正定县",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "复杂街道地址",
|
||||||
|
input: "浙江省杭州市拱墅区武林街道杭州锦麟宾馆中河片区",
|
||||||
|
want: &fuzzyResult{
|
||||||
|
A2: "杭州市",
|
||||||
|
A3: "拱墅区",
|
||||||
|
Street: "武林街道杭州锦麟宾馆中河片区",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "北京市重复格式",
|
||||||
|
input: "北京市北京市市辖区东城区",
|
||||||
|
want: &fuzzyResult{
|
||||||
|
A2: "北京市",
|
||||||
|
A3: "东城区",
|
||||||
|
Street: "",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "详细地址包含市字",
|
||||||
|
input: "北京市朝阳区建外大街1号国贸商城",
|
||||||
|
want: &fuzzyResult{
|
||||||
|
A2: "北京市",
|
||||||
|
A3: "朝阳区",
|
||||||
|
Street: "建外大街1号国贸商城",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "详细地址真的包含市字",
|
||||||
|
input: "北京市朝阳区农贸市场路1号",
|
||||||
|
want: &fuzzyResult{
|
||||||
|
A2: "北京市",
|
||||||
|
A3: "朝阳区",
|
||||||
|
Street: "农贸市场路1号",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "河北省新乐市地址",
|
||||||
|
input: "河北省石家庄市新乐市经济开发区兴工街10号来优品仓库",
|
||||||
|
want: &fuzzyResult{
|
||||||
|
A2: "石家庄市",
|
||||||
|
A3: "新乐市",
|
||||||
|
Street: "经济开发区兴工街10号来优品仓库",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got := fuzz(tt.input)
|
||||||
|
jsonData, _ := json.MarshalIndent(got, "", " ")
|
||||||
|
t.Logf("Result: %s", jsonData)
|
||||||
|
|
||||||
|
if got.A2 != tt.want.A2 {
|
||||||
|
t.Errorf("A2 = %v, want %v", got.A2, tt.want.A2)
|
||||||
|
}
|
||||||
|
if got.A3 != tt.want.A3 {
|
||||||
|
t.Errorf("A3 = %v, want %v", got.A3, tt.want.A3)
|
||||||
|
}
|
||||||
|
if tt.want.Street != "" && got.Street != tt.want.Street {
|
||||||
|
t.Errorf("Street = %v, want %v", got.Street, tt.want.Street)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleParseCNAddress() {
|
||||||
|
// 解析包含用户信息的完整地址
|
||||||
|
result := ParseCNAddress("张三 13800138000 北京市朝阳区建国路1号", true)
|
||||||
|
jsonData, _ := json.MarshalIndent(result, "", " ")
|
||||||
|
println(string(jsonData))
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleParsePersonInfo() {
|
||||||
|
// 分离用户信息
|
||||||
|
result := ParsePersonInfo("收货人:李四 电话:18612345678 地址:上海市浦东新区世纪大道100号")
|
||||||
|
jsonData, _ := json.MarshalIndent(result, "", " ")
|
||||||
|
println(string(jsonData))
|
||||||
|
}
|
||||||
@@ -26,8 +26,9 @@ func Comma[T constraints.Float | constraints.Integer | string](value T, prefixSy
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
isNegative := strings.HasPrefix(numString, "-")
|
sign := ""
|
||||||
if isNegative {
|
if strings.HasPrefix(numString, "-") || strings.HasPrefix(numString, "+") {
|
||||||
|
sign = numString[:1]
|
||||||
numString = numString[1:]
|
numString = numString[1:]
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,11 +42,7 @@ func Comma[T constraints.Float | constraints.Integer | string](value T, prefixSy
|
|||||||
numString = numString[:index] + "," + numString[index:]
|
numString = numString[:index] + "," + numString[index:]
|
||||||
}
|
}
|
||||||
|
|
||||||
if isNegative {
|
return prefixSymbol + sign + numString
|
||||||
numString = "-" + numString
|
|
||||||
}
|
|
||||||
|
|
||||||
return prefixSymbol + numString
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pretty data to JSON string.
|
// Pretty data to JSON string.
|
||||||
|
|||||||
@@ -11,6 +11,9 @@ func TestComma(t *testing.T) {
|
|||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
assert := internal.NewAssert(t, "TestComma")
|
assert := internal.NewAssert(t, "TestComma")
|
||||||
|
assert.Equal("+123", Comma("+123", ""))
|
||||||
|
assert.Equal("+123,456", Comma("+123456", ""))
|
||||||
|
assert.Equal("$+123,456.78", Comma("+123456.78", "$"))
|
||||||
|
|
||||||
assert.Equal("", Comma("", ""))
|
assert.Equal("", Comma("", ""))
|
||||||
assert.Equal("", Comma("aa", ""))
|
assert.Equal("", Comma("aa", ""))
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ func And[T any](predicates ...func(T) bool) func(T) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Nand returns a composed predicate that represents the logical NAND of a list of predicates.
|
// Nand returns a composed predicate that represents the logical NAND of a list of predicates.
|
||||||
// It evaluates to true only if all predicates evaluate to false for the given value.
|
// It evaluates to false only if all predicates evaluate to true for the given value.
|
||||||
// Play: https://go.dev/play/p/Rb-FdNGpgSO
|
// Play: https://go.dev/play/p/Rb-FdNGpgSO
|
||||||
func Nand[T any](predicates ...func(T) bool) func(T) bool {
|
func Nand[T any](predicates ...func(T) bool) func(T) bool {
|
||||||
if len(predicates) < 2 {
|
if len(predicates) < 2 {
|
||||||
@@ -26,11 +26,11 @@ func Nand[T any](predicates ...func(T) bool) func(T) bool {
|
|||||||
}
|
}
|
||||||
return func(value T) bool {
|
return func(value T) bool {
|
||||||
for _, predicate := range predicates {
|
for _, predicate := range predicates {
|
||||||
if predicate(value) {
|
if !predicate(value) {
|
||||||
return false // Short-circuit on the first true predicate
|
return true // Short-circuit on the first false predicate
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true // True if all predicates are false
|
return false // False if all predicates are true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ func ExampleNand() {
|
|||||||
|
|
||||||
// Output:
|
// Output:
|
||||||
// false
|
// false
|
||||||
// false
|
// true
|
||||||
// true
|
// true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ func TestPredicatesNandPure(t *testing.T) {
|
|||||||
)
|
)
|
||||||
|
|
||||||
assert.ShouldBeFalse(isNumericAndLength5("12345"))
|
assert.ShouldBeFalse(isNumericAndLength5("12345"))
|
||||||
assert.ShouldBeFalse(isNumericAndLength5("1234"))
|
assert.ShouldBeTrue(isNumericAndLength5("1234"))
|
||||||
assert.ShouldBeTrue(isNumericAndLength5("abcdef"))
|
assert.ShouldBeTrue(isNumericAndLength5("abcdef"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package iterator
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestTakeHasNextExhaustedSource(t *testing.T) {
|
||||||
|
it := Take[int](FromSlice([]int{1}), 3)
|
||||||
|
if value, ok := it.Next(); !ok || value != 1 {
|
||||||
|
t.Fatal("missing first value")
|
||||||
|
}
|
||||||
|
if it.HasNext() {
|
||||||
|
t.Error("exhausted source still reports an element")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFilterHasNextMatches(t *testing.T) {
|
||||||
|
it := Filter[int](FromSlice([]int{1, 2, 3}), func(value int) bool { return value%2 == 0 })
|
||||||
|
if !it.HasNext() || !it.HasNext() {
|
||||||
|
t.Fatal("missing matching value")
|
||||||
|
}
|
||||||
|
if value, ok := it.Next(); !ok || value != 2 {
|
||||||
|
t.Fatal("HasNext consumed the matching value")
|
||||||
|
}
|
||||||
|
if it.HasNext() {
|
||||||
|
t.Error("unmatched tail reported as another element")
|
||||||
|
}
|
||||||
|
}
|
||||||
+13
-2
@@ -44,9 +44,17 @@ func Filter[T any](iter Iterator[T], predicateFunc func(item T) bool) Iterator[T
|
|||||||
type filterIterator[T any] struct {
|
type filterIterator[T any] struct {
|
||||||
iter Iterator[T]
|
iter Iterator[T]
|
||||||
predicateFunc func(T) bool
|
predicateFunc func(T) bool
|
||||||
|
next T
|
||||||
|
ready bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (fr *filterIterator[T]) Next() (T, bool) {
|
func (fr *filterIterator[T]) Next() (T, bool) {
|
||||||
|
if fr.ready {
|
||||||
|
item := fr.next
|
||||||
|
var zero T
|
||||||
|
fr.next, fr.ready = zero, false
|
||||||
|
return item, true
|
||||||
|
}
|
||||||
for item, ok := fr.iter.Next(); ok; item, ok = fr.iter.Next() {
|
for item, ok := fr.iter.Next(); ok; item, ok = fr.iter.Next() {
|
||||||
if fr.predicateFunc(item) {
|
if fr.predicateFunc(item) {
|
||||||
return item, true
|
return item, true
|
||||||
@@ -57,7 +65,10 @@ func (fr *filterIterator[T]) Next() (T, bool) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (fr *filterIterator[T]) HasNext() bool {
|
func (fr *filterIterator[T]) HasNext() bool {
|
||||||
return fr.iter.HasNext()
|
if !fr.ready {
|
||||||
|
fr.next, fr.ready = fr.Next()
|
||||||
|
}
|
||||||
|
return fr.ready
|
||||||
}
|
}
|
||||||
|
|
||||||
// Join creates an iterator that join all elements of iters[0], then all elements of iters[1] and so on.
|
// Join creates an iterator that join all elements of iters[0], then all elements of iters[1] and so on.
|
||||||
@@ -135,5 +146,5 @@ func (iter *takeIterator[T]) Next() (T, bool) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (iter *takeIterator[T]) HasNext() bool {
|
func (iter *takeIterator[T]) HasNext() bool {
|
||||||
return iter.num > 0
|
return iter.num > 0 && iter.it.HasNext()
|
||||||
}
|
}
|
||||||
+161
-3
@@ -8,6 +8,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
"sort"
|
"sort"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"golang.org/x/exp/constraints"
|
"golang.org/x/exp/constraints"
|
||||||
@@ -317,6 +318,10 @@ func HasKey[K comparable, V any](m map[K]V, key K) bool {
|
|||||||
// MapToStruct converts map to struct
|
// MapToStruct converts map to struct
|
||||||
// Play: https://go.dev/play/p/7wYyVfX38Dp
|
// Play: https://go.dev/play/p/7wYyVfX38Dp
|
||||||
func MapToStruct(m map[string]any, structObj any) error {
|
func MapToStruct(m map[string]any, structObj any) error {
|
||||||
|
target := reflect.ValueOf(structObj)
|
||||||
|
if target.Kind() != reflect.Ptr || target.IsNil() || target.Elem().Kind() != reflect.Struct {
|
||||||
|
return fmt.Errorf("destination must be a non-nil pointer to a struct")
|
||||||
|
}
|
||||||
for k, v := range m {
|
for k, v := range m {
|
||||||
err := setStructField(structObj, k, v)
|
err := setStructField(structObj, k, v)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -346,6 +351,9 @@ func setStructField(structObj any, fieldName string, fieldValue any) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
val := reflect.ValueOf(fieldValue)
|
val := reflect.ValueOf(fieldValue)
|
||||||
|
if !val.IsValid() {
|
||||||
|
return fmt.Errorf("Map value type don't match struct field type")
|
||||||
|
}
|
||||||
|
|
||||||
if fieldVal.Type() != val.Type() {
|
if fieldVal.Type() != val.Type() {
|
||||||
|
|
||||||
@@ -574,9 +582,12 @@ func convertSlice(src reflect.Value, dst reflect.Value) error {
|
|||||||
return fmt.Errorf("error type:%s", dst.Type().String())
|
return fmt.Errorf("error type:%s", dst.Type().String())
|
||||||
}
|
}
|
||||||
l := src.Len()
|
l := src.Len()
|
||||||
target := reflect.MakeSlice(dst.Type(), l, l)
|
if dst.Kind() == reflect.Array {
|
||||||
if dst.CanSet() {
|
if l > dst.Len() {
|
||||||
dst.Set(target)
|
return fmt.Errorf("source length %d exceeds destination length %d", l, dst.Len())
|
||||||
|
}
|
||||||
|
} else if dst.CanSet() {
|
||||||
|
dst.Set(reflect.MakeSlice(dst.Type(), l, l))
|
||||||
}
|
}
|
||||||
for i := 0; i < l; i++ {
|
for i := 0; i < l; i++ {
|
||||||
srcValue := src.Index(i)
|
srcValue := src.Index(i)
|
||||||
@@ -680,3 +691,150 @@ func FindValuesBy[K comparable, V any](m map[K]V, predicate func(key K, value V)
|
|||||||
|
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ToMarkdownTable converts a slice of maps to a Markdown table.
|
||||||
|
// Play: ttps://go.dev/play/p/w_pSLfeyEB5
|
||||||
|
func ToMarkdownTable(data []map[string]interface{}, headerMap map[string]string, columnOrder []string) string {
|
||||||
|
if len(data) == 0 {
|
||||||
|
return "| |\n|---|\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
var headers []string
|
||||||
|
|
||||||
|
// 如果提供了columnOrder,则按指定顺序排列
|
||||||
|
if len(columnOrder) > 0 {
|
||||||
|
headers = make([]string, len(columnOrder))
|
||||||
|
copy(headers, columnOrder)
|
||||||
|
} else {
|
||||||
|
// 否则按自然顺序提取headers
|
||||||
|
seen := make(map[string]bool)
|
||||||
|
for _, row := range data {
|
||||||
|
for k := range row {
|
||||||
|
if !seen[k] {
|
||||||
|
seen[k] = true
|
||||||
|
headers = append(headers, k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var builder strings.Builder
|
||||||
|
|
||||||
|
// Header row - 使用映射的中文标题
|
||||||
|
builder.WriteString("| ")
|
||||||
|
for i, h := range headers {
|
||||||
|
// 如果有映射则使用中文标题,否则使用原字段名
|
||||||
|
displayHeader := h
|
||||||
|
if headerMap != nil && headerMap[h] != "" {
|
||||||
|
displayHeader = headerMap[h]
|
||||||
|
}
|
||||||
|
builder.WriteString(displayHeader)
|
||||||
|
if i < len(headers)-1 {
|
||||||
|
builder.WriteString(" | ")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
builder.WriteString(" |\n")
|
||||||
|
|
||||||
|
// Separator
|
||||||
|
builder.WriteString("|")
|
||||||
|
for i := range headers {
|
||||||
|
if i > 0 {
|
||||||
|
builder.WriteString("|")
|
||||||
|
}
|
||||||
|
builder.WriteString("---")
|
||||||
|
}
|
||||||
|
builder.WriteString("|\n")
|
||||||
|
|
||||||
|
// Data rows
|
||||||
|
for _, row := range data {
|
||||||
|
builder.WriteString("| ")
|
||||||
|
for i, h := range headers {
|
||||||
|
val, exists := row[h]
|
||||||
|
var cell string
|
||||||
|
if !exists {
|
||||||
|
cell = ""
|
||||||
|
} else {
|
||||||
|
cell = formatValue(val)
|
||||||
|
}
|
||||||
|
builder.WriteString(cell)
|
||||||
|
if i < len(headers)-1 {
|
||||||
|
builder.WriteString(" | ")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
builder.WriteString(" |\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
return builder.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// formatValue formats any value for display in Markdown table
|
||||||
|
func formatValue(v interface{}) string {
|
||||||
|
switch val := v.(type) {
|
||||||
|
case int:
|
||||||
|
return commaInt64(int64(val))
|
||||||
|
case int8:
|
||||||
|
return commaInt64(int64(val))
|
||||||
|
case int16:
|
||||||
|
return commaInt64(int64(val))
|
||||||
|
case int32:
|
||||||
|
return commaInt64(int64(val))
|
||||||
|
case int64:
|
||||||
|
return commaInt64(val)
|
||||||
|
case uint:
|
||||||
|
return commaUint64(uint64(val))
|
||||||
|
case uint8:
|
||||||
|
return commaUint64(uint64(val))
|
||||||
|
case uint16:
|
||||||
|
return commaUint64(uint64(val))
|
||||||
|
case uint32:
|
||||||
|
return commaUint64(uint64(val))
|
||||||
|
case uint64:
|
||||||
|
return commaUint64(val)
|
||||||
|
case float32:
|
||||||
|
return fmt.Sprintf("%.2f", val)
|
||||||
|
case float64:
|
||||||
|
return fmt.Sprintf("%.2f", val)
|
||||||
|
case string:
|
||||||
|
return val
|
||||||
|
case bool:
|
||||||
|
return fmt.Sprintf("%t", val)
|
||||||
|
case nil:
|
||||||
|
return ""
|
||||||
|
default:
|
||||||
|
return fmt.Sprintf("%v", val)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// commaInt64 adds comma separators to int64
|
||||||
|
func commaInt64(n int64) string {
|
||||||
|
if n == 0 {
|
||||||
|
return "0"
|
||||||
|
}
|
||||||
|
neg := n < 0
|
||||||
|
if neg {
|
||||||
|
n = -n
|
||||||
|
}
|
||||||
|
s := strconv.FormatInt(n, 10)
|
||||||
|
return addCommas(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
// commaUint64 adds comma separators to uint64
|
||||||
|
func commaUint64(n uint64) string {
|
||||||
|
if n == 0 {
|
||||||
|
return "0"
|
||||||
|
}
|
||||||
|
s := strconv.FormatUint(n, 10)
|
||||||
|
return addCommas(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
// addCommas inserts commas every 3 digits
|
||||||
|
func addCommas(s string) string {
|
||||||
|
var result strings.Builder
|
||||||
|
for i, c := range s {
|
||||||
|
if i > 0 && (len(s)-i)%3 == 0 {
|
||||||
|
result.WriteRune(',')
|
||||||
|
}
|
||||||
|
result.WriteRune(c)
|
||||||
|
}
|
||||||
|
return result.String()
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package maputil
|
package maputil
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"math/cmplx"
|
"math/cmplx"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
@@ -10,6 +11,33 @@ import (
|
|||||||
"github.com/duke-git/lancet/v2/internal"
|
"github.com/duke-git/lancet/v2/internal"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestMapToArray(t *testing.T) {
|
||||||
|
var dst [2]int
|
||||||
|
if err := MapTo([]int{3, 4}, &dst); err != nil || dst != [2]int{3, 4} {
|
||||||
|
t.Fatalf("got %v, %v", dst, err)
|
||||||
|
}
|
||||||
|
if err := MapTo([]int{1, 2, 3}, &dst); err == nil {
|
||||||
|
t.Fatal("expected an error for an oversized source")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMapToStructInvalidInputs(t *testing.T) {
|
||||||
|
var nilTarget *struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
for _, dst := range []any{nil, nilTarget, 1, &[]int{}} {
|
||||||
|
if err := MapToStruct(map[string]any{"name": "value"}, dst); err == nil {
|
||||||
|
t.Errorf("expected an error for %T", dst)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var dst struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
if err := MapToStruct(map[string]any{"name": nil}, &dst); err == nil {
|
||||||
|
t.Error("expected an error for an incompatible nil value")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestKeys(t *testing.T) {
|
func TestKeys(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
@@ -926,3 +954,46 @@ func TestFindValuesBy(t *testing.T) {
|
|||||||
assert.Equal(tt.expected, result)
|
assert.Equal(tt.expected, result)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestToMarkdownTable(t *testing.T) {
|
||||||
|
// 测试空数据
|
||||||
|
emptyResult := ToMarkdownTable([]map[string]interface{}{}, nil, nil)
|
||||||
|
expectedEmpty := "| |\n|---|\n"
|
||||||
|
if emptyResult != expectedEmpty {
|
||||||
|
t.Errorf("Expected empty table, got: %s", emptyResult)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试基本数据
|
||||||
|
data := []map[string]interface{}{
|
||||||
|
{"name": "Alice", "age": 25, "salary": 50000},
|
||||||
|
{"name": "Bob", "age": 30, "salary": 60000},
|
||||||
|
}
|
||||||
|
result := ToMarkdownTable(data, nil, nil)
|
||||||
|
fmt.Printf("%s", result)
|
||||||
|
// 验证结果包含预期的表头和数据行
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试自定义列顺序
|
||||||
|
func TestToMarkdownTableWithColumnOrder(t *testing.T) {
|
||||||
|
data := []map[string]interface{}{
|
||||||
|
{"name": "Alice", "age": 25, "salary": 50000},
|
||||||
|
}
|
||||||
|
columnOrder := []string{"salary", "name", "age"}
|
||||||
|
result := ToMarkdownTable(data, nil, columnOrder)
|
||||||
|
fmt.Printf("%s", result)
|
||||||
|
// 验证列顺序是否正确
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试自定义表头
|
||||||
|
func TestToMarkdownTableWithHeaderMap(t *testing.T) {
|
||||||
|
data := []map[string]interface{}{
|
||||||
|
{"name": "Alice", "age": 25},
|
||||||
|
}
|
||||||
|
headerMap := map[string]string{
|
||||||
|
"name": "姓名",
|
||||||
|
"age": "年龄",
|
||||||
|
}
|
||||||
|
result := ToMarkdownTable(data, headerMap, nil)
|
||||||
|
fmt.Printf("%s", result)
|
||||||
|
// 验证中文表头是否正确显示
|
||||||
|
}
|
||||||
+28
-27
@@ -35,8 +35,10 @@ func Fibonacci(first, second, n int) int {
|
|||||||
if n <= 0 {
|
if n <= 0 {
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
if n < 3 {
|
if n == 1 {
|
||||||
return 1
|
return first
|
||||||
|
} else if n == 2 {
|
||||||
|
return second
|
||||||
} else if n == 3 {
|
} else if n == 3 {
|
||||||
return first + second
|
return first + second
|
||||||
} else {
|
} else {
|
||||||
@@ -75,8 +77,7 @@ func Percent(val, total float64, n int) float64 {
|
|||||||
// Play: https://go.dev/play/p/kZwpBRAcllO
|
// Play: https://go.dev/play/p/kZwpBRAcllO
|
||||||
func RoundToString[T constraints.Float | constraints.Integer](x T, n int) string {
|
func RoundToString[T constraints.Float | constraints.Integer](x T, n int) string {
|
||||||
tmp := math.Pow(10.0, float64(n))
|
tmp := math.Pow(10.0, float64(n))
|
||||||
x *= T(tmp)
|
r := math.Round(float64(x) * tmp)
|
||||||
r := math.Round(float64(x))
|
|
||||||
result := strconv.FormatFloat(r/tmp, 'f', n, 64)
|
result := strconv.FormatFloat(r/tmp, 'f', n, 64)
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
@@ -85,15 +86,14 @@ func RoundToString[T constraints.Float | constraints.Integer](x T, n int) string
|
|||||||
// Play: https://go.dev/play/p/ghyb528JRJL
|
// Play: https://go.dev/play/p/ghyb528JRJL
|
||||||
func RoundToFloat[T constraints.Float | constraints.Integer](x T, n int) float64 {
|
func RoundToFloat[T constraints.Float | constraints.Integer](x T, n int) float64 {
|
||||||
tmp := math.Pow(10.0, float64(n))
|
tmp := math.Pow(10.0, float64(n))
|
||||||
x *= T(tmp)
|
r := math.Round(float64(x) * tmp)
|
||||||
r := math.Round(float64(x))
|
|
||||||
return r / tmp
|
return r / tmp
|
||||||
}
|
}
|
||||||
|
|
||||||
// TruncRound round off n decimal places.
|
// TruncRound round off n decimal places.
|
||||||
// Play: https://go.dev/play/p/aumarSHIGzP
|
// Play: https://go.dev/play/p/aumarSHIGzP
|
||||||
func TruncRound[T constraints.Float | constraints.Integer](x T, n int) T {
|
func TruncRound[T constraints.Float | constraints.Integer](x T, n int) T {
|
||||||
floatStr := fmt.Sprintf("%."+strconv.Itoa(n+1)+"f", x)
|
floatStr := fmt.Sprintf("%."+strconv.Itoa(n+1)+"f", float64(x))
|
||||||
temp := strings.Split(floatStr, ".")
|
temp := strings.Split(floatStr, ".")
|
||||||
var newFloat string
|
var newFloat string
|
||||||
if len(temp) < 2 || n >= len(temp[1]) {
|
if len(temp) < 2 || n >= len(temp[1]) {
|
||||||
@@ -109,8 +109,7 @@ func TruncRound[T constraints.Float | constraints.Integer](x T, n int) T {
|
|||||||
// Play: https://go.dev/play/p/vbCBrQHZEED
|
// Play: https://go.dev/play/p/vbCBrQHZEED
|
||||||
func FloorToFloat[T constraints.Float | constraints.Integer](x T, n int) float64 {
|
func FloorToFloat[T constraints.Float | constraints.Integer](x T, n int) float64 {
|
||||||
tmp := math.Pow(10.0, float64(n))
|
tmp := math.Pow(10.0, float64(n))
|
||||||
x *= T(tmp)
|
r := math.Floor(float64(x) * tmp)
|
||||||
r := math.Floor(float64(x))
|
|
||||||
return r / tmp
|
return r / tmp
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,8 +117,7 @@ func FloorToFloat[T constraints.Float | constraints.Integer](x T, n int) float64
|
|||||||
// Play: https://go.dev/play/p/Qk9KPd2IdDb
|
// Play: https://go.dev/play/p/Qk9KPd2IdDb
|
||||||
func FloorToString[T constraints.Float | constraints.Integer](x T, n int) string {
|
func FloorToString[T constraints.Float | constraints.Integer](x T, n int) string {
|
||||||
tmp := math.Pow(10.0, float64(n))
|
tmp := math.Pow(10.0, float64(n))
|
||||||
x *= T(tmp)
|
r := math.Floor(float64(x) * tmp)
|
||||||
r := math.Floor(float64(x))
|
|
||||||
result := strconv.FormatFloat(r/tmp, 'f', n, 64)
|
result := strconv.FormatFloat(r/tmp, 'f', n, 64)
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
@@ -128,8 +126,7 @@ func FloorToString[T constraints.Float | constraints.Integer](x T, n int) string
|
|||||||
// Play: https://go.dev/play/p/8hOeSADZPCo
|
// Play: https://go.dev/play/p/8hOeSADZPCo
|
||||||
func CeilToFloat[T constraints.Float | constraints.Integer](x T, n int) float64 {
|
func CeilToFloat[T constraints.Float | constraints.Integer](x T, n int) float64 {
|
||||||
tmp := math.Pow(10.0, float64(n))
|
tmp := math.Pow(10.0, float64(n))
|
||||||
x *= T(tmp)
|
r := math.Ceil(float64(x) * tmp)
|
||||||
r := math.Ceil(float64(x))
|
|
||||||
return r / tmp
|
return r / tmp
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -137,8 +134,7 @@ func CeilToFloat[T constraints.Float | constraints.Integer](x T, n int) float64
|
|||||||
// Play: https://go.dev/play/p/wy5bYEyUKKG
|
// Play: https://go.dev/play/p/wy5bYEyUKKG
|
||||||
func CeilToString[T constraints.Float | constraints.Integer](x T, n int) string {
|
func CeilToString[T constraints.Float | constraints.Integer](x T, n int) string {
|
||||||
tmp := math.Pow(10.0, float64(n))
|
tmp := math.Pow(10.0, float64(n))
|
||||||
x *= T(tmp)
|
r := math.Ceil(float64(x) * tmp)
|
||||||
r := math.Ceil(float64(x))
|
|
||||||
result := strconv.FormatFloat(r/tmp, 'f', n, 64)
|
result := strconv.FormatFloat(r/tmp, 'f', n, 64)
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
@@ -238,6 +234,9 @@ func Sum[T constraints.Integer | constraints.Float](numbers ...T) T {
|
|||||||
// Average return average value of numbers.
|
// Average return average value of numbers.
|
||||||
// Play: https://go.dev/play/p/Vv7LBwER-pz
|
// Play: https://go.dev/play/p/Vv7LBwER-pz
|
||||||
func Average[T constraints.Integer | constraints.Float](numbers ...T) float64 {
|
func Average[T constraints.Integer | constraints.Float](numbers ...T) float64 {
|
||||||
|
if len(numbers) == 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
var sum float64
|
var sum float64
|
||||||
for _, num := range numbers {
|
for _, num := range numbers {
|
||||||
sum += float64(num)
|
sum += float64(num)
|
||||||
@@ -267,12 +266,17 @@ func Range[T constraints.Integer | constraints.Float](start T, count int) []T {
|
|||||||
func RangeWithStep[T constraints.Integer | constraints.Float](start, end, step T) []T {
|
func RangeWithStep[T constraints.Integer | constraints.Float](start, end, step T) []T {
|
||||||
result := []T{}
|
result := []T{}
|
||||||
|
|
||||||
if start >= end || step == 0 {
|
if start >= end || step <= 0 {
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
for i := start; i < end; i += step {
|
for i := start; i < end; {
|
||||||
result = append(result, i)
|
result = append(result, i)
|
||||||
|
next := i + step
|
||||||
|
if next <= i {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
i = next
|
||||||
}
|
}
|
||||||
|
|
||||||
return result
|
return result
|
||||||
@@ -295,11 +299,7 @@ func RadianToAngle(radian float64) float64 {
|
|||||||
// PointDistance get two points distance.
|
// PointDistance get two points distance.
|
||||||
// Play: https://go.dev/play/p/RrG4JIaziM8
|
// Play: https://go.dev/play/p/RrG4JIaziM8
|
||||||
func PointDistance(x1, y1, x2, y2 float64) float64 {
|
func PointDistance(x1, y1, x2, y2 float64) float64 {
|
||||||
a := x1 - x2
|
return math.Hypot(x1-x2, y1-y2)
|
||||||
b := y1 - y2
|
|
||||||
c := math.Pow(a, 2) + math.Pow(b, 2)
|
|
||||||
|
|
||||||
return math.Sqrt(c)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsPrime checks if number is prime number.
|
// IsPrime checks if number is prime number.
|
||||||
@@ -360,7 +360,7 @@ func lcm[T constraints.Integer](a, b T) T {
|
|||||||
if a == 0 || b == 0 {
|
if a == 0 || b == 0 {
|
||||||
panic("lcm function: provide non zero integers only.")
|
panic("lcm function: provide non zero integers only.")
|
||||||
}
|
}
|
||||||
return a * b / gcd(a, b)
|
return a / gcd(a, b) * b
|
||||||
}
|
}
|
||||||
|
|
||||||
// Cos returns the cosine of the radian argument.
|
// Cos returns the cosine of the radian argument.
|
||||||
@@ -438,10 +438,11 @@ func Permutation(n, k uint) uint {
|
|||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
nFactorial := Factorial(n)
|
result := uint(1)
|
||||||
nMinusKFactorial := Factorial(n - k)
|
for i := uint(0); i < k; i++ {
|
||||||
|
result *= n - i
|
||||||
return nFactorial / nMinusKFactorial
|
}
|
||||||
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
// Combination calculate C(n, k).
|
// Combination calculate C(n, k).
|
||||||
|
|||||||
@@ -17,6 +17,19 @@ func TestExponent(t *testing.T) {
|
|||||||
assert.Equal(int64(100), Exponent(10, 2))
|
assert.Equal(int64(100), Exponent(10, 2))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestTruncRoundInteger(t *testing.T) {
|
||||||
|
assert := internal.NewAssert(t, "TestTruncRoundInteger")
|
||||||
|
assert.Equal(42, TruncRound(42, 0))
|
||||||
|
assert.Equal(int8(-42), TruncRound(int8(-42), 2))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLCMIntermediateOverflow(t *testing.T) {
|
||||||
|
assert := internal.NewAssert(t, "TestLCMIntermediateOverflow")
|
||||||
|
assert.Equal(uint8(32), LCM(uint8(32)))
|
||||||
|
assert.Equal(uint8(192), LCM(uint8(64), uint8(96)))
|
||||||
|
assert.Equal(uint64(1<<40), LCM(uint64(1<<40), uint64(1<<39)))
|
||||||
|
}
|
||||||
|
|
||||||
func TestFibonacci(t *testing.T) {
|
func TestFibonacci(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
@@ -26,6 +39,10 @@ func TestFibonacci(t *testing.T) {
|
|||||||
assert.Equal(1, Fibonacci(1, 1, 1))
|
assert.Equal(1, Fibonacci(1, 1, 1))
|
||||||
assert.Equal(1, Fibonacci(1, 1, 2))
|
assert.Equal(1, Fibonacci(1, 1, 2))
|
||||||
assert.Equal(5, Fibonacci(1, 1, 5))
|
assert.Equal(5, Fibonacci(1, 1, 5))
|
||||||
|
assert.Equal(2, Fibonacci(2, 3, 1))
|
||||||
|
assert.Equal(3, Fibonacci(2, 3, 2))
|
||||||
|
assert.Equal(5, Fibonacci(2, 3, 3))
|
||||||
|
assert.Equal(13, Fibonacci(2, 3, 5))
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFactorial(t *testing.T) {
|
func TestFactorial(t *testing.T) {
|
||||||
@@ -49,6 +66,19 @@ func TestPercent(t *testing.T) {
|
|||||||
assert.EqualValues(-7.42, Percent(-30305, 408420, 2))
|
assert.EqualValues(-7.42, Percent(-30305, 408420, 2))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestIntegerRoundingScale(t *testing.T) {
|
||||||
|
assert := internal.NewAssert(t, "TestIntegerRoundingScale")
|
||||||
|
assert.Equal(float64(42), RoundToFloat(int8(42), 2))
|
||||||
|
assert.Equal("42.00", RoundToString(int8(42), 2))
|
||||||
|
assert.Equal(float64(42), FloorToFloat(uint8(42), 2))
|
||||||
|
assert.Equal("42.00", FloorToString(uint8(42), 2))
|
||||||
|
assert.Equal(float64(42), CeilToFloat(int8(42), 2))
|
||||||
|
assert.Equal("42.00", CeilToString(int8(42), 2))
|
||||||
|
assert.Equal(float64(150), RoundToFloat(149, -1))
|
||||||
|
assert.Equal(float64(140), FloorToFloat(149, -1))
|
||||||
|
assert.Equal(float64(150), CeilToFloat(149, -1))
|
||||||
|
}
|
||||||
|
|
||||||
func TestRoundToFloat(t *testing.T) {
|
func TestRoundToFloat(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
@@ -260,6 +290,10 @@ func TestRangeWithStep(t *testing.T) {
|
|||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
assert := internal.NewAssert(t, "TestRangeWithStep")
|
assert := internal.NewAssert(t, "TestRangeWithStep")
|
||||||
|
assert.Equal([]int8{120}, RangeWithStep[int8](120, 125, 10))
|
||||||
|
assert.Equal([]uint8{250}, RangeWithStep[uint8](250, 253, 10))
|
||||||
|
assert.Equal([]int{}, RangeWithStep(1, 4, -1))
|
||||||
|
assert.Equal([]float64{1e20}, RangeWithStep(1e20, 1e21, 1.0))
|
||||||
|
|
||||||
result1 := RangeWithStep(1, 4, 1)
|
result1 := RangeWithStep(1, 4, 1)
|
||||||
result2 := RangeWithStep(1, -1, 0)
|
result2 := RangeWithStep(1, -1, 0)
|
||||||
@@ -300,6 +334,15 @@ func TestRadianToAngle(t *testing.T) {
|
|||||||
assert.Equal(float64(45), result3)
|
assert.Equal(float64(45), result3)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestPointDistanceExtremeScales(t *testing.T) {
|
||||||
|
for _, scale := range []float64{1e200, 1e-200} {
|
||||||
|
got := PointDistance(0, 0, 3*scale, 4*scale)
|
||||||
|
if math.Abs(got/(5*scale)-1) > 1e-15 {
|
||||||
|
t.Errorf("scale %g: got %g, want %g", scale, got, 5*scale)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestPointDistance(t *testing.T) {
|
func TestPointDistance(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package netutil
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDownloadFileStatus(t *testing.T) {
|
||||||
|
for _, status := range []int{http.StatusOK, http.StatusNotFound, http.StatusInternalServerError} {
|
||||||
|
t.Run(http.StatusText(status), func(t *testing.T) {
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.WriteHeader(status)
|
||||||
|
w.Write([]byte("response"))
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
path := filepath.Join(t.TempDir(), "download.txt")
|
||||||
|
if err := os.WriteFile(path, []byte("original"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
err := DownloadFile(path, server.URL)
|
||||||
|
if (err != nil) != (status != http.StatusOK) {
|
||||||
|
t.Errorf("unexpected result: %v", err)
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := "original"
|
||||||
|
if status == http.StatusOK {
|
||||||
|
want = "response"
|
||||||
|
}
|
||||||
|
if string(data) != want {
|
||||||
|
t.Errorf("got %q, want %q", data, want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -209,6 +209,9 @@ func (client *HttpClient) SendRequest(request *HttpRequest) (*http.Response, err
|
|||||||
} else {
|
} else {
|
||||||
err = client.setFormData(req, request.FormData, nil)
|
err = client.setFormData(req, request.FormData, nil)
|
||||||
}
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
client.Request = req
|
client.Request = req
|
||||||
|
|||||||
+28
-8
@@ -412,21 +412,41 @@ func TestHttpClient_AsyncSendRequest(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestProxy(t *testing.T) {
|
func TestProxy(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
// Local target server
|
||||||
|
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
_, _ = w.Write([]byte("ok"))
|
||||||
|
}))
|
||||||
|
defer target.Close()
|
||||||
|
|
||||||
|
// Local proxy server (basic forwarding stub)
|
||||||
|
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// In real proxy tests, you'd validate request form and forward.
|
||||||
|
// Keep deterministic: just return OK.
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
_, _ = w.Write([]byte("proxied"))
|
||||||
|
}))
|
||||||
|
defer proxy.Close()
|
||||||
|
|
||||||
|
proxyURL, err := url.Parse(proxy.URL)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to parse proxy URL: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
config := &HttpClientConfig{
|
config := &HttpClientConfig{
|
||||||
HandshakeTimeout: 20 * time.Second,
|
HandshakeTimeout: 20 * time.Second,
|
||||||
ResponseTimeout: 40 * time.Second,
|
ResponseTimeout: 40 * time.Second,
|
||||||
// Use the proxy ip to add it here
|
Proxy: proxyURL,
|
||||||
//Proxy: &url.URL{
|
|
||||||
// Scheme: "http",
|
|
||||||
// Host: "46.17.63.166:18888",
|
|
||||||
//},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
httpClient := NewHttpClientWithConfig(config)
|
httpClient := NewHttpClientWithConfig(config)
|
||||||
resp, err := httpClient.Get("https://www.ipplus360.com/getLocation")
|
resp, err := httpClient.Get(target.URL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Log("net error: ", err.Error())
|
t.Fatalf("request failed: %v", err)
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
t.Fatalf("expected %d, got %d", http.StatusOK, resp.StatusCode)
|
t.Fatalf("expected %d, got %d", http.StatusOK, resp.StatusCode)
|
||||||
|
|||||||
+35
-9
@@ -70,12 +70,12 @@ func GetInternalIp() string {
|
|||||||
func GetRequestPublicIp(req *http.Request) string {
|
func GetRequestPublicIp(req *http.Request) string {
|
||||||
var ip string
|
var ip string
|
||||||
for _, ip = range strings.Split(req.Header.Get("X-Forwarded-For"), ",") {
|
for _, ip = range strings.Split(req.Header.Get("X-Forwarded-For"), ",") {
|
||||||
if ip = strings.TrimSpace(ip); ip != "" && !IsInternalIP(net.ParseIP(ip)) {
|
if ip = strings.TrimSpace(ip); net.ParseIP(ip) != nil && !IsInternalIP(net.ParseIP(ip)) {
|
||||||
return ip
|
return ip
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ip = strings.TrimSpace(req.Header.Get("X-Real-Ip")); ip != "" && !IsInternalIP(net.ParseIP(ip)) {
|
if ip = strings.TrimSpace(req.Header.Get("X-Real-Ip")); net.ParseIP(ip) != nil && !IsInternalIP(net.ParseIP(ip)) {
|
||||||
return ip
|
return ip
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -192,18 +192,37 @@ func IsPublicIP(IP net.IP) bool {
|
|||||||
// IsInternalIP verify an ip is intranet or not.
|
// IsInternalIP verify an ip is intranet or not.
|
||||||
// Play: https://go.dev/play/p/sYGhXbgO4Cb
|
// Play: https://go.dev/play/p/sYGhXbgO4Cb
|
||||||
func IsInternalIP(IP net.IP) bool {
|
func IsInternalIP(IP net.IP) bool {
|
||||||
if IP.IsLoopback() {
|
if IP.IsLoopback() || IP.IsPrivate() || IP.IsLinkLocalUnicast() {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
if ip4 := IP.To4(); ip4 != nil {
|
if ip4 := IP.To4(); ip4 != nil {
|
||||||
return ip4[0] == 10 ||
|
// RFC 6598 shared address space, 100.64.0.0/10.
|
||||||
(ip4[0] == 172 && ip4[1] >= 16 && ip4[1] <= 31) ||
|
return ip4[0] == 100 && ip4[1]&0xc0 == 0x40
|
||||||
(ip4[0] == 169 && ip4[1] == 254) ||
|
}
|
||||||
(ip4[0] == 192 && ip4[1] == 168)
|
if embedded, ok := embeddedTransitionIPv4(IP); ok {
|
||||||
|
return IsInternalIP(embedded)
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// embeddedTransitionIPv4 returns the IPv4 address carried by a NAT64, 6to4, or Teredo address.
|
||||||
|
func embeddedTransitionIPv4(ip net.IP) (net.IP, bool) {
|
||||||
|
ip = ip.To16()
|
||||||
|
if ip == nil || ip.To4() != nil {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case bytes.Equal(ip[:12], []byte{0x00, 0x64, 0xff, 0x9b, 0, 0, 0, 0, 0, 0, 0, 0}):
|
||||||
|
return net.IPv4(ip[12], ip[13], ip[14], ip[15]), true
|
||||||
|
case ip[0] == 0x20 && ip[1] == 0x02:
|
||||||
|
return net.IPv4(ip[2], ip[3], ip[4], ip[5]), true
|
||||||
|
case ip[0] == 0x20 && ip[1] == 0x01 && ip[2] == 0 && ip[3] == 0:
|
||||||
|
return net.IPv4(ip[12]^0xff, ip[13]^0xff, ip[14]^0xff, ip[15]^0xff), true
|
||||||
|
default:
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// EncodeUrl encode url.
|
// EncodeUrl encode url.
|
||||||
// Play: https://go.dev/play/p/bsZ6BRC4uKI
|
// Play: https://go.dev/play/p/bsZ6BRC4uKI
|
||||||
func EncodeUrl(urlStr string) (string, error) {
|
func EncodeUrl(urlStr string) (string, error) {
|
||||||
@@ -250,10 +269,14 @@ func UploadFile(filepath string, server string) (bool, error) {
|
|||||||
contentType := writer.FormDataContentType()
|
contentType := writer.FormDataContentType()
|
||||||
writer.Close()
|
writer.Close()
|
||||||
|
|
||||||
_, err = http.Post(server, contentType, bodyBuffer)
|
resp, err := http.Post(server, contentType, bodyBuffer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
|
||||||
|
return false, fmt.Errorf("upload failed: %s", resp.Status)
|
||||||
|
}
|
||||||
|
|
||||||
return true, nil
|
return true, nil
|
||||||
}
|
}
|
||||||
@@ -265,6 +288,9 @@ func DownloadFile(filepath string, url string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
|
||||||
|
return fmt.Errorf("download failed: %s", resp.Status)
|
||||||
|
}
|
||||||
|
|
||||||
out, err := os.Create(filepath)
|
out, err := os.Create(filepath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -296,7 +322,7 @@ func IsPingConnected(host string) bool {
|
|||||||
// IsTelnetConnected checks if can telnet specified host or not.
|
// IsTelnetConnected checks if can telnet specified host or not.
|
||||||
// Play: https://go.dev/play/p/yiLCGtQv_ZG
|
// Play: https://go.dev/play/p/yiLCGtQv_ZG
|
||||||
func IsTelnetConnected(host string, port string) bool {
|
func IsTelnetConnected(host string, port string) bool {
|
||||||
adder := host + ":" + port
|
adder := net.JoinHostPort(host, port)
|
||||||
conn, err := net.DialTimeout("tcp", adder, 5*time.Second)
|
conn, err := net.DialTimeout("tcp", adder, 5*time.Second)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -95,6 +95,36 @@ func TestIsInternalIP(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestIsInternalIPCoversIPv6AndSharedSpace(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
assert := internal.NewAssert(t, "TestIsInternalIPCoversIPv6AndSharedSpace")
|
||||||
|
|
||||||
|
ips := []net.IP{
|
||||||
|
net.ParseIP("fd12:3456:789a::1"),
|
||||||
|
net.ParseIP("fe80::1"),
|
||||||
|
net.ParseIP("100.64.0.1"),
|
||||||
|
net.ParseIP("100.127.255.255"),
|
||||||
|
net.ParseIP("100.63.255.255"),
|
||||||
|
net.ParseIP("100.128.0.1"),
|
||||||
|
net.ParseIP("::ffff:192.168.0.1"),
|
||||||
|
net.ParseIP("64:ff9b::a9fe:a9fe"),
|
||||||
|
net.ParseIP("64:ff9b::808:808"),
|
||||||
|
net.ParseIP("2002:7f00:1::1"),
|
||||||
|
net.ParseIP("2002:808:808::1"),
|
||||||
|
net.ParseIP("2001::80ff:fffe"),
|
||||||
|
net.ParseIP("2001:db8::1"),
|
||||||
|
}
|
||||||
|
expected := []bool{
|
||||||
|
true, true, true, true, false, false, true,
|
||||||
|
true, false, true, false, true, false,
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < len(ips); i++ {
|
||||||
|
assert.Equal(expected[i], IsInternalIP(ips[i]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestGetIps(t *testing.T) {
|
func TestGetIps(t *testing.T) {
|
||||||
ips := GetIps()
|
ips := GetIps()
|
||||||
t.Log(ips)
|
t.Log(ips)
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package netutil
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGetRequestPublicIpInvalidHeaders(t *testing.T) {
|
||||||
|
for _, test := range []struct{ forwarded, real, want string }{
|
||||||
|
{"unknown, 8.8.8.8", "", "8.8.8.8"},
|
||||||
|
{"unknown", "invalid", "1.1.1.1"},
|
||||||
|
{"10.0.0.1", "8.8.4.4", "8.8.4.4"},
|
||||||
|
} {
|
||||||
|
req := httptest.NewRequest("GET", "http://example.com", nil)
|
||||||
|
req.RemoteAddr = "1.1.1.1:1234"
|
||||||
|
req.Header.Set("X-Forwarded-For", test.forwarded)
|
||||||
|
req.Header.Set("X-Real-Ip", test.real)
|
||||||
|
if got := GetRequestPublicIp(req); got != test.want {
|
||||||
|
t.Errorf("got %q, want %q", got, test.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package netutil
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestIsTelnetConnectedIPv6(t *testing.T) {
|
||||||
|
listener, err := net.Listen("tcp6", "[::1]:0")
|
||||||
|
if err != nil {
|
||||||
|
t.Skipf("IPv6 loopback unavailable: %v", err)
|
||||||
|
}
|
||||||
|
defer listener.Close()
|
||||||
|
host, port, err := net.SplitHostPort(listener.Addr().String())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !IsTelnetConnected(host, port) {
|
||||||
|
t.Error("could not connect to the IPv6 loopback listener")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package netutil
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
type uploadResponseBody struct {
|
||||||
|
io.Reader
|
||||||
|
closed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *uploadResponseBody) Close() error { b.closed = true; return nil }
|
||||||
|
|
||||||
|
type uploadTransport struct{ response *http.Response }
|
||||||
|
|
||||||
|
func (t uploadTransport) RoundTrip(*http.Request) (*http.Response, error) { return t.response, nil }
|
||||||
|
|
||||||
|
func TestUploadFileResponse(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "upload.txt")
|
||||||
|
if err := os.WriteFile(path, []byte("content"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
original := http.DefaultClient
|
||||||
|
defer func() { http.DefaultClient = original }()
|
||||||
|
for _, status := range []int{http.StatusCreated, http.StatusInternalServerError} {
|
||||||
|
body := &uploadResponseBody{Reader: strings.NewReader("response")}
|
||||||
|
http.DefaultClient = &http.Client{Transport: uploadTransport{&http.Response{StatusCode: status, Body: body}}}
|
||||||
|
ok, err := UploadFile(path, "https://example.com/upload")
|
||||||
|
if ok != (status == http.StatusCreated) || (err != nil) != (status != http.StatusCreated) {
|
||||||
|
t.Errorf("status %d: got %v, %v", status, ok, err)
|
||||||
|
}
|
||||||
|
if !body.closed {
|
||||||
|
t.Errorf("status %d: response body was not closed", status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package random
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestUniqueRandomSlicesNonPositiveLength(t *testing.T) {
|
||||||
|
for _, length := range []int{-1, 0} {
|
||||||
|
if got := RandUniqueIntSlice(length, 1, 10); len(got) != 0 {
|
||||||
|
t.Errorf("unexpected integers: %v", got)
|
||||||
|
}
|
||||||
|
if got := RandFloats(length, 1, 10, 2); len(got) != 0 {
|
||||||
|
t.Errorf("unexpected floats: %v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+16
-7
@@ -10,7 +10,7 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"math"
|
"math"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
"os"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
@@ -27,7 +27,14 @@ const (
|
|||||||
AllChars = Numeral + LowwerLetters + UpperLetters + SymbolChars
|
AllChars = Numeral + LowwerLetters + UpperLetters + SymbolChars
|
||||||
)
|
)
|
||||||
|
|
||||||
var rn = rand.NewSource(time.Now().UnixNano())
|
// var rn = rand.NewSource(time.Now().UnixNano())
|
||||||
|
|
||||||
|
// 每个 goroutine 独立的 rand.Rand,避免并发问题
|
||||||
|
var randPool = sync.Pool{
|
||||||
|
New: func() any {
|
||||||
|
return rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
rand.Seed(time.Now().UnixNano())
|
rand.Seed(time.Now().UnixNano())
|
||||||
@@ -91,7 +98,7 @@ func RandIntSlice(length, min, max int) []int {
|
|||||||
// RandUniqueIntSlice generate a slice of random int of length that do not repeat.
|
// RandUniqueIntSlice generate a slice of random int of length that do not repeat.
|
||||||
// Play: https://go.dev/play/p/uBkRSOz73Ec
|
// Play: https://go.dev/play/p/uBkRSOz73Ec
|
||||||
func RandUniqueIntSlice(length, min, max int) []int {
|
func RandUniqueIntSlice(length, min, max int) []int {
|
||||||
if min > max {
|
if length <= 0 || min > max {
|
||||||
return []int{}
|
return []int{}
|
||||||
}
|
}
|
||||||
if length > max-min {
|
if length > max-min {
|
||||||
@@ -132,6 +139,9 @@ func RandFloat(min, max float64, precision int) float64 {
|
|||||||
// RandFloats generate a slice of random float64 numbers of length that do not repeat.
|
// RandFloats generate a slice of random float64 numbers of length that do not repeat.
|
||||||
// Play: https://go.dev/play/p/I3yndUQ-rhh
|
// Play: https://go.dev/play/p/I3yndUQ-rhh
|
||||||
func RandFloats(length int, min, max float64, precision int) []float64 {
|
func RandFloats(length int, min, max float64, precision int) []float64 {
|
||||||
|
if length <= 0 {
|
||||||
|
return []float64{}
|
||||||
|
}
|
||||||
if max < min {
|
if max < min {
|
||||||
min, max = max, min
|
min, max = max, min
|
||||||
}
|
}
|
||||||
@@ -286,10 +296,9 @@ func nearestPowerOfTwo(cap int) int {
|
|||||||
|
|
||||||
// random generate a random string based on given string range.
|
// random generate a random string based on given string range.
|
||||||
func random(s string, length int) string {
|
func random(s string, length int) string {
|
||||||
// 确保随机数生成器的种子是动态的
|
// 从 pool 中获取 rand.Rand(替代全局 rand)
|
||||||
pid := os.Getpid()
|
rn := randPool.Get().(*rand.Rand)
|
||||||
timestamp := time.Now().UnixNano()
|
defer randPool.Put(rn)
|
||||||
rand.Seed(int64(pid) + timestamp)
|
|
||||||
|
|
||||||
// 仿照strings.Builder
|
// 仿照strings.Builder
|
||||||
// 创建一个长度为 length 的字节切片
|
// 创建一个长度为 length 的字节切片
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
package random
|
package random
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/duke-git/lancet/v2/internal"
|
"github.com/duke-git/lancet/v2/internal"
|
||||||
@@ -376,3 +378,46 @@ func TestRandNumberOfLength(t *testing.T) {
|
|||||||
assert := internal.NewAssert(t, "TestRandNumberOfLength")
|
assert := internal.NewAssert(t, "TestRandNumberOfLength")
|
||||||
assert.Equal(6, len(strconv.Itoa(randi)))
|
assert.Equal(6, len(strconv.Itoa(randi)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestRandStringConcurrent verifies RandString is safe under high concurrency.
|
||||||
|
// Before the fix, this test may panic or trigger data races.
|
||||||
|
// After the fix, it should always pass.
|
||||||
|
func TestRandStringConcurrent(t *testing.T) {
|
||||||
|
const (
|
||||||
|
goroutines = 100
|
||||||
|
iterations = 1000
|
||||||
|
length = 32
|
||||||
|
)
|
||||||
|
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
wg.Add(goroutines)
|
||||||
|
|
||||||
|
errCh := make(chan error, goroutines)
|
||||||
|
|
||||||
|
for g := 0; g < goroutines; g++ {
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
for i := 0; i < iterations; i++ {
|
||||||
|
s := RandString(length)
|
||||||
|
if len(s) != length {
|
||||||
|
errCh <- fmt.Errorf("unexpected string length: got %d, want %d", len(s), length)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
wg.Wait()
|
||||||
|
close(errCh)
|
||||||
|
}()
|
||||||
|
|
||||||
|
for err := range errCh {
|
||||||
|
t.Errorf("test failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(errCh) > 0 {
|
||||||
|
t.FailNow()
|
||||||
|
}
|
||||||
|
|
||||||
|
// wg.Wait()
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package slice
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestUniqueByFieldUnreadableInputs(t *testing.T) {
|
||||||
|
for _, input := range []any{nil, struct{ hidden string }{"value"}} {
|
||||||
|
if _, err := UniqueByField([]any{input}, "hidden"); err == nil {
|
||||||
|
t.Errorf("expected an error for %T", input)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+78
-50
@@ -74,6 +74,27 @@ func ContainSubSlice[T comparable](slice, subSlice []T) bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ContainAny check if the slice contains any element from the targets slice.
|
||||||
|
// Play: https://go.dev/play/p/4xoxhc9XSSw
|
||||||
|
func ContainAny[T comparable](slice []T, targets []T) bool {
|
||||||
|
if len(targets) == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
sliceMap := make(map[T]struct{}, len(slice))
|
||||||
|
for _, item := range slice {
|
||||||
|
sliceMap[item] = struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, target := range targets {
|
||||||
|
if _, exists := sliceMap[target]; exists {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
// Chunk creates a slice of elements split into groups the length of size.
|
// Chunk creates a slice of elements split into groups the length of size.
|
||||||
// Play: https://go.dev/play/p/b4Pou5j2L_C
|
// Play: https://go.dev/play/p/b4Pou5j2L_C
|
||||||
func Chunk[T any](slice []T, size int) [][]T {
|
func Chunk[T any](slice []T, size int) [][]T {
|
||||||
@@ -166,8 +187,8 @@ func DifferenceBy[T comparable](slice []T, comparedSlice []T, iteratee func(inde
|
|||||||
result := make([]T, 0)
|
result := make([]T, 0)
|
||||||
|
|
||||||
comparedMap := make(map[T]struct{}, len(comparedSlice))
|
comparedMap := make(map[T]struct{}, len(comparedSlice))
|
||||||
for _, item := range comparedSlice {
|
for i, item := range comparedSlice {
|
||||||
comparedMap[iteratee(0, item)] = struct{}{}
|
comparedMap[iteratee(i, item)] = struct{}{}
|
||||||
}
|
}
|
||||||
|
|
||||||
for i, item := range slice {
|
for i, item := range slice {
|
||||||
@@ -507,19 +528,17 @@ func flattenRecursive(value reflect.Value, result reflect.Value) reflect.Value {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ForEach iterates over elements of slice and invokes function for each element.
|
// ForEach iterates over elements of slice and invokes function for each element.
|
||||||
// Play: https://go.dev/play/p/DrPaa4YsHRF
|
|
||||||
func ForEach[T any](slice []T, iteratee func(index int, item T)) {
|
func ForEach[T any](slice []T, iteratee func(index int, item T)) {
|
||||||
for i := 0; i < len(slice); i++ {
|
for idx, elem := range slice {
|
||||||
iteratee(i, slice[i])
|
iteratee(idx, elem)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ForEachWithBreak iterates over elements of slice and invokes function for each element,
|
// ForEachWithBreak iterates over elements of slice and invokes function for each element,
|
||||||
// when iteratee return false, will break the for each loop.
|
// when function return false, will break the for each loop.
|
||||||
// Play: https://go.dev/play/p/qScs39f3D9W
|
|
||||||
func ForEachWithBreak[T any](slice []T, iteratee func(index int, item T) bool) {
|
func ForEachWithBreak[T any](slice []T, iteratee func(index int, item T) bool) {
|
||||||
for i := 0; i < len(slice); i++ {
|
for idx, elem := range slice {
|
||||||
if !iteratee(i, slice[i]) {
|
if !iteratee(idx, elem) {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -692,11 +711,15 @@ func IntSlice(slice any) []int {
|
|||||||
// DeleteAt delete the element of slice at index.
|
// DeleteAt delete the element of slice at index.
|
||||||
// Play: https://go.dev/play/p/800B1dPBYyd
|
// Play: https://go.dev/play/p/800B1dPBYyd
|
||||||
func DeleteAt[T any](slice []T, index int) []T {
|
func DeleteAt[T any](slice []T, index int) []T {
|
||||||
|
result := append([]T(nil), slice...)
|
||||||
|
if len(result) == 0 {
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
if index < 0 || index >= len(slice) {
|
if index < 0 || index >= len(slice) {
|
||||||
return slice[:len(slice)-1]
|
return result[:len(slice)-1]
|
||||||
}
|
}
|
||||||
|
|
||||||
result := append([]T(nil), slice...)
|
|
||||||
copy(result[index:], result[index+1:])
|
copy(result[index:], result[index+1:])
|
||||||
|
|
||||||
// Set the last element to zero value, clean up the memory.
|
// Set the last element to zero value, clean up the memory.
|
||||||
@@ -736,7 +759,8 @@ func Drop[T any](slice []T, n int) []T {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if n <= 0 {
|
if n <= 0 {
|
||||||
return slice
|
result := make([]T, 0, size)
|
||||||
|
return append(result, slice...)
|
||||||
}
|
}
|
||||||
|
|
||||||
result := make([]T, 0, size-n)
|
result := make([]T, 0, size-n)
|
||||||
@@ -754,7 +778,8 @@ func DropRight[T any](slice []T, n int) []T {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if n <= 0 {
|
if n <= 0 {
|
||||||
return slice
|
result := make([]T, 0, size)
|
||||||
|
return append(result, slice...)
|
||||||
}
|
}
|
||||||
|
|
||||||
result := make([]T, 0, size-n)
|
result := make([]T, 0, size-n)
|
||||||
@@ -800,7 +825,9 @@ func InsertAt[T any](slice []T, index int, value any) []T {
|
|||||||
size := len(slice)
|
size := len(slice)
|
||||||
|
|
||||||
if index < 0 || index > size {
|
if index < 0 || index > size {
|
||||||
return slice
|
result := make([]T, size)
|
||||||
|
copy(result, slice)
|
||||||
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
switch v := value.(type) {
|
switch v := value.(type) {
|
||||||
@@ -817,21 +844,21 @@ func InsertAt[T any](slice []T, index int, value any) []T {
|
|||||||
copy(result[index+len(v):], slice[index:])
|
copy(result[index+len(v):], slice[index:])
|
||||||
return result
|
return result
|
||||||
default:
|
default:
|
||||||
return slice
|
result := make([]T, size)
|
||||||
|
copy(result, slice)
|
||||||
|
return result
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateAt update the slice element at index.
|
// UpdateAt update the slice element at index.
|
||||||
// Play: https://go.dev/play/p/f3mh2KloWVm
|
// Play: https://go.dev/play/p/f3mh2KloWVm
|
||||||
func UpdateAt[T any](slice []T, index int, value T) []T {
|
func UpdateAt[T any](slice []T, index int, value T) []T {
|
||||||
if index < 0 || index >= len(slice) {
|
|
||||||
return slice
|
|
||||||
}
|
|
||||||
|
|
||||||
result := make([]T, len(slice))
|
result := make([]T, len(slice))
|
||||||
copy(result, slice)
|
copy(result, slice)
|
||||||
|
|
||||||
result[index] = value
|
if index >= 0 && index < len(slice) {
|
||||||
|
result[index] = value
|
||||||
|
}
|
||||||
|
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
@@ -925,10 +952,8 @@ func UniqueByField[T any](slice []T, field string) ([]T, error) {
|
|||||||
|
|
||||||
func getField[T any](item T, field string) (interface{}, error) {
|
func getField[T any](item T, field string) (interface{}, error) {
|
||||||
v := reflect.ValueOf(item)
|
v := reflect.ValueOf(item)
|
||||||
t := reflect.TypeOf(item)
|
|
||||||
|
|
||||||
if t.Kind() == reflect.Ptr {
|
if v.Kind() == reflect.Ptr {
|
||||||
t = t.Elem()
|
|
||||||
v = v.Elem()
|
v = v.Elem()
|
||||||
}
|
}
|
||||||
if v.Kind() != reflect.Struct {
|
if v.Kind() != reflect.Struct {
|
||||||
@@ -939,6 +964,9 @@ func getField[T any](item T, field string) (interface{}, error) {
|
|||||||
if !f.IsValid() {
|
if !f.IsValid() {
|
||||||
return nil, fmt.Errorf("field name %s not found", field)
|
return nil, fmt.Errorf("field name %s not found", field)
|
||||||
}
|
}
|
||||||
|
if !f.CanInterface() {
|
||||||
|
return nil, fmt.Errorf("field name %s is not exported", field)
|
||||||
|
}
|
||||||
|
|
||||||
return v.FieldByName(field).Interface(), nil
|
return v.FieldByName(field).Interface(), nil
|
||||||
}
|
}
|
||||||
@@ -991,6 +1019,9 @@ func Merge[T any](slices ...[]T) []T {
|
|||||||
// Play: https://go.dev/play/p/anJXfB5wq_t
|
// Play: https://go.dev/play/p/anJXfB5wq_t
|
||||||
func Intersection[T comparable](slices ...[]T) []T {
|
func Intersection[T comparable](slices ...[]T) []T {
|
||||||
result := []T{}
|
result := []T{}
|
||||||
|
if len(slices) == 0 {
|
||||||
|
return result
|
||||||
|
}
|
||||||
elementCount := make(map[T]int)
|
elementCount := make(map[T]int)
|
||||||
|
|
||||||
for _, slice := range slices {
|
for _, slice := range slices {
|
||||||
@@ -1021,7 +1052,9 @@ func SymmetricDifference[T comparable](slices ...[]T) []T {
|
|||||||
return []T{}
|
return []T{}
|
||||||
}
|
}
|
||||||
if len(slices) == 1 {
|
if len(slices) == 1 {
|
||||||
return Unique(slices[0])
|
result := make([]T, len(slices[0]))
|
||||||
|
copy(result, slices[0])
|
||||||
|
return Unique(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
result := make([]T, 0)
|
result := make([]T, 0)
|
||||||
@@ -1042,6 +1075,7 @@ func SymmetricDifference[T comparable](slices ...[]T) []T {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Reverse return slice of element order is reversed to the given slice.
|
// Reverse return slice of element order is reversed to the given slice.
|
||||||
|
// Reverse modifies the slice in place.
|
||||||
// Play: https://go.dev/play/p/8uI8f1lwNrQ
|
// Play: https://go.dev/play/p/8uI8f1lwNrQ
|
||||||
func Reverse[T any](slice []T) {
|
func Reverse[T any](slice []T) {
|
||||||
for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
|
for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
|
||||||
@@ -1049,7 +1083,8 @@ func Reverse[T any](slice []T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReverseCopy return a new slice of element order is reversed to the given slice.
|
// ReverseCopy return a new slice of element where the order is reversed to the given
|
||||||
|
// slice.
|
||||||
// Play: https://go.dev/play/p/c9arEaP7Cg-
|
// Play: https://go.dev/play/p/c9arEaP7Cg-
|
||||||
func ReverseCopy[T any](slice []T) []T {
|
func ReverseCopy[T any](slice []T) []T {
|
||||||
result := make([]T, len(slice))
|
result := make([]T, len(slice))
|
||||||
@@ -1067,7 +1102,7 @@ func Shuffle[T any](slice []T) []T {
|
|||||||
rand.Seed(time.Now().UnixNano())
|
rand.Seed(time.Now().UnixNano())
|
||||||
|
|
||||||
rand.Shuffle(len(slice), func(i, j int) {
|
rand.Shuffle(len(slice), func(i, j int) {
|
||||||
slice[i], slice[j] = slice[j], slice[i]
|
swap(slice, i, j)
|
||||||
})
|
})
|
||||||
|
|
||||||
return slice
|
return slice
|
||||||
@@ -1240,11 +1275,12 @@ func SortByField[T any](slice []T, field string, sortType ...string) error {
|
|||||||
// Without creates a slice excluding all given items.
|
// Without creates a slice excluding all given items.
|
||||||
// Play: https://go.dev/play/p/bwhEXEypThg
|
// Play: https://go.dev/play/p/bwhEXEypThg
|
||||||
func Without[T comparable](slice []T, items ...T) []T {
|
func Without[T comparable](slice []T, items ...T) []T {
|
||||||
|
result := make([]T, 0, len(slice))
|
||||||
|
|
||||||
if len(items) == 0 || len(slice) == 0 {
|
if len(items) == 0 || len(slice) == 0 {
|
||||||
return slice
|
return append(result, slice...)
|
||||||
}
|
}
|
||||||
|
|
||||||
result := make([]T, 0, len(slice))
|
|
||||||
for _, v := range slice {
|
for _, v := range slice {
|
||||||
if !Contain(items, v) {
|
if !Contain(items, v) {
|
||||||
result = append(result, v)
|
result = append(result, v)
|
||||||
@@ -1465,36 +1501,28 @@ func Random[T any](slice []T) (val T, idx int) {
|
|||||||
return slice[idx], idx
|
return slice[idx], idx
|
||||||
}
|
}
|
||||||
|
|
||||||
// RightPadding adds padding to the right end of a slice.
|
// RightPadding returns a copy of the slice padding the given value to the right end of a slice.
|
||||||
|
// If paddingLength is zero or less, the function returns a copy of the slice.
|
||||||
// Play: https://go.dev/play/p/0_2rlLEMBXL
|
// Play: https://go.dev/play/p/0_2rlLEMBXL
|
||||||
func RightPadding[T any](slice []T, paddingValue T, paddingLength int) []T {
|
func RightPadding[T any](slice []T, paddingValue T, paddingLength int) []T {
|
||||||
if paddingLength == 0 {
|
suffix := []T{}
|
||||||
return slice
|
if paddingLength > 0 {
|
||||||
|
suffix = repeat([]T{paddingValue}, paddingLength)
|
||||||
}
|
}
|
||||||
for i := 0; i < paddingLength; i++ {
|
padded := concat(slice, suffix)
|
||||||
slice = append(slice, paddingValue)
|
return padded
|
||||||
}
|
|
||||||
return slice
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// LeftPadding adds padding to the left begin of a slice.
|
// LeftPadding returns a copy of the slice padding the given value to the left begin of a slice.
|
||||||
|
// If paddingLength is zero or less, the function returns a copy of the slice.
|
||||||
// Play: https://go.dev/play/p/jlQVoelLl2k
|
// Play: https://go.dev/play/p/jlQVoelLl2k
|
||||||
func LeftPadding[T any](slice []T, paddingValue T, paddingLength int) []T {
|
func LeftPadding[T any](slice []T, paddingValue T, paddingLength int) []T {
|
||||||
if paddingLength == 0 {
|
prefix := []T{}
|
||||||
return slice
|
if paddingLength > 0 {
|
||||||
|
prefix = repeat([]T{paddingValue}, paddingLength)
|
||||||
}
|
}
|
||||||
|
padded := concat(prefix, slice)
|
||||||
paddedSlice := make([]T, len(slice)+paddingLength)
|
return padded
|
||||||
i := 0
|
|
||||||
for ; i < paddingLength; i++ {
|
|
||||||
paddedSlice[i] = paddingValue
|
|
||||||
}
|
|
||||||
for j := 0; j < len(slice); j++ {
|
|
||||||
paddedSlice[i] = slice[j]
|
|
||||||
i++
|
|
||||||
}
|
|
||||||
|
|
||||||
return paddedSlice
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Frequency counts the frequency of each element in the slice.
|
// Frequency counts the frequency of each element in the slice.
|
||||||
|
|||||||
@@ -58,6 +58,24 @@ func ExampleContainSubSlice() {
|
|||||||
// false
|
// false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ExampleContainAny() {
|
||||||
|
result1 := ContainAny([]string{"a", "b", "c"}, []string{"a"})
|
||||||
|
result2 := ContainAny([]string{"a", "b", "c"}, []string{"d", "e"})
|
||||||
|
result3 := ContainAny([]string{"a", "b", "c"}, []string{"d", "a"})
|
||||||
|
result4 := ContainAny([]string{"a", "b", "c"}, []string{})
|
||||||
|
|
||||||
|
fmt.Println(result1)
|
||||||
|
fmt.Println(result2)
|
||||||
|
fmt.Println(result3)
|
||||||
|
fmt.Println(result4)
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// true
|
||||||
|
// false
|
||||||
|
// true
|
||||||
|
// false
|
||||||
|
}
|
||||||
|
|
||||||
func ExampleChunk() {
|
func ExampleChunk() {
|
||||||
arr := []string{"a", "b", "c", "d", "e"}
|
arr := []string{"a", "b", "c", "d", "e"}
|
||||||
|
|
||||||
@@ -831,7 +849,7 @@ func ExampleUniqueByComparator() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
caseInsensitiveStrings := UniqueByComparator([]string{"apple", "banana", "Apple", "cherry", "Banana", "date"}, func(item string, other string) bool {
|
caseInsensitiveStrings := UniqueByComparator([]string{"apple", "banana", "Apple", "cherry", "Banana", "date"}, func(item string, other string) bool {
|
||||||
return strings.ToLower(item) == strings.ToLower(other)
|
return strings.EqualFold(item, other)
|
||||||
})
|
})
|
||||||
|
|
||||||
fmt.Println(uniqueNums)
|
fmt.Println(uniqueNums)
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package slice
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"math/bits"
|
||||||
"reflect"
|
"reflect"
|
||||||
|
|
||||||
"golang.org/x/exp/constraints"
|
"golang.org/x/exp/constraints"
|
||||||
@@ -96,3 +97,71 @@ func partitionAnySlice[T any](slice []T, lowIndex, highIndex int, less func(a, b
|
|||||||
func swap[T any](slice []T, i, j int) {
|
func swap[T any](slice []T, i, j int) {
|
||||||
slice[i], slice[j] = slice[j], slice[i]
|
slice[i], slice[j] = slice[j], slice[i]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// `repeat` returns a new slice that repeats the provided slice the given number of
|
||||||
|
// times. The result has length and capacity (len(x) * count). The result is never nil.
|
||||||
|
// Repeat panics if count is negative or if the result of (len(x) * count) overflows.
|
||||||
|
//
|
||||||
|
// repeat has been provided in the standard lib within the package `slices` under the
|
||||||
|
// name Repeat since GO version 1.21 onwards. As lancet commits to compatibility with GO
|
||||||
|
// 1.18 onwards, we implement the functionality as an internal function.
|
||||||
|
func repeat[S ~[]E, E any](x S, count int) S {
|
||||||
|
if count < 0 {
|
||||||
|
panic("count cannot be negative")
|
||||||
|
}
|
||||||
|
|
||||||
|
const maxInt = ^uint(0) >> 1
|
||||||
|
hi, lo := bits.Mul(uint(len(x)), uint(count))
|
||||||
|
if hi > 0 || lo > maxInt {
|
||||||
|
panic("the result of (len(x) * count) overflows")
|
||||||
|
}
|
||||||
|
|
||||||
|
newslice := make(S, int(lo)) // lo = len(x) * count
|
||||||
|
n := copy(newslice, x)
|
||||||
|
for n < len(newslice) {
|
||||||
|
n += copy(newslice[n:], newslice[:n])
|
||||||
|
}
|
||||||
|
return newslice
|
||||||
|
}
|
||||||
|
|
||||||
|
// concat returns a new slice concatenating the passed in slices.
|
||||||
|
//
|
||||||
|
// concat has been provided in the standard lib within the package `slices` under the
|
||||||
|
// name Concat since GO version 1.21 onwards. As lancet commits to compatibility with GO
|
||||||
|
// 1.18 onwards, we implement the functionality as an internal function.
|
||||||
|
func concat[S ~[]E, E any](slices ...S) S {
|
||||||
|
size := 0
|
||||||
|
for _, s := range slices {
|
||||||
|
size += len(s)
|
||||||
|
if size < 0 {
|
||||||
|
panic("len out of range")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Use Grow, not make, to round up to the size class:
|
||||||
|
// the extra space is otherwise unused and helps
|
||||||
|
// callers that append a few elements to the result.
|
||||||
|
newslice := grow[S](nil, size)
|
||||||
|
for _, s := range slices {
|
||||||
|
newslice = append(newslice, s...)
|
||||||
|
}
|
||||||
|
return newslice
|
||||||
|
}
|
||||||
|
|
||||||
|
// grow increases the slice's capacity, if necessary, to guarantee space for
|
||||||
|
// another n elements. After grow(n), at least n elements can be appended
|
||||||
|
// to the slice without another allocation. If n is negative or too large to
|
||||||
|
// allocate the memory, grow panics.
|
||||||
|
//
|
||||||
|
// grow has been provided in the standard lib within the package `slices` under the
|
||||||
|
// name Grow since GO version 1.21 onwards. As lancet commits to compatibility with GO
|
||||||
|
// 1.18 onwards, we implement the functionality as an internal function.
|
||||||
|
func grow[S ~[]E, E any](s S, n int) S {
|
||||||
|
if n < 0 {
|
||||||
|
panic("cannot be negative")
|
||||||
|
}
|
||||||
|
if n -= cap(s) - len(s); n > 0 {
|
||||||
|
// This expression allocates only once.
|
||||||
|
s = append(s[:cap(s)], make([]E, n)...)[:len(s)]
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
+61
-1
@@ -89,6 +89,46 @@ func TestContainSubSlice(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestContainAny(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
assert := internal.NewAssert(t, "TestContainAny")
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
slice []string
|
||||||
|
targets []string
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{[]string{"a", "b", "c"}, []string{"a"}, true},
|
||||||
|
{[]string{"a", "b", "c"}, []string{"a", "b"}, true},
|
||||||
|
{[]string{"a", "b", "c"}, []string{"d", "e"}, false},
|
||||||
|
{[]string{"a", "b", "c"}, []string{"d", "a"}, true},
|
||||||
|
{[]string{"a", "b", "c"}, []string{}, false},
|
||||||
|
{[]string{}, []string{"a"}, false},
|
||||||
|
{[]string{}, []string{}, false},
|
||||||
|
{[]string{"a", "b", "c"}, []string{"c", "d", "e"}, true},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
assert.Equal(tt.want, ContainAny(tt.slice, tt.targets))
|
||||||
|
}
|
||||||
|
|
||||||
|
intTests := []struct {
|
||||||
|
slice []int
|
||||||
|
targets []int
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{[]int{1, 2, 3, 4, 5}, []int{3}, true},
|
||||||
|
{[]int{1, 2, 3, 4, 5}, []int{6, 7}, false},
|
||||||
|
{[]int{1, 2, 3, 4, 5}, []int{5, 6, 7}, true},
|
||||||
|
{[]int{1, 2, 3, 4, 5}, []int{}, false},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range intTests {
|
||||||
|
assert.Equal(tt.want, ContainAny(tt.slice, tt.targets))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestChunk(t *testing.T) {
|
func TestChunk(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
@@ -761,6 +801,8 @@ func TestDeleteAt(t *testing.T) {
|
|||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
assert := internal.NewAssert(t, "TestDeleteAt")
|
assert := internal.NewAssert(t, "TestDeleteAt")
|
||||||
|
assert.Equal(0, len(DeleteAt([]int(nil), 0)))
|
||||||
|
assert.Equal(0, len(DeleteAt([]int{}, -1)))
|
||||||
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
slice []int
|
slice []int
|
||||||
@@ -1008,7 +1050,7 @@ func TestUniqueByComparator(t *testing.T) {
|
|||||||
t.Run("case-insensitive string comparison", func(t *testing.T) {
|
t.Run("case-insensitive string comparison", func(t *testing.T) {
|
||||||
stringSlice := []string{"apple", "banana", "Apple", "cherry", "Banana", "date"}
|
stringSlice := []string{"apple", "banana", "Apple", "cherry", "Banana", "date"}
|
||||||
caseInsensitiveComparator := func(item, other string) bool {
|
caseInsensitiveComparator := func(item, other string) bool {
|
||||||
return strings.ToLower(item) == strings.ToLower(other)
|
return strings.EqualFold(item, other)
|
||||||
}
|
}
|
||||||
|
|
||||||
result := UniqueByComparator(stringSlice, caseInsensitiveComparator)
|
result := UniqueByComparator(stringSlice, caseInsensitiveComparator)
|
||||||
@@ -1063,6 +1105,7 @@ func TestIntersection(t *testing.T) {
|
|||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
assert := internal.NewAssert(t, "TestIntersection")
|
assert := internal.NewAssert(t, "TestIntersection")
|
||||||
|
assert.Equal([]int{}, Intersection[int]())
|
||||||
|
|
||||||
s1 := []int{1, 2, 2, 3}
|
s1 := []int{1, 2, 2, 3}
|
||||||
s2 := []int{1, 2, 3, 4}
|
s2 := []int{1, 2, 3, 4}
|
||||||
@@ -1163,6 +1206,9 @@ func TestDifferenceBy(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
assert.Equal([]int{1, 2}, DifferenceBy(s1, s2, addOne))
|
assert.Equal([]int{1, 2}, DifferenceBy(s1, s2, addOne))
|
||||||
|
assert.Equal([]int{}, DifferenceBy([]int{10, 10}, []int{10, 10}, func(i, v int) int {
|
||||||
|
return i + v
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestIsAscending(t *testing.T) {
|
func TestIsAscending(t *testing.T) {
|
||||||
@@ -1756,6 +1802,20 @@ func TestRightPaddingAndLeftPadding(t *testing.T) {
|
|||||||
|
|
||||||
padded := LeftPadding(RightPadding(nums, 0, 3), 0, 3)
|
padded := LeftPadding(RightPadding(nums, 0, 3), 0, 3)
|
||||||
assert.Equal([]int{0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0}, padded)
|
assert.Equal([]int{0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0}, padded)
|
||||||
|
|
||||||
|
// Test with negative padding length
|
||||||
|
paddedNegative := LeftPadding(RightPadding(nums, 0, -3), 0, -3)
|
||||||
|
assert.Equal([]int{1, 2, 3, 4, 5}, paddedNegative)
|
||||||
|
|
||||||
|
// Test with empty slice
|
||||||
|
empty := []int{}
|
||||||
|
paddedEmpty := LeftPadding(RightPadding(empty, 0, 3), 0, 3)
|
||||||
|
assert.Equal([]int{0, 0, 0, 0, 0, 0}, paddedEmpty)
|
||||||
|
|
||||||
|
// Test with nil
|
||||||
|
nilSlice := []int(nil)
|
||||||
|
paddedNil := LeftPadding(RightPadding(nilSlice, 0, 3), 0, 3)
|
||||||
|
assert.Equal([]int{0, 0, 0, 0, 0, 0}, paddedNil)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestUniqueByConcurrent(t *testing.T) {
|
func TestUniqueByConcurrent(t *testing.T) {
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package stream
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestLimitLargerThanSource(t *testing.T) {
|
||||||
|
got := Of(1, 2).Limit(math.MaxInt).ToSlice()
|
||||||
|
if len(got) != 2 || got[0] != 1 || got[1] != 2 {
|
||||||
|
t.Errorf("unexpected limited stream: %v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package stream
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestFromRangeSmallIntegerSpan(t *testing.T) {
|
||||||
|
got := FromRange[int8](-120, 120, 10).ToSlice()
|
||||||
|
if len(got) != 25 || got[0] != -120 || got[len(got)-1] != 120 {
|
||||||
|
t.Errorf("unexpected range: %v", got)
|
||||||
|
}
|
||||||
|
if got := FromRange[uint8](250, 255, 5).ToSlice(); len(got) != 2 || got[1] != 255 {
|
||||||
|
t.Errorf("unexpected unsigned range: %v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
+11
-5
@@ -101,11 +101,14 @@ func FromRange[T constraints.Integer | constraints.Float](start, end, step T) St
|
|||||||
panic("stream.FromRange: param step should be positive")
|
panic("stream.FromRange: param step should be positive")
|
||||||
}
|
}
|
||||||
|
|
||||||
l := int((end-start)/step) + 1
|
source := make([]T, 0)
|
||||||
source := make([]T, l)
|
for value := start; value <= end; {
|
||||||
|
source = append(source, value)
|
||||||
for i := 0; i < l; i++ {
|
next := value + step
|
||||||
source[i] = start + (T(i) * step)
|
if next <= value {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
value = next
|
||||||
}
|
}
|
||||||
|
|
||||||
return FromSlice(source)
|
return FromSlice(source)
|
||||||
@@ -219,6 +222,9 @@ func (s Stream[T]) Limit(maxSize int) Stream[T] {
|
|||||||
if maxSize < 0 {
|
if maxSize < 0 {
|
||||||
return FromSlice([]T{})
|
return FromSlice([]T{})
|
||||||
}
|
}
|
||||||
|
if maxSize > len(s.source) {
|
||||||
|
maxSize = len(s.source)
|
||||||
|
}
|
||||||
|
|
||||||
source := make([]T, 0, maxSize)
|
source := make([]T, 0, maxSize)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package structs
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestFieldIsEmbeddedUsesAnonymousFlag(t *testing.T) {
|
||||||
|
type Embedded struct{ Promoted int }
|
||||||
|
s := New(struct {
|
||||||
|
Embedded
|
||||||
|
Named Embedded
|
||||||
|
}{})
|
||||||
|
for _, tt := range []struct {
|
||||||
|
name string
|
||||||
|
want bool
|
||||||
|
}{{"Embedded", true}, {"Promoted", true}, {"Named", false}} {
|
||||||
|
field, ok := s.Field(tt.name)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("field %s missing", tt.name)
|
||||||
|
}
|
||||||
|
if got := field.IsEmbedded(); got != tt.want {
|
||||||
|
t.Errorf("%s: got %v, want %v", tt.name, got, tt.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+10
-1
@@ -26,26 +26,31 @@ func newField(v reflect.Value, f reflect.StructField, tagName string) *Field {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Tag returns the value that the key in the tag string.
|
// Tag returns the value that the key in the tag string.
|
||||||
|
// Play: https://go.dev/play/p/DVrx5HvvUJr
|
||||||
func (f *Field) Tag() *Tag {
|
func (f *Field) Tag() *Tag {
|
||||||
return f.tag
|
return f.tag
|
||||||
}
|
}
|
||||||
|
|
||||||
// Value returns the underlying value of the field.
|
// Value returns the underlying value of the field.
|
||||||
|
// Play: https://go.dev/play/p/qufYEU2o4Oi
|
||||||
func (f *Field) Value() any {
|
func (f *Field) Value() any {
|
||||||
return f.rvalue.Interface()
|
return f.rvalue.Interface()
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsEmbedded returns true if the given field is an embedded field.
|
// IsEmbedded returns true if the given field is an embedded field.
|
||||||
|
// Play: https://go.dev/play/p/wV2PrbYm3Ec
|
||||||
func (f *Field) IsEmbedded() bool {
|
func (f *Field) IsEmbedded() bool {
|
||||||
return len(f.field.Index) > 1
|
return f.field.Anonymous || len(f.field.Index) > 1
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsExported returns true if the given field is exported.
|
// IsExported returns true if the given field is exported.
|
||||||
|
// Play: https://go.dev/play/p/csK4AXYaNbJ
|
||||||
func (f *Field) IsExported() bool {
|
func (f *Field) IsExported() bool {
|
||||||
return f.field.IsExported()
|
return f.field.IsExported()
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsZero returns true if the given field is zero value.
|
// IsZero returns true if the given field is zero value.
|
||||||
|
// Play: https://go.dev/play/p/RzqpGISf87r
|
||||||
func (f *Field) IsZero() bool {
|
func (f *Field) IsZero() bool {
|
||||||
z := reflect.Zero(f.rvalue.Type()).Interface()
|
z := reflect.Zero(f.rvalue.Type()).Interface()
|
||||||
v := f.Value()
|
v := f.Value()
|
||||||
@@ -63,22 +68,26 @@ func (f *Field) IsNil() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Name returns the name of the given field
|
// Name returns the name of the given field
|
||||||
|
// Play: https://go.dev/play/p/zfIGlqsatee
|
||||||
func (f *Field) Name() string {
|
func (f *Field) Name() string {
|
||||||
return f.field.Name
|
return f.field.Name
|
||||||
}
|
}
|
||||||
|
|
||||||
// Kind returns the field's kind
|
// Kind returns the field's kind
|
||||||
|
// Play: https://go.dev/play/p/wg4NlcUNG5o
|
||||||
func (f *Field) Kind() reflect.Kind {
|
func (f *Field) Kind() reflect.Kind {
|
||||||
return f.rvalue.Kind()
|
return f.rvalue.Kind()
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsSlice check if a struct field type is slice or not
|
// IsSlice check if a struct field type is slice or not
|
||||||
|
// Play: https://go.dev/play/p/MKz4CgBIUrU
|
||||||
func (f *Field) IsSlice() bool {
|
func (f *Field) IsSlice() bool {
|
||||||
k := f.rvalue.Kind()
|
k := f.rvalue.Kind()
|
||||||
return k == reflect.Slice
|
return k == reflect.Slice
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsTargetType check if a struct field type is target type or not
|
// IsTargetType check if a struct field type is target type or not
|
||||||
|
// Play: https://go.dev/play/p/Ig75P-agN39
|
||||||
func (f *Field) IsTargetType(targetType reflect.Kind) bool {
|
func (f *Field) IsTargetType(targetType reflect.Kind) bool {
|
||||||
return f.rvalue.Kind() == targetType
|
return f.rvalue.Kind() == targetType
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ type Struct struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// New returns a new *Struct
|
// New returns a new *Struct
|
||||||
|
// Play: https://go.dev/play/p/O29l8kk-Z17
|
||||||
func New(value any, tagName ...string) *Struct {
|
func New(value any, tagName ...string) *Struct {
|
||||||
value = pointer.ExtractPointer(value)
|
value = pointer.ExtractPointer(value)
|
||||||
v := reflect.ValueOf(value)
|
v := reflect.ValueOf(value)
|
||||||
@@ -60,6 +61,7 @@ func New(value any, tagName ...string) *Struct {
|
|||||||
// Name string `json:"myName"`
|
// Name string `json:"myName"`
|
||||||
//
|
//
|
||||||
// ToMap convert the exported fields of a struct to map.
|
// ToMap convert the exported fields of a struct to map.
|
||||||
|
// Play: https://go.dev/play/p/qQbLySBgerZ
|
||||||
func (s *Struct) ToMap() (map[string]any, error) {
|
func (s *Struct) ToMap() (map[string]any, error) {
|
||||||
if !s.IsStruct() {
|
if !s.IsStruct() {
|
||||||
return nil, fmt.Errorf("invalid struct %v", s)
|
return nil, fmt.Errorf("invalid struct %v", s)
|
||||||
@@ -87,6 +89,7 @@ func (s *Struct) ToMap() (map[string]any, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Fields returns all the struct fields within a slice
|
// Fields returns all the struct fields within a slice
|
||||||
|
// Play: https://go.dev/play/p/w3Kk_CyVY7D
|
||||||
func (s *Struct) Fields() []*Field {
|
func (s *Struct) Fields() []*Field {
|
||||||
fieldNum := s.rvalue.NumField()
|
fieldNum := s.rvalue.NumField()
|
||||||
fields := make([]*Field, 0, fieldNum)
|
fields := make([]*Field, 0, fieldNum)
|
||||||
@@ -100,6 +103,7 @@ func (s *Struct) Fields() []*Field {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Field returns a Field if the given field name was found
|
// Field returns a Field if the given field name was found
|
||||||
|
// Play: https://go.dev/play/p/KocZMSYarza
|
||||||
func (s *Struct) Field(name string) (*Field, bool) {
|
func (s *Struct) Field(name string) (*Field, bool) {
|
||||||
f, ok := s.rtype.FieldByName(name)
|
f, ok := s.rtype.FieldByName(name)
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -109,6 +113,7 @@ func (s *Struct) Field(name string) (*Field, bool) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// IsStruct returns true if the given rvalue is a struct
|
// IsStruct returns true if the given rvalue is a struct
|
||||||
|
// Play: https://go.dev/play/p/bU2FSdkbK1C
|
||||||
func (s *Struct) IsStruct() bool {
|
func (s *Struct) IsStruct() bool {
|
||||||
k := s.rvalue.Kind()
|
k := s.rvalue.Kind()
|
||||||
if k == reflect.Invalid {
|
if k == reflect.Invalid {
|
||||||
@@ -119,6 +124,13 @@ func (s *Struct) IsStruct() bool {
|
|||||||
|
|
||||||
// ToMap convert struct to map, only convert exported struct field
|
// ToMap convert struct to map, only convert exported struct field
|
||||||
// map key is specified same as struct field tag `json` value.
|
// map key is specified same as struct field tag `json` value.
|
||||||
|
// Play: https://go.dev/play/p/qQbLySBgerZ
|
||||||
func ToMap(v any) (map[string]any, error) {
|
func ToMap(v any) (map[string]any, error) {
|
||||||
return New(v).ToMap()
|
return New(v).ToMap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TypeName return struct type name
|
||||||
|
// Play: https://go.dev/play/p/SWLWd0XBaBb
|
||||||
|
func (s *Struct) TypeName() string {
|
||||||
|
return s.rtype.Name()
|
||||||
|
}
|
||||||
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user