1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

Compare commits

...

22 Commits

Author SHA1 Message Date
残念
5b3a59e785 Merge pull request #334 from duke-git/v2
Add enum package
2025-10-25 12:32:12 +08:00
chentong
74abb2d3f1 feat(struct): add struct name function (#328)
* feat(struct): add struct name function

- Add Name() method to Struct type to return the struct name
- Implement unit tests for the new Name() method

* refactor(structs): rename Struct.Name to Struct.TypeName

- Rename method Name to TypeName for clarity and accuracy
- Update corresponding test cases
2025-10-23 11:20:43 +08:00
dudaodong
3f12b34eea fix: fix issue for PR #334, usge Pair struct to instance enum items 2025-10-16 18:43:24 +08:00
dudaodong
cd43004a91 feat: add example for enum package 2025-10-14 16:37:02 +08:00
dudaodong
3ac9461c00 Merge branch 'rc' into v2 2025-09-30 14:57:01 +08:00
dudaodong
309b07ae8a feat: a simple enum implementation 2025-09-30 14:56:25 +08:00
chentong
8fe56b6dc7 fix(eventbus): update error handler to include topic information (#333)
* fix(eventbus): update error handler to include topic information

- Modified error handler signature to accept topic string and error
- Updated panic recovery logic to pass event topic to error handler
- Adjusted SetErrorHandler method parameter signature
- Updated example test to demonstrate new error handler usage
- Enhanced error handling test to verify topic information

* fix(eventbus): unit test
2025-09-28 20:10:12 +08:00
残念
15a0dad0d8 Merge pull request #330 from zoulux/main
fix: return 0 when Average is called with empty slice
2025-09-23 11:22:30 +08:00
jake
93c777a418 Update mathutil.go
fix: return 0 when Average is called with empty slice
2025-09-22 10:04:23 +08:00
jake
5ff1c6578f Merge branch 'duke-git:main' into main 2025-09-22 09:53:09 +08:00
dudaodong
7d4b9510a2 feat: add IsChineseHMPassport 2025-08-21 14:13:43 +08:00
dudaodong
9f0ad2354a feat: update some test fucntions 2025-08-21 10:52:44 +08:00
dudaodong
55b66dee99 Merge branch 'rc' into v2 2025-08-21 10:08:21 +08:00
Idichekop
4c64a16204 fix(package): [slice] functions with inconsistent return behaviour (#326)
* Some functions modified

* Fixes in all the functions of slice.go

* Re-use of swap function internal.
2025-08-19 10:50:25 +08:00
dudaodong
385e64cc52 feat: add IsPassport 2025-08-13 14:01:24 +08:00
dudaodong
be45a259db Merge branch 'v2' into rc 2025-08-13 11:24:27 +08:00
Idichekop
6f703fe577 fix(package): [slice] Fix RigthPadding and LeftPadding (#322)
* Fixes in  RightPadding and LeftPadding

* Tests cover padding empty, nil, and negative lenght

* Implemented repeat, concat, and grow functionalities as internal.
2025-08-04 10:45:29 +08:00
Idichekop
cb8d93c499 Simple refactor of ForEach functions (#323) 2025-07-30 14:28:27 +08:00
idichekop
ae1014c572 fix(package):[function] Corrected behaviour of Nand predicate (#319) 2025-07-22 10:08:50 +08:00
dudaodong
d5b9e67330 fix: fix go lint issue 2025-07-07 11:18:34 +08:00
dudaodong
a81403766f feat: add ToPointers, FromPointer, FromPointers 2025-07-07 11:16:44 +08:00
jake
83c069e234 Update slice_concurrent.go 2025-06-24 19:14:37 +08:00
24 changed files with 1430 additions and 192 deletions

View File

@@ -228,6 +228,42 @@ func ToPointer[T any](value T) *T {
return &value
}
// ToPointers convert a slice of values to a slice of pointers.
// Play: todo
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: todo
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: todo
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.
// 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 {
@@ -406,15 +442,15 @@ func ToStdBase64(value any) string {
if value == nil || (reflect.ValueOf(value).Kind() == reflect.Ptr && reflect.ValueOf(value).IsNil()) {
return ""
}
switch value.(type) {
switch v := value.(type) {
case []byte:
return base64.StdEncoding.EncodeToString(value.([]byte))
return base64.StdEncoding.EncodeToString(v)
case string:
return base64.StdEncoding.EncodeToString([]byte(value.(string)))
return base64.StdEncoding.EncodeToString([]byte(v))
case error:
return base64.StdEncoding.EncodeToString([]byte(value.(error).Error()))
return base64.StdEncoding.EncodeToString([]byte(v.Error()))
default:
marshal, err := json.Marshal(value)
marshal, err := json.Marshal(v)
if err != nil {
return ""
}
@@ -428,15 +464,15 @@ func ToUrlBase64(value any) string {
if value == nil || (reflect.ValueOf(value).Kind() == reflect.Ptr && reflect.ValueOf(value).IsNil()) {
return ""
}
switch value.(type) {
switch v := value.(type) {
case []byte:
return base64.URLEncoding.EncodeToString(value.([]byte))
return base64.URLEncoding.EncodeToString(v)
case string:
return base64.URLEncoding.EncodeToString([]byte(value.(string)))
return base64.URLEncoding.EncodeToString([]byte(v))
case error:
return base64.URLEncoding.EncodeToString([]byte(value.(error).Error()))
return base64.URLEncoding.EncodeToString([]byte(v.Error()))
default:
marshal, err := json.Marshal(value)
marshal, err := json.Marshal(v)
if err != nil {
return ""
}
@@ -450,7 +486,7 @@ func ToRawStdBase64(value any) string {
if value == nil || (reflect.ValueOf(value).Kind() == reflect.Ptr && reflect.ValueOf(value).IsNil()) {
return ""
}
switch value.(type) {
switch v := value.(type) {
case []byte:
return base64.RawStdEncoding.EncodeToString(value.([]byte))
case string:
@@ -458,7 +494,7 @@ func ToRawStdBase64(value any) string {
case error:
return base64.RawStdEncoding.EncodeToString([]byte(value.(error).Error()))
default:
marshal, err := json.Marshal(value)
marshal, err := json.Marshal(v)
if err != nil {
return ""
}
@@ -472,7 +508,7 @@ func ToRawUrlBase64(value any) string {
if value == nil || (reflect.ValueOf(value).Kind() == reflect.Ptr && reflect.ValueOf(value).IsNil()) {
return ""
}
switch value.(type) {
switch v := value.(type) {
case []byte:
return base64.RawURLEncoding.EncodeToString(value.([]byte))
case string:
@@ -480,7 +516,7 @@ func ToRawUrlBase64(value any) string {
case error:
return base64.RawURLEncoding.EncodeToString([]byte(value.(error).Error()))
default:
marshal, err := json.Marshal(value)
marshal, err := json.Marshal(v)
if err != nil {
return ""
}

View File

@@ -302,6 +302,75 @@ func TestToPointer(t *testing.T) {
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) {
t.Parallel()

View File

@@ -1,51 +1,51 @@
-----BEGIN rsa private key-----
MIIJKAIBAAKCAgEAw0anfgtraA2uaZwoLpLBvo1EkfYvDBgeXoMQ4WMKbcw6jU8k
18E+f3WM52I2RssEk6g0X1vIiarHZU5qyxbv2iN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2aUmZE+BagOQ/HAIKPbhmyMEA3
odgqaALsvD/58iVv9syqEEm5trLYA/p2uo0yv3iHrEggEZkjPXkrgbZ6lZNafGaZ
Hs0ANg+7NIJR9joKvXGJkg8E2thpg9UKl/Z2astZk7o92trMp5DQW1vjV7JW+mEQ
dztQxE5NgeE8cI/BdqMSyvG2UA7u5LqBHXx35s3gPva+eutKnTcRpO3T01PH2sba
iXiiNG5oFUYjocikhY7f3TUCAwEAAQ==
-----END rsa public key-----

View File

@@ -620,7 +620,7 @@ func main() {
### <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>
@@ -650,7 +650,7 @@ func main() {
// Output:
// false
// false
// true
// true
}
```

312
enum/enum.go Normal file
View File

@@ -0,0 +1,312 @@
// 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
}
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.
func NewItems[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
}
func (e *Item[T]) Value() T {
return e.value
}
func (e *Item[T]) Name() string {
return e.name
}
func (e *Item[T]) String() string {
return e.name
}
// Valid checks if the enum item is valid. If a custom check function is provided, it will be used to validate the value.
func (e *Item[T]) Valid(checker ...func(T) bool) bool {
if len(checker) > 0 {
return checker[0](e.value) && e.name != ""
}
var zero T
return e.value != zero && e.name != ""
}
// MarshalJSON implements the json.Marshaler interface.
func (e *Item[T]) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]any{
"value": e.value,
"name": e.name,
})
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (e *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)
e.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)
e.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)
e.value = converted.Interface().(T)
case reflect.String:
val, ok := temp.Value.(string)
if !ok {
return fmt.Errorf("invalid type for value, want string")
}
e.value = any(val).(T)
case reflect.Bool:
val, ok := temp.Value.(bool)
if !ok {
return fmt.Errorf("invalid type for value, want bool")
}
e.value = any(val).(T)
default:
// 枚举类型底层通常是 int可以尝试 float64->int64->底层类型
val, ok := temp.Value.(float64)
if ok {
converted := reflect.ValueOf(int64(val)).Convert(rv)
e.value = converted.Interface().(T)
} else {
val2, ok2 := temp.Value.(T)
if !ok2 {
return fmt.Errorf("invalid type for value")
}
e.value = val2
}
}
e.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]
}
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.
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.
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.
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.
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.
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.
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.
func (r *Registry[T]) Contains(value T) bool {
_, ok := r.GetByValue(value)
return ok
}
// Validate checks if the given value is a valid enum item in the registry.
func (r *Registry[T]) Validate(value T) error {
if !r.Contains(value) {
return fmt.Errorf("invalid enum value: %v", value)
}
return nil
}
// ValidateAll checks if all given values are valid enum items in the registry.
func (r *Registry[T]) ValidateAll(values ...T) error {
for _, value := range values {
if err := r.Validate(value); err != nil {
return err
}
}
return nil
}
// Size returns the number of enum items in the registry.
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.
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.
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.
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
}

222
enum/enum_example_test.go Normal file
View File

@@ -0,0 +1,222 @@
package enum
import "fmt"
func ExampleNewItem() {
items := NewItems(
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]()
item1 := NewItem(Active, "Active")
registry.Add(item1)
fmt.Println("Contains Active:", registry.Contains(Active))
fmt.Println("Contains Inactive:", registry.Contains(Inactive))
}
func ExampleRegistry_Validate() {
registry := NewRegistry[Status]()
item1 := NewItem(Active, "Active")
item2 := NewItem(Inactive, "Inactive")
registry.Add(item1, item2)
fmt.Println("Validate Active:", registry.Validate(Active))
fmt.Println("Validate Inactive:", registry.Validate(Inactive))
fmt.Println("Validate Unknown:", registry.Validate(Unknown))
// Output:
// Validate Active: <nil>
// Validate Inactive: <nil>
// Validate Unknown: invalid enum value: 0
}
func ExampleRegistry_ValidateAll() {
registry := NewRegistry[Status]()
item1 := NewItem(Active, "Active")
item2 := NewItem(Inactive, "Inactive")
registry.Add(item1, item2)
fmt.Println("ValidateAll Active, Inactive:", registry.ValidateAll(Active, Inactive))
fmt.Println("ValidateAll Active, Unknown:", registry.ValidateAll(Active, Unknown))
// Output:
// ValidateAll Active, Inactive: <nil>
// ValidateAll Active, Unknown: invalid enum value: 0
}
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
}

218
enum/enum_test.go Normal file
View File

@@ -0,0 +1,218 @@
// 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 TestNewItem(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestNewItem")
items := NewItems(
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_Validate(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestRegistry_Validate")
registry := NewRegistry[Status]()
item1 := NewItem(Active, "Active")
item2 := NewItem(Inactive, "Inactive")
registry.Add(item1, item2)
err := registry.Validate(Active)
assert.IsNil(err)
err = registry.Validate(Inactive)
assert.IsNil(err)
err = registry.Validate(Unknown)
assert.IsNotNil(err)
}
func TestRegistry_ValidateAll(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestRegistry_ValidateAll")
registry := NewRegistry[Status]()
item1 := NewItem(Active, "Active")
item2 := NewItem(Inactive, "Inactive")
registry.Add(item1, item2)
err := registry.ValidateAll(Active, Inactive)
assert.IsNil(err)
err = registry.ValidateAll(Active, Unknown)
assert.IsNotNil(err)
}
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())
}

View File

@@ -21,7 +21,7 @@ type EventBus[T any] struct {
// listeners map[string][]*EventListener[T]
listeners sync.Map
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.
@@ -117,7 +117,7 @@ func (eb *EventBus[T]) Publish(event Event[T]) {
func (eb *EventBus[T]) publishToListener(listener *EventListener[T], event Event[T]) {
defer func() {
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.
// 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
}

View File

@@ -189,8 +189,8 @@ func ExampleEventBus_GetListenersCount() {
func ExampleEventBus_SetErrorHandler() {
eb := NewEventBus[int]()
eb.SetErrorHandler(func(err error) {
fmt.Println(err)
eb.SetErrorHandler(func(topic string, err error) {
fmt.Println(topic, err)
})
eb.Subscribe("event1", func(eventData int) {
@@ -200,7 +200,7 @@ func ExampleEventBus_SetErrorHandler() {
eb.Publish(Event[int]{Topic: "event1", Payload: 1})
// Output:
// error
// event1 error
}
func ExampleEventBus_GetAllListenersCount() {

View File

@@ -114,7 +114,8 @@ func TestEventBus_ErrorHandler(t *testing.T) {
eb := NewEventBus[string]()
eb.SetErrorHandler(func(err error) {
eb.SetErrorHandler(func(topic string, err error) {
assert.Equal("event1", topic)
assert.Equal("error", err.Error())
})

View File

@@ -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.
// 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
func Nand[T any](predicates ...func(T) bool) func(T) bool {
if len(predicates) < 2 {
@@ -26,11 +26,11 @@ func Nand[T any](predicates ...func(T) bool) func(T) bool {
}
return func(value T) bool {
for _, predicate := range predicates {
if predicate(value) {
return false // Short-circuit on the first true predicate
if !predicate(value) {
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
}
}

View File

@@ -65,7 +65,7 @@ func ExampleNand() {
// Output:
// false
// false
// true
// true
}

View File

@@ -65,7 +65,7 @@ func TestPredicatesNandPure(t *testing.T) {
)
assert.ShouldBeFalse(isNumericAndLength5("12345"))
assert.ShouldBeFalse(isNumericAndLength5("1234"))
assert.ShouldBeTrue(isNumericAndLength5("1234"))
assert.ShouldBeTrue(isNumericAndLength5("abcdef"))
}

View File

@@ -238,6 +238,9 @@ func Sum[T constraints.Integer | constraints.Float](numbers ...T) T {
// Average return average value of numbers.
// Play: https://go.dev/play/p/Vv7LBwER-pz
func Average[T constraints.Integer | constraints.Float](numbers ...T) float64 {
if len(numbers) == 0 {
return 0
}
var sum float64
for _, num := range numbers {
sum += float64(num)

View File

@@ -507,19 +507,17 @@ func flattenRecursive(value reflect.Value, result reflect.Value) reflect.Value {
}
// 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)) {
for i := 0; i < len(slice); i++ {
iteratee(i, slice[i])
for idx, elem := range slice {
iteratee(idx, elem)
}
}
// ForEachWithBreak iterates over elements of slice and invokes function for each element,
// when iteratee return false, will break the for each loop.
// Play: https://go.dev/play/p/qScs39f3D9W
// when function return false, will break the for each loop.
func ForEachWithBreak[T any](slice []T, iteratee func(index int, item T) bool) {
for i := 0; i < len(slice); i++ {
if !iteratee(i, slice[i]) {
for idx, elem := range slice {
if !iteratee(idx, elem) {
break
}
}
@@ -692,11 +690,12 @@ func IntSlice(slice any) []int {
// DeleteAt delete the element of slice at index.
// Play: https://go.dev/play/p/800B1dPBYyd
func DeleteAt[T any](slice []T, index int) []T {
result := append([]T(nil), 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:])
// Set the last element to zero value, clean up the memory.
@@ -736,7 +735,8 @@ func Drop[T any](slice []T, n int) []T {
}
if n <= 0 {
return slice
result := make([]T, 0, size)
return append(result, slice...)
}
result := make([]T, 0, size-n)
@@ -754,7 +754,8 @@ func DropRight[T any](slice []T, n int) []T {
}
if n <= 0 {
return slice
result := make([]T, 0, size)
return append(result, slice...)
}
result := make([]T, 0, size-n)
@@ -800,7 +801,9 @@ func InsertAt[T any](slice []T, index int, value any) []T {
size := len(slice)
if index < 0 || index > size {
return slice
result := make([]T, size)
copy(result, slice)
return result
}
switch v := value.(type) {
@@ -817,21 +820,21 @@ func InsertAt[T any](slice []T, index int, value any) []T {
copy(result[index+len(v):], slice[index:])
return result
default:
return slice
result := make([]T, size)
copy(result, slice)
return result
}
}
// UpdateAt update the slice element at index.
// Play: https://go.dev/play/p/f3mh2KloWVm
func UpdateAt[T any](slice []T, index int, value T) []T {
if index < 0 || index >= len(slice) {
return slice
}
result := make([]T, len(slice))
copy(result, slice)
result[index] = value
if index >= 0 && index < len(slice) {
result[index] = value
}
return result
}
@@ -1021,7 +1024,9 @@ func SymmetricDifference[T comparable](slices ...[]T) []T {
return []T{}
}
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)
@@ -1042,6 +1047,7 @@ func SymmetricDifference[T comparable](slices ...[]T) []T {
}
// 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
func Reverse[T any](slice []T) {
for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
@@ -1049,7 +1055,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-
func ReverseCopy[T any](slice []T) []T {
result := make([]T, len(slice))
@@ -1067,7 +1074,7 @@ func Shuffle[T any](slice []T) []T {
rand.Seed(time.Now().UnixNano())
rand.Shuffle(len(slice), func(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
swap(slice, i, j)
})
return slice
@@ -1240,11 +1247,12 @@ func SortByField[T any](slice []T, field string, sortType ...string) error {
// Without creates a slice excluding all given items.
// Play: https://go.dev/play/p/bwhEXEypThg
func Without[T comparable](slice []T, items ...T) []T {
result := make([]T, 0, len(slice))
if len(items) == 0 || len(slice) == 0 {
return slice
return append(result, slice...)
}
result := make([]T, 0, len(slice))
for _, v := range slice {
if !Contain(items, v) {
result = append(result, v)
@@ -1465,36 +1473,28 @@ func Random[T any](slice []T) (val T, idx int) {
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
func RightPadding[T any](slice []T, paddingValue T, paddingLength int) []T {
if paddingLength == 0 {
return slice
suffix := []T{}
if paddingLength > 0 {
suffix = repeat([]T{paddingValue}, paddingLength)
}
for i := 0; i < paddingLength; i++ {
slice = append(slice, paddingValue)
}
return slice
padded := concat(slice, suffix)
return padded
}
// 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
func LeftPadding[T any](slice []T, paddingValue T, paddingLength int) []T {
if paddingLength == 0 {
return slice
prefix := []T{}
if paddingLength > 0 {
prefix = repeat([]T{paddingValue}, paddingLength)
}
paddedSlice := make([]T, len(slice)+paddingLength)
i := 0
for ; i < paddingLength; i++ {
paddedSlice[i] = paddingValue
}
for j := 0; j < len(slice); j++ {
paddedSlice[i] = slice[j]
i++
}
return paddedSlice
padded := concat(prefix, slice)
return padded
}
// Frequency counts the frequency of each element in the slice.

View File

@@ -831,7 +831,7 @@ func ExampleUniqueByComparator() {
})
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)

View File

@@ -2,6 +2,7 @@ package slice
import (
"fmt"
"math/bits"
"reflect"
"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) {
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
}

View File

@@ -1008,7 +1008,7 @@ func TestUniqueByComparator(t *testing.T) {
t.Run("case-insensitive string comparison", func(t *testing.T) {
stringSlice := []string{"apple", "banana", "Apple", "cherry", "Banana", "date"}
caseInsensitiveComparator := func(item, other string) bool {
return strings.ToLower(item) == strings.ToLower(other)
return strings.EqualFold(item, other)
}
result := UniqueByComparator(stringSlice, caseInsensitiveComparator)
@@ -1756,6 +1756,20 @@ func TestRightPaddingAndLeftPadding(t *testing.T) {
padded := LeftPadding(RightPadding(nums, 0, 3), 0, 3)
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) {

View File

@@ -122,3 +122,8 @@ func (s *Struct) IsStruct() bool {
func ToMap(v any) (map[string]any, error) {
return New(v).ToMap()
}
// TypeName return struct type name
func (s *Struct) TypeName() string {
return s.rtype.Name()
}

View File

@@ -177,3 +177,21 @@ func TestStruct_IsStruct(t *testing.T) {
assert.Equal(true, s1.IsStruct())
assert.Equal(false, s2.IsStruct())
}
func TestStruct_TypeName(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestStruct_TypeName")
type Test1 struct{}
t1 := &Test1{}
s1 := New(t1)
assert.Equal("Test1", s1.TypeName())
type Test2 struct{}
t2 := Test2{}
s2 := New(t2)
assert.Equal("Test2", s2.TypeName())
}

View File

@@ -19,30 +19,48 @@ import (
)
var (
alphaMatcher *regexp.Regexp = regexp.MustCompile(`^[a-zA-Z]+$`)
letterRegexMatcher *regexp.Regexp = regexp.MustCompile(`[a-zA-Z]`)
alphaNumericMatcher *regexp.Regexp = regexp.MustCompile(`^[a-zA-Z0-9-]+$`)
numberRegexMatcher *regexp.Regexp = regexp.MustCompile(`\d`)
intStrMatcher *regexp.Regexp = regexp.MustCompile(`^[\+-]?\d+$`)
urlMatcher *regexp.Regexp = regexp.MustCompile(`^((ftp|http|https?):\/\/)?(\S+(:\S*)?@)?((([1-9]\d?|1\d\d|2[01]\d|22[0-3])(\.(1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.([0-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(([a-zA-Z0-9]+([-\.][a-zA-Z0-9]+)*)|((www\.)?))?(([a-z\x{00a1}-\x{ffff}0-9]+-?-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.([a-z\x{00a1}-\x{ffff}]{2,}))?))(:(\d{1,5}))?((\/|\?|#)[^\s]*)?$`)
dnsMatcher *regexp.Regexp = regexp.MustCompile(`^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$`)
emailMatcher *regexp.Regexp = regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`)
chineseMobileMatcher *regexp.Regexp = regexp.MustCompile(`^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$`)
chineseIdMatcher *regexp.Regexp = regexp.MustCompile(`^(\d{17})([0-9]|X|x)$`)
chineseMatcher *regexp.Regexp = regexp.MustCompile("[\u4e00-\u9fa5]")
chinesePhoneMatcher *regexp.Regexp = regexp.MustCompile(`\d{3}-\d{8}|\d{4}-\d{7}|\d{4}-\d{8}`)
creditCardMatcher *regexp.Regexp = regexp.MustCompile(`^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11}|6[27][0-9]{14})$`)
base64Matcher *regexp.Regexp = regexp.MustCompile(`^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{4})$`)
base64URLMatcher *regexp.Regexp = regexp.MustCompile(`^([A-Za-z0-9_-]{4})*([A-Za-z0-9_-]{2}(==)?|[A-Za-z0-9_-]{3}=?)?$`)
binMatcher *regexp.Regexp = regexp.MustCompile(`^(0b)?[01]+$`)
hexMatcher *regexp.Regexp = regexp.MustCompile(`^(#|0x|0X)?[0-9a-fA-F]+$`)
visaMatcher *regexp.Regexp = regexp.MustCompile(`^4[0-9]{12}(?:[0-9]{3})?$`)
masterCardMatcher *regexp.Regexp = regexp.MustCompile(`^5[1-5][0-9]{14}$`)
americanExpressMatcher *regexp.Regexp = regexp.MustCompile(`^3[47][0-9]{13}$`)
unionPay *regexp.Regexp = regexp.MustCompile("^62[0-5]\\d{13,16}$")
chinaUnionPay *regexp.Regexp = regexp.MustCompile(`^62[0-9]{14,17}$`)
alphaMatcher *regexp.Regexp = regexp.MustCompile(`^[a-zA-Z]+$`)
letterRegexMatcher *regexp.Regexp = regexp.MustCompile(`[a-zA-Z]`)
alphaNumericMatcher *regexp.Regexp = regexp.MustCompile(`^[a-zA-Z0-9-]+$`)
numberRegexMatcher *regexp.Regexp = regexp.MustCompile(`\d`)
intStrMatcher *regexp.Regexp = regexp.MustCompile(`^[\+-]?\d+$`)
urlMatcher *regexp.Regexp = regexp.MustCompile(`^((ftp|http|https?):\/\/)?(\S+(:\S*)?@)?((([1-9]\d?|1\d\d|2[01]\d|22[0-3])(\.(1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.([0-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(([a-zA-Z0-9]+([-\.][a-zA-Z0-9]+)*)|((www\.)?))?(([a-z\x{00a1}-\x{ffff}0-9]+-?-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.([a-z\x{00a1}-\x{ffff}]{2,}))?))(:(\d{1,5}))?((\/|\?|#)[^\s]*)?$`)
dnsMatcher *regexp.Regexp = regexp.MustCompile(`^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$`)
// emailMatcher *regexp.Regexp = regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`)
emailMatcher *regexp.Regexp = regexp.MustCompile(`\w+(-+.\w+)*@\w+(-.\w+)*.\w+(-.\w+)*`)
chineseMobileMatcher *regexp.Regexp = regexp.MustCompile(`^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$`)
chineseIdMatcher *regexp.Regexp = regexp.MustCompile(`([1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx])|([1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx])`)
chineseMatcher *regexp.Regexp = regexp.MustCompile("[\u4e00-\u9fa5]")
chinesePhoneMatcher *regexp.Regexp = regexp.MustCompile(`\d{3}-\d{8}|\d{4}-\d{7}|\d{4}-\d{8}`)
creditCardMatcher *regexp.Regexp = regexp.MustCompile(`^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11}|6[27][0-9]{14})$`)
base64Matcher *regexp.Regexp = regexp.MustCompile(`^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{4})$`)
base64URLMatcher *regexp.Regexp = regexp.MustCompile(`^([A-Za-z0-9_-]{4})*([A-Za-z0-9_-]{2}(==)?|[A-Za-z0-9_-]{3}=?)?$`)
binMatcher *regexp.Regexp = regexp.MustCompile(`^(0b)?[01]+$`)
hexMatcher *regexp.Regexp = regexp.MustCompile(`^(#|0x|0X)?[0-9a-fA-F]+$`)
visaMatcher *regexp.Regexp = regexp.MustCompile(`^4[0-9]{12}(?:[0-9]{3})?$`)
masterCardMatcher *regexp.Regexp = regexp.MustCompile(`^5[1-5][0-9]{14}$`)
americanExpressMatcher *regexp.Regexp = regexp.MustCompile(`^3[47][0-9]{13}$`)
unionPayMatcher *regexp.Regexp = regexp.MustCompile(`^62[0-5]\\d{13,16}$`)
chinaUnionPayMatcher *regexp.Regexp = regexp.MustCompile(`^62[0-9]{14,17}$`)
chineseHMPassportMatcher *regexp.Regexp = regexp.MustCompile(`^[CM]\d{8}$`)
)
var passportMatcher = map[string]*regexp.Regexp{
"CN": regexp.MustCompile(`^P\d{9}$`),
"US": regexp.MustCompile(`^\d{9}$`),
"GB": regexp.MustCompile(`^[A-Z0-9]{9}$`),
"RU": regexp.MustCompile(`^[A-Z]{2}\d{7}$`),
"DE": regexp.MustCompile(`^\d{9}$`),
"FR": regexp.MustCompile(`^[A-Z]{2}\d{7}$`),
"JP": regexp.MustCompile(`^\d{8}$`),
"IT": regexp.MustCompile(`^\d{8}$`),
"AU": regexp.MustCompile(`^[A-Z]{1}\d{8}$`),
"BR": regexp.MustCompile(`^\d{9}$`),
"IN": regexp.MustCompile(`^[A-Z]{1,2}\d{7}$`),
"HK": regexp.MustCompile(`^M\d{8}$`),
"MO": regexp.MustCompile(`^[A-Z]\d{8}$`),
}
var (
// Identity card formula
factor = [17]int{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}
@@ -258,21 +276,45 @@ func IsPort(str string) bool {
// IsUrl check if the string is url.
// Play: https://go.dev/play/p/pbJGa7F98Ka
func IsUrl(str string) bool {
if str == "" || len(str) >= 2083 || len(str) <= 3 || strings.HasPrefix(str, ".") {
return false
}
u, err := url.Parse(str)
if err != nil {
return false
}
if strings.HasPrefix(u.Host, ".") {
return false
}
if u.Host == "" && (u.Path != "" && !strings.Contains(u.Path, ".")) {
if str == "" {
return false
}
return urlMatcher.MatchString(str)
u, err := url.Parse(str)
if err != nil || u.Scheme == "" || u.Host == "" {
return false
}
allowedSchemes := map[string]struct{}{
"http": {},
"https": {},
"ftp": {},
"ws": {},
"wss": {},
"file": {},
"mailto": {},
"data": {},
}
if _, ok := allowedSchemes[u.Scheme]; !ok {
return false
}
if u.Scheme == "file" || u.Scheme == "mailto" || u.Scheme == "data" {
return true
}
host := u.Hostname()
if !strings.Contains(host, ".") || strings.HasSuffix(host, ".") {
return false
}
// domainRegexp := regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9\-\.]*[a-zA-Z0-9]$`)
if !dnsMatcher.MatchString(host) {
return false
}
return true
}
// IsDns check if the string is dns.
@@ -286,8 +328,6 @@ func IsDns(dns string) bool {
func IsEmail(email string) bool {
_, err := mail.ParseAddress(email)
return err == nil
// return emailMatcher.MatchString(email)
}
// IsChineseMobile check if the string is chinese mobile number.
@@ -460,12 +500,13 @@ func IsZeroValue(value any) bool {
func IsGBK(data []byte) bool {
i := 0
for i < len(data) {
if data[i] <= 0xff {
if data[i] < 0x81 {
i++
continue
} else {
if data[i] >= 0x81 &&
data[i] <= 0xfe &&
i+1 < len(data) &&
data[i+1] >= 0x40 &&
data[i+1] <= 0xfe &&
data[i+1] != 0xf7 {
@@ -561,12 +602,71 @@ func IsAmericanExpress(v string) bool {
// IsUnionPay check if a give string is a valid union pay nubmer or not.
// Play: https://go.dev/play/p/CUHPEwEITDf
func IsUnionPay(v string) bool {
return unionPay.MatchString(v)
func IsUnionPay(cardNo string) bool {
if len(cardNo) < 16 || len(cardNo) > 19 {
return false
}
matched, _ := regexp.MatchString(`^\d+$`, cardNo)
if !matched {
return false
}
if len(cardNo) < 3 {
return false
}
prefix := cardNo[:3]
prefixNum, err := strconv.Atoi(prefix)
if err != nil {
return false
}
if prefixNum < 620 || prefixNum > 625 {
return false
}
return true
}
// IsChinaUnionPay check if a give string is a valid china union pay nubmer or not.
// Play: https://go.dev/play/p/yafpdxLiymu
func IsChinaUnionPay(v string) bool {
return chinaUnionPay.MatchString(v)
func IsChinaUnionPay(cardNo string) bool {
return chinaUnionPayMatcher.MatchString(cardNo)
}
// luhnCheck checks if the credit card number is valid using the Luhn algorithm.
func luhnCheck(card string) bool {
var sum int
alt := false
for i := len(card) - 1; i >= 0; i-- {
n := int(card[i] - '0')
if alt {
n *= 2
if n > 9 {
n -= 9
}
}
sum += n
alt = !alt
}
return sum%10 == 0
}
// IsPassport checks if the passport number is valid for a given country.
// country is a two-letter country code (ISO 3166-1 alpha-2).
// Play: todo
func IsPassport(passport, country string) bool {
if matcher, ok := passportMatcher[country]; ok {
return matcher.MatchString(passport)
}
return false
}
// IsChineseHMPassport checks if the string is a valid Chinese Hong Kong and Macau Travel Permit number.
// Chinese Hong Kong and Macau Travel Permit format: C or M + 8 digits (e.g., C12345678, M12345678).
// Play: https://go.dev/play/p/TODO
func IsChineseHMPassport(hmPassport string) bool {
return chineseHMPassportMatcher.MatchString(hmPassport)
}

View File

@@ -214,7 +214,7 @@ func ExampleIsUrl() {
fmt.Println(result3)
// Output:
// true
// false
// true
// false
}
@@ -683,3 +683,42 @@ func ExampleIsAlphaNumeric() {
// true
// false
}
func ExampleIsPassport() {
result1 := IsPassport("P123456789", "CN")
result2 := IsPassport("123456789", "US")
result3 := IsPassport("AB1234567", "RU")
result4 := IsPassport("123456789", "CN")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// true
// true
// true
// false
}
func ExampleIsChineseHMPassport() {
result1 := IsChineseHMPassport("C12345678")
result2 := IsChineseHMPassport("C00000000")
result3 := IsChineseHMPassport("M12345678")
result4 := IsChineseHMPassport("c12345678")
result5 := IsChineseHMPassport("C1234567")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
// Output:
// true
// true
// true
// false
// false
}

View File

@@ -437,10 +437,32 @@ func TestIsUrl(t *testing.T) {
assert := internal.NewAssert(t, "TestIsUrl")
assert.Equal(true, IsUrl("http://abc.com"))
assert.Equal(true, IsUrl("abc.com"))
assert.Equal(true, IsUrl("a.b.com"))
assert.Equal(false, IsUrl("abc"))
tests := []struct {
input string
expected bool
}{
{"http://abc.com", true},
{"https://abc.com", true},
{"ftp://abc.com", true},
{"http://abc.com/path?query=123", true},
{"https://abc.com/path/to/resource", true},
{"ws://abc.com", true},
{"wss://abc.com", true},
{"mailto://abc.com", true},
{"file://path/to/file", true},
{"data://text/plain;base64,SGVsbG8sIFdvcmxkIQ==", true},
{"http://abc.com/path/to/resource?query=123#fragment", true},
{"abc", false},
{"http://", false},
{"http://abc", false},
{"http://abc:8080", false},
{"http://abc:99999999", false},
}
for _, tt := range tests {
assert.Equal(tt.expected, IsUrl(tt.input))
}
}
func TestIsDns(t *testing.T) {
@@ -477,12 +499,24 @@ func TestIsEmail(t *testing.T) {
func TestContainChinese(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestContainChinese")
assert.Equal(true, ContainChinese("你好"))
assert.Equal(true, ContainChinese("你好hello"))
assert.Equal(false, ContainChinese("hello"))
tests := []struct {
input string
expected bool
}{
{"你好", true},
{"hello", false},
{"你好hello", true},
{"hello你好", true},
{"", false},
{"123", false},
{"!@#$%^&*()", false},
}
for _, tt := range tests {
assert.Equal(tt.expected, ContainChinese(tt.input))
}
}
func TestIsChineseMobile(t *testing.T) {
@@ -490,8 +524,20 @@ func TestIsChineseMobile(t *testing.T) {
assert := internal.NewAssert(t, "TestIsChineseMobile")
assert.Equal(true, IsChineseMobile("13263527980"))
assert.Equal(false, IsChineseMobile("434324324"))
tests := []struct {
input string
expected bool
}{
{"13263527980", true},
{"1326352798", false},
{"132635279801", false},
{"1326352798a", false},
{"1326352798@", false},
}
for _, tt := range tests {
assert.Equal(tt.expected, IsChineseMobile(tt.input))
}
}
func TestIsChinesePhone(t *testing.T) {
@@ -887,7 +933,7 @@ func TestIsUnionPay(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestIsUnionPay")
assert.Equal(true, IsUnionPay("6221263430109903"))
assert.Equal(true, IsUnionPay("6228480402564890"))
assert.Equal(false, IsUnionPay("3782822463100007"))
}
@@ -895,8 +941,25 @@ func TestIsChinaUnionPay(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestIsChinaUnionPay")
assert.Equal(true, IsChinaUnionPay("6250941006528599"))
assert.Equal(false, IsChinaUnionPay("3782822463100007"))
tests := []struct {
cardNumber string
expected bool
}{
{"6228480420000000000", true},
{"6214830000000000", true},
{"6230580000000000000", true},
{"6259640000000000000", true},
{"6260000000000000000", true},
{"6288888888888888", true},
// 非银联前缀
{"4123456789012345", false},
{"3528000000000000", false},
}
for _, tt := range tests {
assert.Equal(tt.expected, IsChinaUnionPay(tt.cardNumber))
}
}
func TestIsAlphaNumeric(t *testing.T) {
@@ -924,3 +987,72 @@ func TestIsAlphaNumeric(t *testing.T) {
assert.Equal(tt.expected, IsAlphaNumeric(tt.input))
}
}
func TestIsPassport(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestIsPassport")
tests := []struct {
passport string
countryCode string
expected bool
}{
{"P123456789", "CN", true},
{"123456789", "US", true},
{"A12345678", "GB", true},
{"AB1234567", "FR", true},
{"12345678", "JP", true},
{"M12345678", "HK", true},
{"A12345678", "MO", true},
{"A1234567", "IN", true},
{"12345678", "IT", true},
{"A12345678", "AU", true},
{"123456789", "BR", true},
{"AB1234567", "RU", true},
{"123456789", "CN", false},
}
for _, tt := range tests {
assert.Equal(tt.expected, IsPassport(tt.passport, tt.countryCode))
}
}
func TestIsChineseHMPassport(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestIsChineseHMPassport")
tests := []struct {
input string
expected bool
}{
{"C12345678", true},
{"C00000000", true},
{"C99999999", true},
{"M12345678", true}, // M prefix
{"M00000000", true}, // M prefix
{"M99999999", true}, // M prefix
{"c12345678", false}, // lowercase c
{"m12345678", false}, // lowercase m
{"C1234567", false}, // 7 digits
{"M1234567", false}, // 7 digits with M
{"C123456789", false}, // 9 digits
{"M123456789", false}, // 9 digits with M
{"C1234567a", false}, // contains letter
{"M1234567a", false}, // contains letter with M
{"D12345678", false}, // starts with D
{"12345678", false}, // no prefix
{"CC12345678", false}, // double C
{"MM12345678", false}, // double M
{"C 12345678", false}, // contains space
{"M 12345678", false}, // contains space with M
{"C12345-678", false}, // contains dash
{"M12345-678", false}, // contains dash with M
{"", false},
}
for _, tt := range tests {
assert.Equal(tt.expected, IsChineseHMPassport(tt.input))
}
}