putils

package
v1.1.59 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 26, 2025 License: MIT Imports: 22 Imported by: 5

README

putils

一个功能丰富的 Go 工具库,提供常用的数据处理、验证、网络、时间处理等实用功能。

安装

go get github.com/go-puzzles/puzzles/putils

功能模块

📝 字符串处理 (string.go)

提供高效的字符串搜索算法和处理功能:

  • 多种字符串搜索算法:KMP、Boyer-Moore、暴力搜索
  • 智能算法选择:根据文本长度自动选择最适合的搜索算法
// 字符串搜索
index := putils.StringSearch("hello world", "world")

// 使用指定算法
index := putils.StringSearch("text", "pattern", putils.WithKMP())
index := putils.StringSearch("text", "pattern", putils.WithBM())
🎲 随机数生成 (random.go)

强大的随机数生成工具:

// 随机布尔值
randBool := putils.RandBool()

// 随机整数 [min, max)
randInt := putils.RandInt(1, 100)

// 随机字符串
randStr := putils.RandString(10)                    // 字母
randNum := putils.RandNumeral(6)                   // 数字
randMixed := putils.RandNumeralOrLetter(8)         // 数字+字母

// 随机浮点数
randFloat := putils.RandFloat(1.0, 10.0, 2)       // 精度为2

// 随机字节
randBytes := putils.RandBytes(16)

// 从切片中随机选择
item := putils.RandFromGivenSlice([]string{"a", "b", "c"})

// 生成唯一随机整数切片
uniqueInts := putils.RandUniqueIntSlice(5, 1, 100)
✅ 数据验证 (validator.go)

全面的数据验证工具:

// 字符串验证
putils.IsAlpha("abc")                  // 纯字母
putils.IsASCII("hello")                // ASCII字符
putils.IsNumberStr("123")              // 数字字符串
putils.IsFloatStr("123.45")            // 浮点数字符串
putils.IsIntStr("-123")                // 整数字符串

// 网络验证
putils.IsIp("192.168.1.1")            // IP地址
putils.IsIpV4("192.168.1.1")          // IPv4
putils.IsIpV6("::1")                  // IPv6
putils.IsUrl("https://example.com")    // URL
putils.IsEmail("[email protected]")     // 邮箱
putils.IsDns("example.com")           // DNS

// 内容验证
putils.IsJSON(`{"key": "value"}`)      // JSON格式
putils.IsBase64("SGVsbG8=")           // Base64编码
putils.ContainChinese("你好世界")       // 包含中文
putils.ContainLetter("abc123")         // 包含字母
putils.ContainNumber("abc123")         // 包含数字

// 密码强度
putils.IsStrongPassword("Abc123!@#", 8)  // 强密码验证
📅 日期时间处理 (datetime.go)

便捷的时间处理工具:

now := time.Now()

// 时间边界
beginDay := putils.BeginOfDay(now)     // 当日开始
endDay := putils.EndOfDay(now)         // 当日结束
beginWeek := putils.BeginOfWeek(now)   // 本周开始
endWeek := putils.EndOfWeek(now)       // 本周结束
beginMonth := putils.BeginOfMonth(now) // 本月开始
endMonth := putils.EndOfMonth(now)     // 本月结束

// 快速获取今日、本周、本月时间范围
start, end := putils.StartEndDay()     // 今日
start, end = putils.StartEndWeek()     // 本周
start, end = putils.StartEndMonth()    // 本月

// 时间判断
isLeap := putils.IsLeapYear(2024)      // 闰年判断
isWeekend := putils.IsWeekend(now)     // 是否周末
dayOfYear := putils.DayOfYear(now)     // 一年中的第几天

// 时间计算
seconds := putils.BetweenSeconds(time1, time2)  // 时间差(秒)
🌐 网络工具 (network.go)

网络信息获取:

// 获取网卡信息
ip, err := putils.GetLocalIP("eth0")        // 本地IP
mac, err := putils.GetMacAddr("eth0")       // MAC地址
mask, err := putils.GetSubnetMask("eth0")   // 子网掩码
🔧 函数式编程 (function.go)

提供常用的函数式编程工具:

numbers := []int{1, 2, 3, 4, 5}

// Map 操作
doubled := putils.Map(numbers, func(x int) int { return x * 2 })

// Filter 过滤
evens := putils.Filter(numbers, func(x int) bool { return x%2 == 0 })

// Reduce 聚合
sum := putils.Reduce(numbers, 0, func(acc, x int) int { return acc + x })

// 查找
value, found := putils.Find(numbers, func(x int) bool { return x > 3 })

// 分组
grouped := putils.GroupBy(numbers, func(x int) string {
    if x%2 == 0 { return "even" } else { return "odd" }
})

// 检查
hasEven := putils.Any(numbers, func(x int) bool { return x%2 == 0 })
allPositive := putils.All(numbers, func(x int) bool { return x > 0 })

// 包含检查
contains := putils.Contains(numbers, 3)

// 分区
evens, odds := putils.Partition(numbers, func(x int) bool { return x%2 == 0 })
🗂️ 数据去重 (dedup.go)

智能去重功能,根据数据量选择最优算法:

data := []int{1, 2, 2, 3, 3, 4}
unique := putils.Dedup(data)  // [1, 2, 3, 4]

// 自动选择算法:
// - 小于等于50个元素:使用O(n²)简单算法
// - 大于50个元素:使用O(n)哈希表算法
📦 字节处理 (bytes.go)

字节和类型转换工具:

// MD5 计算
hash := putils.Md5("hello world")      // 完整MD5
shortHash := putils.ShortMd5("hello")  // 短MD5(16字符)

// 类型安全的字节追加
buf := make([]byte, 0)
buf = putils.AppendAny(buf, 123)       // 追加整数
buf = putils.AppendAny(buf, "hello")   // 追加字符串
buf = putils.AppendAny(buf, time.Now()) // 追加时间
📚 栈数据结构 (stack.go)

泛型栈实现:

stack := &putils.Stack[int]{}

stack.Push(1)
stack.Push(2)
stack.Push(3)

value, ok := stack.Pop()  // 3, true
🛠️ 工具函数 (utils.go)

基础工具函数:

// 文件操作
exists := putils.FileExists("/path/to/file")
size, err := putils.FileSize("/path/to/file")

// 随机字符串 (已废弃,建议使用 RandString)
str := putils.GenerateRandomString(10)
🔄 类型转换 (convert.go)

提供类型转换相关的工具函数。

⏰ 时间工具 (time.go)

额外的时间处理工具。

🔄 迭代器函数 (iter_function.go)

提供迭代器相关的函数式编程工具。

测试

go test ./...

部分模块包含测试文件:

  • random_test.go - 随机数生成测试
  • string_test.go - 字符串处理测试

特性

  • 零依赖:除了 golang.org/x/exp 外无外部依赖
  • 🚀 高性能:针对不同场景选择最优算法
  • 🔒 类型安全:广泛使用 Go 泛型
  • 📖 简单易用:API 设计简洁直观
  • 🧪 测试覆盖:核心功能都有测试用例

许可证

(c) 2024 Example Corp. All rights reserved.

Documentation

Index

Constants

View Source
const (
	MaximumCapacity = math.MaxInt>>1 + 1
	Numeral         = "0123456789"
	LowwerLetters   = "abcdefghijklmnopqrstuvwxyz"
	UpperLetters    = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	Letters         = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	SymbolChars     = "!@#$%^&*()_+-=[]{}|;':\",./<>?"
	AllChars        = Numeral + LowwerLetters + UpperLetters + SymbolChars
)

Variables

This section is empty.

Functions

func All

func All[T any](arr []T, predicate func(T) bool) bool

All checks if all elements in the slice satisfy the predicate function

func Any

func Any[T any](arr []T, predicate func(T) bool) bool

Any checks if any element in the slice satisfies the predicate function

func AppendAny added in v1.1.48

func AppendAny(dst []byte, v any) []byte

func BeginOfDay added in v1.0.6

func BeginOfDay(t time.Time) time.Time

BeginOfDay return beginning hour time of day.

func BeginOfHour added in v1.0.6

func BeginOfHour(t time.Time) time.Time

BeginOfHour return beginning hour time of day.

func BeginOfMinute added in v1.0.6

func BeginOfMinute(t time.Time) time.Time

BeginOfMinute return beginning minute time of day.

func BeginOfMonth added in v1.0.6

func BeginOfMonth(t time.Time) time.Time

BeginOfMonth return beginning of month.

func BeginOfWeek added in v1.0.6

func BeginOfWeek(t time.Time, beginFrom ...time.Weekday) time.Time

BeginOfWeek return beginning week, default week begin from Sunday.

func BeginOfYear added in v1.0.6

func BeginOfYear(t time.Time) time.Time

BeginOfYear return the date time at the begin of year.

func BetweenSeconds added in v1.0.6

func BetweenSeconds(t1 time.Time, t2 time.Time) int64

BetweenSeconds returns the number of seconds between two times.

func ContainChinese added in v1.0.9

func ContainChinese(s string) bool

ContainChinese check if the string contain mandarin chinese.

func ContainLetter added in v1.0.9

func ContainLetter(str string) bool

ContainLetter check if the string contain at least one letter.

func ContainNumber added in v1.0.9

func ContainNumber(input string) bool

ContainNumber check if the string contain at least one number.

func Contains added in v1.0.9

func Contains[T comparable](arr []T, tar T) bool

func Convert added in v1.1.13

func Convert[S, T any](s []S, fn func(S) T) []T

func DayOfYear added in v1.0.6

func DayOfYear(t time.Time) int

DayOfYear returns which day of the year the parameter date `t` is.

func Dedup added in v1.1.17

func Dedup[T comparable](slice []T) []T

func EndOfDay added in v1.0.6

func EndOfDay(t time.Time) time.Time

EndOfDay return end time of day.

func EndOfHour added in v1.0.6

func EndOfHour(t time.Time) time.Time

EndOfHour return end hour time of day.

func EndOfMinute added in v1.0.6

func EndOfMinute(t time.Time) time.Time

EndOfMinute return end minute time of day.

func EndOfMonth added in v1.0.6

func EndOfMonth(t time.Time) time.Time

EndOfMonth return end of month.

func EndOfWeek added in v1.0.6

func EndOfWeek(t time.Time, endWith ...time.Weekday) time.Time

EndOfWeek return end week time, default week end with Saturday.

func EndOfYear added in v1.0.6

func EndOfYear(t time.Time) time.Time

EndOfYear return the date time at the end of year.

func FileExists

func FileExists(filePath string) bool

func FileSize added in v1.0.17

func FileSize(filePath string) (int64, error)

func Filter

func Filter[T any](arr []T, predicate func(T) bool) []T

Filter returns a new slice containing elements that satisfy a predicate function

func FilterIter

func FilterIter[inputs ~[]E, E any](arr inputs, fn func(E) bool) iter.Seq[E]

func Find

func Find[T any](arr []T, predicate func(T) bool) (T, bool)

Find returns the first element in the slice that satisfies the predicate function

func FirstDayOfMonth

func FirstDayOfMonth(date time.Time) time.Time

FirstDayOfMonth Get the first day of the month in which the given time is located

func FirstDayOfWeek

func FirstDayOfWeek(date time.Time) time.Time

FirstDayOfWeek

func FormatDuration

func FormatDuration(duration time.Duration) string

func GenerateRandomString

func GenerateRandomString(n int) string

GenerateRandomString Deprecated: Use RandString() instead.

func GetLocalIP

func GetLocalIP(ifaceName string) (string, error)

func GetMacAddr

func GetMacAddr(ifaceName string) (string, error)

func GetSubnetMask

func GetSubnetMask(ifaceName string) (string, error)

func GroupBy

func GroupBy[T any, K comparable](arr []T, keyFunc func(T) K) map[K][]T

GroupBy groups elements in the slice by a specified key function

func IsASCII added in v1.0.9

func IsASCII(str string) bool

IsASCII checks if string is all ASCII char.

func IsAlpha added in v1.0.9

func IsAlpha(str string) bool

IsAlpha checks if the string contains only letters (a-zA-Z).

func IsBase64 added in v1.0.9

func IsBase64(base64 string) bool

IsBase64 check if the string is base64 string.

func IsBase64URL added in v1.0.9

func IsBase64URL(v string) bool

IsBase64URL check if a give string is a valid URL-safe Base64 encoded string.

func IsBin added in v1.0.9

func IsBin(v string) bool

IsBin check if a give string is a valid binary value or not.

func IsDns added in v1.0.9

func IsDns(dns string) bool

IsDns check if the string is dns.

func IsEmail added in v1.0.9

func IsEmail(email string) bool

IsEmail check if the string is a email address.

func IsEmptyString added in v1.0.9

func IsEmptyString(str string) bool

IsEmptyString check if the string is empty.

func IsFloat added in v1.0.9

func IsFloat(v any) bool

IsFloat check if the value is float(float32, float34) or not.

func IsFloatStr added in v1.0.9

func IsFloatStr(str string) bool

IsFloatStr check if the string can convert to a float.

func IsGBK added in v1.0.9

func IsGBK(data []byte) bool

IsGBK check if data encoding is gbk Note: this function is implemented by whether double bytes fall within the encoding range of gbk, while each byte of utf-8 encoding format falls within the encoding range of gbk. Therefore, utf8.valid() should be called first to check whether it is not utf-8 encoding, and then call IsGBK() to check gbk encoding. like below *

data := []byte("你好")
if utf8.Valid(data) {
	fmt.Println("data encoding is utf-8")
}else if(IsGBK(data)) {
	fmt.Println("data encoding is GBK")
}
fmt.Println("data encoding is unknown")

*

func IsHex added in v1.0.9

func IsHex(v string) bool

IsHex check if a give string is a valid hexadecimal value or not.

func IsInt added in v1.0.9

func IsInt(v any) bool

IsInt check if the value is integer(int, unit) or not.

func IsIntStr added in v1.0.9

func IsIntStr(str string) bool

IsIntStr check if the string can convert to a integer.

func IsIp added in v1.0.9

func IsIp(ipstr string) bool

IsIp check if the string is a ip address.

func IsIpV4 added in v1.0.9

func IsIpV4(ipstr string) bool

IsIpV4 check if the string is a ipv4 address.

func IsIpV6 added in v1.0.9

func IsIpV6(ipstr string) bool

IsIpV6 check if the string is a ipv6 address.

func IsJSON added in v1.0.9

func IsJSON(str string) bool

IsJSON checks if the string is valid JSON.

func IsJWT added in v1.0.9

func IsJWT(v string) bool

IsJWT check if a give string is a valid JSON Web Token (JWT).

func IsLeapYear added in v1.0.6

func IsLeapYear(year int) bool

IsLeapYear check if param year is leap year or not.

func IsNumber added in v1.0.9

func IsNumber(v any) bool

IsNumber check if the value is number(integer, float) or not.

func IsNumberStr added in v1.0.9

func IsNumberStr(s string) bool

IsNumberStr check if the string can convert to a number.

func IsPort added in v1.0.9

func IsPort(str string) bool

IsPort check if the string is a valid net port.

func IsPrintable added in v1.0.9

func IsPrintable(str string) bool

IsPrintable checks if string is all printable chars.

func IsRegexMatch added in v1.0.9

func IsRegexMatch(str, regex string) bool

IsRegexMatch check if the string match the regexp.

func IsStrongPassword added in v1.0.9

func IsStrongPassword(password string, length int) bool

IsStrongPassword check if the string is strong password, if len(password) is less than the length param, return false Strong password: alpha(lower+upper) + number + special chars(!@#$%^&*()?><).

func IsUrl added in v1.0.9

func IsUrl(str string) bool

IsUrl check if the string is url.

func IsWeakPassword added in v1.0.9

func IsWeakPassword(password string) bool

IsWeakPassword check if the string is weak password Weak password: only letter or only number or letter + number.

func IsWeekend added in v1.0.6

func IsWeekend(t time.Time) bool

IsWeekend checks if passed time is weekend or not.

func IsZeroValue added in v1.0.9

func IsZeroValue(value any) bool

IsZeroValue checks if value is a zero value.

func LastDayOfMonth

func LastDayOfMonth(date time.Time) time.Time

LastDayOfMonth Get the last day of the month in which the given time is located

func LastDayOfWeek

func LastDayOfWeek(date time.Time) time.Time

func Map

func Map[T any, U any](arr []T, fn func(T) U) []U

Map applies a function to each element in a slice and returns a new slice

func MapIter

func MapIter[inputs ~[]E, E any, U any](arr inputs, fn func(E) U) iter.Seq[U]

func Md5 added in v1.1.48

func Md5(src any) []byte

func Partition

func Partition[T any](arr []T, predicate func(T) bool) ([]T, []T)

Partition divides a slice into two slices based on a predicate function

func RandBool added in v1.0.7

func RandBool() bool

RandBool generates a random boolean value (true or false).

func RandBoolSlice added in v1.0.7

func RandBoolSlice(length int) []bool

RandBoolSlice generates a random boolean slice of specified length.

func RandBytes added in v1.0.7

func RandBytes(length int) []byte

RandBytes generate random byte slice.

func RandFloat added in v1.0.7

func RandFloat(min, max float64, precision int) float64

RandFloat generate random float64 number between [min, max) with specific precision.

func RandFloats added in v1.0.7

func RandFloats(length int, min, max float64, precision int) []float64

RandFloats generate a slice of random float64 numbers of length that do not repeat.

func RandFromGivenSlice added in v1.0.7

func RandFromGivenSlice[T any](slice []T) T

RandFromGivenSlice generate a random element from given slice.

func RandInt added in v1.0.7

func RandInt(min, max int) int

RandInt generate random int between [min, max).

func RandIntSlice added in v1.0.7

func RandIntSlice(length, min, max int) []int

RandIntSlice generates a slice of random integers. The generated integers are between min and max (exclusive).

func RandLower added in v1.0.7

func RandLower(length int) string

RandLower generate a random lower case string of specified length.

func RandNumeral added in v1.0.7

func RandNumeral(length int) string

RandNumeral generate a random numeral string of specified length.

func RandNumeralOrLetter added in v1.0.7

func RandNumeralOrLetter(length int) string

RandNumeralOrLetter generate a random numeral or alpha string of specified length.

func RandSliceFromGivenSlice added in v1.0.7

func RandSliceFromGivenSlice[T any](slice []T, num int, repeatable bool) []T

RandSliceFromGivenSlice generate a random slice of length num from given slice.

  • If repeatable is true, the generated slice may contain duplicate elements.

func RandString added in v1.0.7

func RandString(length int) string

RandString generate random alphabeta string of specified length.

func RandStringSlice added in v1.0.7

func RandStringSlice(charset string, sliceLen, strLen int) []string

RandString generate a slice of random string of length strLen based on charset. chartset should be one of the following: random.Numeral, random.LowwerLetters, random.UpperLetters random.Letters, random.SymbolChars, random.AllChars. or a combination of them.

func RandStringWithLetter added in v1.1.22

func RandStringWithLetter(letters string, length int) string

func RandSymbolChar added in v1.0.7

func RandSymbolChar(length int) string

RandSymbolChar generate a random symbol char of specified length. symbol chars: !@#$%^&*()_+-=[]{}|;':\",./<>?.

func RandUniqueIntSlice added in v1.0.7

func RandUniqueIntSlice(length, min, max int) []int

RandUniqueIntSlice generate a slice of random int of length that do not repeat.

func RandUpper added in v1.0.7

func RandUpper(length int) string

RandUpper generate a random upper case string of specified length.

func Reduce

func Reduce[T any, U any](arr []T, initial U, fn func(acc U, v T) U) U

Reduce reduces a slice to a single value using a provided function and initial value

func RoundToFloat added in v1.0.7

func RoundToFloat[T constraints.Float | constraints.Integer](x T, n int) float64

func ShortMd5 added in v1.1.48

func ShortMd5(src any) []byte

func StartEndDay added in v1.0.23

func StartEndDay() (start, end time.Time)

func StartEndMonth added in v1.0.23

func StartEndMonth() (start, end time.Time)

func StartEndWeek added in v1.0.23

func StartEndWeek() (start, end time.Time)

func StartOfDay

func StartOfDay(date time.Time) time.Time

func StringSearch added in v1.0.22

func StringSearch(text, pattern string, opts ...stringSearchOptFunc) int

func WithBM added in v1.0.24

func WithBM() stringSearchOptFunc

func WithBruteForce added in v1.0.24

func WithBruteForce() stringSearchOptFunc

func WithEngine added in v1.0.22

func WithEngine(engine SearchEngine) stringSearchOptFunc

func WithKMP added in v1.0.22

func WithKMP() stringSearchOptFunc

func WithKMPV2 added in v1.0.24

func WithKMPV2() stringSearchOptFunc

func Zip

func Zip[T1 any, T2 any](arr1 []T1, arr2 []T2) [][2]any

Zip combines two slices into a slice of pairs (tuples)

func ZipIter added in v1.0.6

func ZipIter[T1 any, T2 any, E [2]any](arr1 []T1, arrs []T2) iter.Seq[E]

Types

type BMSearchEngine added in v1.0.24

type BMSearchEngine struct{}

func (*BMSearchEngine) Search added in v1.0.24

func (bm *BMSearchEngine) Search(text, pattern string) int

type BruteForceSearchEngine added in v1.0.24

type BruteForceSearchEngine struct{}

func (*BruteForceSearchEngine) Search added in v1.0.24

func (bf *BruteForceSearchEngine) Search(text, pattern string) int

type KMPSearchEngine added in v1.0.22

type KMPSearchEngine struct{}

func (*KMPSearchEngine) Search added in v1.0.22

func (k *KMPSearchEngine) Search(text, pattern string) int

type KMPSearchEngineV2 added in v1.0.24

type KMPSearchEngineV2 struct{}

func (*KMPSearchEngineV2) Search added in v1.0.24

func (k *KMPSearchEngineV2) Search(text, pattern string) int

type SearchEngine added in v1.0.22

type SearchEngine interface {
	Search(text, pattern string) int
}

type Stack

type Stack[T any] struct {
	// contains filtered or unexported fields
}

Stack represents a stack data structure

func (*Stack[T]) Pop

func (s *Stack[T]) Pop() (T, bool)

Pop removes and returns the top element of the stack

func (*Stack[T]) Push

func (s *Stack[T]) Push(element T)

Push adds an element to the stack

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL