safe

package
v0.19.4 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Overview

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-16 22:55:55 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-16 22:55:55 * @FilePath: \go-toolbox\pkg\safe\mathx.go * @Description: 安全的数学工具函数集合,提供各种数学算法的安全实现 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-02-28 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-05-13 22:56:07 * @FilePath: \go-toolbox\pkg\safe\struct_tags.go * @Description: 结构体 tag 解析与字段别名归一化 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

Index

Constants

View Source
const (
	// 使用int64避免32位架构溢出
	MaxSafeInteger64 = int64(1<<53 - 1)    // JavaScript安全整数最大值
	MinSafeInteger64 = int64(-(1<<53 - 1)) // JavaScript安全整数最小值
	GoldenRatio      = 1.618033988749      // 黄金比例
	EulerNumber      = 2.718281828459      // 欧拉数
)

定义常用的数学常数

Variables

View Source
var (
	MaxSafeInteger = getMaxSafeIntegerForArch()
	MinSafeInteger = getMinSafeIntegerForArch()
)

架构相关的安全整数最大值

Functions

func Abs

func Abs(n int64) (int64, error)

Abs 安全绝对值计算,防止溢出

func Add

func Add(a, b int64) (int64, error)

Add 安全整数加法,防止溢出

func AddStringFieldAlias

func AddStringFieldAlias(aliases map[string]struct{}, name string)

AddStringFieldAlias 向别名集合中添加字符串字段别名 忽略空字符串和 "-"(表示字段被忽略)

func As

func As[T types.Numerical](s *Access, defaultValue ...T) T

As 泛型转换方法 - 支持所有数值类型

func AsFloat

func AsFloat[T types.Float](s *Access, mode convert.RoundMode, defaultValue ...T) T

AsFloat 泛型浮点数转换方法

func AsFloatSlice

func AsFloatSlice[T types.Float](s *Access, mode convert.RoundMode) ([]T, error)

AsFloatSlice 泛型浮点数切片转换

func AsSlice

func AsSlice[T types.Numerical](s *Access) ([]T, error)

AsSlice 泛型切片转换

func Average

func Average(numbers []int64) (float64, error)

Average 安全平均值计算,防止溢出

func BoolPtr

func BoolPtr(src *bool) bool

BoolPtr 安全转换 *bool 到 bool(默认false)

func BytesPtr

func BytesPtr(src *[]byte) []byte

BytesPtr 安全转换 *[]byte 到 []byte(空切片)

func Clamp

func Clamp(value, min, max int64) (int64, error)

Clamp 安全值范围限制

func Divide

func Divide(a, b int64) (int64, error)

Divide 安全整数除法,防止除零和溢出

func DurationPtr

func DurationPtr(src *time.Duration) time.Duration

DurationPtr 安全转换 *time.Duration 到 time.Duration(默认0)

func ExtractGormColumnName

func ExtractGormColumnName(field reflect.StructField) string

ExtractGormColumnName 从 gorm 结构体标签中提取列名

func ExtractGormType

func ExtractGormType(field reflect.StructField) string

ExtractGormType 从 gorm 结构体标签中提取数据库类型

func ExtractStructuredTagValue

func ExtractStructuredTagValue(tag string, key string) string

ExtractStructuredTagValue 从分号分隔的结构化标签中提取值 例如从 `gorm:"column:detail;type:json"` 中提取 column 或 type 的值

func Factorial

func Factorial(n int) (*big.Int, error)

Factorial 安全阶乘计算,防止溢出

func FastHash

func FastHash(s string) uint64

FastHash 快速哈希函数 - 安全版本 使用FNV-1a算法,避免哈希冲突和安全问题

func Fibonacci

func Fibonacci(n int) (int64, error)

Fibonacci 安全斐波那契数列计算,防止溢出

func FieldNameAliases

func FieldNameAliases(name string) []string

FieldNameAliases 返回字段名的别名列表 包含原始字段名和 snake_case 形式(如果两者不同)

func Float32Ptr

func Float32Ptr(src *float32) float32

Float32Ptr 安全转换 *float32 到 float32(默认0)

func Float64Ptr

func Float64Ptr(src *float64) float64

Float64Ptr 安全转换 *float64 到 float64(默认0)

func GCD

func GCD(a, b int64) int64

GCD 安全最大公约数计算,使用欧几里得算法

func GenericStructType

func GenericStructType[T any]() reflect.Type

GenericStructType 获取泛型结构体的反射类型 自动解引用指针类型,返回最终的结构体类型

func GetBool

func GetBool(m map[string]interface{}, key string) bool

GetBool 安全获取map中的布尔值

func GetString

func GetString(m map[string]interface{}, key string) string

GetString 安全获取map中的字符串值

func GetStringSlice

func GetStringSlice(m map[string]interface{}, key string) []string

GetStringSlice 安全获取map中的字符串切片

func HashToInt64

func HashToInt64(parts []string, separator string) int64

HashToInt64 将多个字符串拼接后哈希为非负 int64 内部使用 FNV-1a 短哈希 + Base36 解码,保证确定性且跨平台一致

参数:

  • parts: 待哈希的字符串切片
  • separator: 拼接分隔符

返回:非负的 int64 哈希值

func Int32Ptr

func Int32Ptr(src *int32) int32

Int32Ptr 安全转换 *int32 到 int32(默认0)

func Int64Ptr

func Int64Ptr(src *int64) int64

Int64Ptr 安全转换 *int64 到 int64(默认0)

func IntPtr

func IntPtr(src *int) int

IntPtr 安全转换 *int 到 int(默认0)

func IsPrime

func IsPrime(n int64) bool

IsPrime 安全素数检测,使用Miller-Rabin算法

func IsType

func IsType[T any](s *Access) bool

IsType 检查值是否为指定类型

func LCM

func LCM(a, b int64) (int64, error)

LCM 安全最小公倍数计算

func Log

func Log(n, base float64) (float64, error)

Log 安全对数计算

func Max

func Max(numbers []int64) (int64, error)

Max 安全获取最大值

func MergeWithDefaults

func MergeWithDefaults[T any](st *T, defaultSts ...*T) *T

MergeWithDefaults 合并配置,用默认配置填充nil或零值字段 支持泛型,会递归合并所有嵌套结构体、指针、切片、Map等

func Min

func Min(numbers []int64) (int64, error)

Min 安全获取最小值

func Modulo

func Modulo(a, b int64) (int64, error)

Modulo 安全取模运算,防止除零

func Multiply

func Multiply(a, b int64) (int64, error)

Multiply 安全整数乘法,防止溢出

func Must

func Must[T any](s *Access) T

Must 强制获取值,无效时panic

func NextPowerOfTwo

func NextPowerOfTwo(n int) int

NextPowerOfTwo 获取下一个2的幂 - 安全版本 防止整数溢出和无效输入

func NormalizeStringFieldMapByTagType

func NormalizeStringFieldMapByTagType[T any](fields map[string]interface{}, tagName string, typeMatches func(string) bool, normalize func(string) string)

NormalizeStringFieldMapByTagType 规范化 map 中的值 仅对键匹配带标签字符串字段别名的条目进行规范化

func NormalizeStringFieldsByTagType

func NormalizeStringFieldsByTagType(target interface{}, tagName string, typeMatches func(string) bool, normalize func(string) string)

NormalizeStringFieldsByTagType 规范化结构体上的字符串字段 仅当配置的标签类型匹配提供的谓词函数时才进行规范化

func OrDefault

func OrDefault[T any](s *Access, defaultValue T) T

OrDefault 提供默认值

func Power

func Power(base, exp int64) (int64, error)

Power 安全幂运算,使用快速幂算法防止溢出

func Ptr

func Ptr[T any, R any](src *T, f func(T) R) *R

Ptr 通用指针安全转换

func ShortHash

func ShortHash(s string) string

ShortHash 生成短哈希字符串(默认7位,类似Git) 使用 FNV-1a 算法,适用于生成短ID、节点ID等场景 返回格式:7位Base36字符串(0-9a-z),如 "a1b2c3d" 冲突概率:10万节点 < 0.007%

func ShortHashWithLength

func ShortHashWithLength(s string, length int) string

ShortHashWithLength 生成指定长度的短哈希字符串 使用 FNV-1a 算法 + Base36 编码(0-9a-z)

参数:

  • s: 输入字符串
  • length: 哈希长度(最小为1),推荐值:
  • 6位: 适合小规模(< 1万节点),冲突概率 < 0.002%
  • 7位: 适合中规模(< 10万节点),冲突概率 < 0.007%(推荐)
  • 8位: 适合大规模(< 100万节点),冲突概率 < 0.0002%
  • 12-16位: 适合超大规模或需要更低冲突概率的场景

返回:指定长度的Base36字符串

示例:

ShortHashWithLength("192.168.1.100:8080", 7) → "3g5e9ss"
ShortHashWithLength("pod-abc-123", 8) → "2k3m4n5p"
ShortHashWithLength("user123", 16) → "3g5e9ss000000000"

func SlicePtr

func SlicePtr[T any](src *[]T) []T

SlicePtr 安全转换 *[]T 到 []T(空切片)

func Sqrt

func Sqrt(n float64) (float64, error)

Sqrt 安全平方根计算,使用牛顿法

func StringFieldAliasesByTagType

func StringFieldAliasesByTagType[T any](tagName string, typeMatches func(string) bool) map[string]struct{}

StringFieldAliasesByTagType 返回字符串字段的别名集合 这些字段的标签类型匹配提供的谓词函数 包含 Go 字段名、snake_case 名、json 名以及结构化标签中的列名

func StringPtr

func StringPtr(src *string) string

StringPtr 安全转换 *string 到 string(空字符串)

func Subtract

func Subtract(a, b int64) (int64, error)

Subtract 安全整数减法,防止溢出

func UintPtr

func UintPtr(src *uint) uint

UintPtr 安全转换 *uint 到 uint(默认0)

Types

type Access

type Access struct {
	// contains filtered or unexported fields
}

Access 安全访问装饰器

包住一个任意值,之后的取字段、转类型、取下标都不会 panic:路径不存在或类型 不符时返回零值或调用方给的默认值,而不是崩掉本包的「安全」指的就是这件事—— 程序不崩,与信息安全无关

命名不带 Safe 前缀

包名已经是 safe,再叫 SafeAccess 从包外看就是 safe.SafeAccess,重复一遍 Go 官方的命名约定正是为此:包名承担限定作用,类型名不该再重复它 同理 safe.Add / safe.Sqrt / safe.GetString 而不是 safe.SafeAdd 等, 入口从 safe.Safe(v) 改为 safe.New(v)——原先那个函数的文档注释本来就写着 New

[EN] A wrapper around an arbitrary value: field access, type conversion and indexing on it never panic, returning a zero value or a caller-supplied default when the path is missing or the type does not match. "Safe" here means exactly that — the program does not crash — and has nothing to do with information security.

The name carries no Safe prefix. The package is already called safe, so SafeAccess reads as safe.SafeAccess from outside and says it twice; Go's naming convention exists for this, with the package name doing the qualifying. Likewise safe.Add, safe.Sqrt and safe.GetString rather than safe.SafeAdd, and the entry point is safe.New(v) rather than safe.Safe(v) — whose own doc comment already said New

func Map

func Map[T any, R any](s *Access, fn func(T) R) *Access

Map 映射转换(支持泛型)

func New

func New(v interface{}) *Access

New 创建安全访问装饰器

v 为 nil 时返回的 Access 标记为无效,后续取值一律走默认值分支

[EN] Creates the decorator. A nil v yields an Access marked invalid, so every later read takes the default-value path

func (*Access) AsBool

func (s *Access) AsBool() bool

AsBool 智能布尔转换

func (*Access) AsJSON

func (s *Access) AsJSON(indent bool) (string, error)

AsJSON 转换为JSON字符串

func (*Access) AsString

func (s *Access) AsString(timeLayout ...string) string

AsString 智能字符串转换

func (*Access) AsStringSlice

func (s *Access) AsStringSlice() []string

AsStringSlice 字符串切片转换

func (*Access) At

func (s *Access) At(fieldPath string, defaultValue ...interface{}) *Access

At 通用字段路径访问方法,支持链式调用和默认值

func (*Access) Bool

func (s *Access) Bool(defaultValue ...bool) bool

Bool 获取布尔值,如果无效则返回默认值

func (*Access) BoolAt

func (s *Access) BoolAt(fieldPath string, defaultValue ...bool) bool

BoolAt 获取布尔字段的便捷方法

func (*Access) Contains

func (s *Access) Contains(target interface{}) bool

Contains 检查切片或map是否包含指定值

func (*Access) Duration

func (s *Access) Duration(defaultValue ...time.Duration) time.Duration

Duration 获取时间间隔值

func (*Access) DurationAt

func (s *Access) DurationAt(fieldPath string, defaultValue ...time.Duration) time.Duration

DurationAt 获取时间间隔字段的便捷方法

func (*Access) Field

func (s *Access) Field(fieldName string) *Access

Field 安全访问字段,支持链式调用 支持多种命名风格:camelCase, PascalCase, snake_case, kebab-case

先按调用方给的原名直取,未命中才去算命名风格变体: 原名命中是最常见的情形,而算变体要做四次字符串转换并各分配一次, 让命中路径免掉这笔开销比优化未命中路径划算得多

[EN] The caller's own spelling is tried first and the naming-style variants are only computed on a miss. Hitting on the given name is the common case, while building variants means four string conversions with an allocation each, so sparing the hit path that cost matters more than tuning the miss path

func (*Access) Filter

func (s *Access) Filter(predicate func(interface{}) bool) *Access

Filter 过滤值(类似JavaScript的filter)

func (*Access) FlatMap

func (s *Access) FlatMap(fn func(interface{}) *Access) *Access

FlatMap 扁平化映射

func (*Access) Float32

func (s *Access) Float32(defaultValue ...float32) float32

Float32 获取float32值,支持强大的类型自动转换

func (*Access) Float64

func (s *Access) Float64(defaultValue ...float64) float64

Float64 获取float64值,支持强大的类型自动转换

func (*Access) GetInt64Value

func (sa *Access) GetInt64Value(defaultValue int64) int64

GetInt64Value 从Access中获取int64值,支持int/int64/float64类型转换

func (*Access) GetIntValue

func (sa *Access) GetIntValue(defaultValue int) int

GetIntValue 从Access中获取int值,支持int/int64/float64类型转换

func (*Access) IfPresent

func (s *Access) IfPresent(fn func(interface{})) *Access

IfPresent 如果值存在则执行函数

func (*Access) Int

func (s *Access) Int(defaultValue ...int) int

Int 获取整数值,支持强大的类型自动转换

func (*Access) Int32

func (s *Access) Int32(defaultValue ...int32) int32

Int32 获取int32值

func (*Access) Int64

func (s *Access) Int64(defaultValue ...int64) int64

Int64 获取int64值,支持强大的类型自动转换

func (*Access) IntAt

func (s *Access) IntAt(fieldPath string, defaultValue ...int) int

IntAt 获取整数字段的便捷方法

func (*Access) IsBool

func (s *Access) IsBool() bool

IsBool 检查是否为布尔值

func (*Access) IsEmpty

func (s *Access) IsEmpty() bool

IsEmpty 检查是否为空值

func (*Access) IsMap

func (s *Access) IsMap() bool

IsMap 检查是否为map

func (*Access) IsNonEmpty

func (s *Access) IsNonEmpty() bool

IsNonEmpty 检查是否非空

func (*Access) IsNumber

func (s *Access) IsNumber() bool

IsNumber 检查是否为数值类型

func (*Access) IsSlice

func (s *Access) IsSlice() bool

IsSlice 检查是否为切片

func (*Access) IsString

func (s *Access) IsString() bool

IsString 检查是否为字符串

func (*Access) IsValid

func (s *Access) IsValid() bool

IsValid 检查值是否有效

func (*Access) Keys

func (s *Access) Keys() []string

Keys 获取map的所有键

func (*Access) Len

func (s *Access) Len() int

Len 获取长度(字符串、切片、map等)

func (*Access) Map

func (s *Access) Map(fn func(interface{}) interface{}) *Access

Map 转换值(类似JavaScript的map)

func (*Access) OrElse

func (s *Access) OrElse(alternative interface{}) *Access

OrElse 如果当前值无效,返回备用值

func (*Access) String

func (s *Access) String(defaultValue ...string) string

String 获取字符串值

func (*Access) StringAt

func (s *Access) StringAt(fieldPath string, defaultValue ...string) string

StringAt 获取字符串字段的便捷方法

func (*Access) StringOr

func (s *Access) StringOr(defaultValue string) string

StringOr 获取字符串值,如果无效或为空则返回默认值

func (*Access) StringOrAt

func (s *Access) StringOrAt(fieldPath string, defaultValue string) string

StringOrAt 获取字符串字段,支持空值默认值

func (*Access) Uint

func (s *Access) Uint(defaultValue ...uint) uint

Uint 获取uint值,支持强大的类型自动转换

func (*Access) Uint64

func (s *Access) Uint64(defaultValue ...uint64) uint64

Uint64 获取uint64值

func (*Access) Unless

func (s *Access) Unless(predicate func(interface{}) bool, fn func(interface{}) interface{}) *Access

Unless 条件排除

func (*Access) Value

func (s *Access) Value() interface{}

Value 获取原始值

func (*Access) ValueAt

func (s *Access) ValueAt(fieldPath string, defaultValue ...interface{}) interface{}

ValueAt 获取任意类型字段的原始值

func (*Access) Values

func (s *Access) Values() []interface{}

Values 获取map的所有值

func (*Access) When

func (s *Access) When(predicate func(interface{}) bool, fn func(interface{}) interface{}) *Access

When 条件执行

type KV

type KV[K comparable, V any] map[K]V

func PtrKV

func PtrKV[K comparable, V any](src *KV[K, V]) KV[K, V]

Ptr 安全转换 *[K]V 到 [K]V(空 )

type NilPanicDetector

type NilPanicDetector struct {
	// contains filtered or unexported fields
}

NilPanicDetector Nil Panic检测器

func NewNilPanicDetector

func NewNilPanicDetector() *NilPanicDetector

NewNilPanicDetector 创建新的检测器

func (*NilPanicDetector) GenerateReport

func (d *NilPanicDetector) GenerateReport() string

GenerateReport 生成报告

func (*NilPanicDetector) GetFixSuggestions

func (d *NilPanicDetector) GetFixSuggestions() []string

GetFixSuggestions 获取修复建议

func (*NilPanicDetector) GetIssues

func (d *NilPanicDetector) GetIssues() []NilPanicIssue

GetIssues 获取所有检测到的问题

func (*NilPanicDetector) ScanDirectory

func (d *NilPanicDetector) ScanDirectory(dirPath string) error

ScanDirectory 扫描目录中的Go文件

func (*NilPanicDetector) ScanFile

func (d *NilPanicDetector) ScanFile(filePath string) error

ScanFile 扫描单个文件

type NilPanicIssue

type NilPanicIssue struct {
	File        string `json:"file"`
	Line        int    `json:"line"`
	Column      int    `json:"column"`
	Type        string `json:"type"`
	Description string `json:"description"`
	Severity    string `json:"severity"`
	Code        string `json:"code"`
}

NilPanicIssue Nil Panic问题

type RiskPattern

type RiskPattern struct {
	Name        string
	Pattern     string
	Description string
	Severity    string
}

RiskPattern 风险模式

type TemporalHasher

type TemporalHasher struct {
	// contains filtered or unexported fields
}

TemporalHasher 临时哈希生成器 在时间窗口内,相同输入生成相同哈希;超过窗口后生成新哈希

使用场景: - WebSocket ClientID:同一用户+设备短期内复用连接标识 - 会话标识:短期内相同条件复用会话 - 防重放:基于时间窗口的请求去重 - 缓存键:短期内相同条件复用缓存

func NewTemporalHasher

func NewTemporalHasher(opts ...TemporalHasherOption) *TemporalHasher

NewTemporalHasher 创建临时哈希生成器

func (*TemporalHasher) Hash

func (h *TemporalHasher) Hash(parts ...string) string

Hash 生成临时哈希 parts: 参与哈希计算的各个部分(会自动排序以保证一致性)

func (*TemporalHasher) HashAt

func (h *TemporalHasher) HashAt(t time.Time, parts ...string) string

HashAt 使用指定时间生成哈希

func (*TemporalHasher) HashMap

func (h *TemporalHasher) HashMap(kvMap map[string]string) string

HashMap 使用 map 生成哈希(会自动排序 key)

func (*TemporalHasher) HashMapAt

func (h *TemporalHasher) HashMapAt(t time.Time, kvMap map[string]string) string

HashMapAt 使用指定时间和 map 生成哈希

func (*TemporalHasher) IsExpired

func (h *TemporalHasher) IsExpired(hash string, parts ...string) bool

IsExpired 检查哈希是否已过期(超过时间窗口)

func (*TemporalHasher) IsExpiredMap

func (h *TemporalHasher) IsExpiredMap(hash string, kvMap map[string]string) bool

IsExpiredMap 检查哈希是否已过期(使用 map 参数)

func (*TemporalHasher) Length

func (h *TemporalHasher) Length() int

Length 获取配置的哈希长度

func (*TemporalHasher) Window

func (h *TemporalHasher) Window() time.Duration

Window 获取配置的时间窗口

type TemporalHasherOption

type TemporalHasherOption func(*temporalHasherConfig)

TemporalHasherOption 配置选项函数

func WithLength

func WithLength(length int) TemporalHasherOption

WithLength 设置哈希长度

func WithSeparator

func WithSeparator(separator string) TemporalHasherOption

WithSeparator 设置分隔符

func WithWindow

func WithWindow(window time.Duration) TemporalHasherOption

WithWindow 设置时间窗口

Jump to

Keyboard shortcuts

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