utils

package module
v0.0.0-...-cd794a3 Latest Latest
Warning

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

Go to latest
Published: Sep 16, 2024 License: MIT Imports: 17 Imported by: 2

Documentation

Index

Constants

View Source
const (
	//最大1023
	MaxWorkNumber = 1023
	//理论最大4095
	MaxSequenceNumber  = 4000
	WorkLeftShift      = uint(12)
	TimestampLeftShift = uint(22)
)

定义snowflake的参数

View Source
const (
	StatusUnknown = iota + 10
	StatusNil
	StatusPing
	StatusPong
	StatusGoaway
	StatusRequest
	StatusResponse
	StatusNotify
	StatusCtxCancelFunc
	StatusSubscribe
	StatusUnsubscribe
	StatusStream
	StatusBroadcast
	StatusError
)

状态码

View Source
const (
	StatusUnknown16 uint16 = iota + 10
	StatusNil16
	StatusPing16
	StatusPong16
	StatusGoaway16
	StatusRequest16
	StatusResponse16
	StatusNotify16
	StatusCtxCancelFunc16
	StatusSubscribe16
	StatusUnsubscribe16
	StatusStream16
	StatusBroadcast16
	StatusError16
)

状态码

View Source
const (
	StatusContinue           = 100 // RFC 7231, 6.2.1
	StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2
	StatusProcessing         = 102 // RFC 2518, 10.1
	StatusEarlyHints         = 103 // RFC 8297

	StatusOK                   = 200 // RFC 7231, 6.3.1
	StatusCreated              = 201 // RFC 7231, 6.3.2
	StatusAccepted             = 202 // RFC 7231, 6.3.3
	StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4
	StatusNoContent            = 204 // RFC 7231, 6.3.5
	StatusResetContent         = 205 // RFC 7231, 6.3.6
	StatusMultiStatus          = 207 // RFC 4918, 11.1
	StatusAlreadyReported      = 208 // RFC 5842, 7.1
	StatusIMUsed               = 226 // RFC 3229, 10.4.1

	StatusMultipleChoices   = 300 // RFC 7231, 6.4.1
	StatusMovedPermanently  = 301 // RFC 7231, 6.4.2
	StatusFound             = 302 // RFC 7231, 6.4.3
	StatusSeeOther          = 303 // RFC 7231, 6.4.4
	StatusNotModified       = 304 // RFC 7232, 4.1
	StatusUseProxy          = 305 // RFC 7231, 6.4.5
	StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7
	StatusPermanentRedirect = 308 // RFC 7538, 3

	StatusBadRequest                   = 400 // RFC 7231, 6.5.1
	StatusUnauthorized                 = 401 // RFC 7235, 3.1
	StatusPaymentRequired              = 402 // RFC 7231, 6.5.2
	StatusForbidden                    = 403 // RFC 7231, 6.5.3
	StatusNotFound                     = 404 // RFC 7231, 6.5.4
	StatusMethodNotAllowed             = 405 // RFC 7231, 6.5.5
	StatusNotAcceptable                = 406 // RFC 7231, 6.5.6
	StatusProxyAuthRequired            = 407 // RFC 7235, 3.2
	StatusRequestTimeout               = 408 // RFC 7231, 6.5.7
	StatusConflict                     = 409 // RFC 7231, 6.5.8
	StatusGone                         = 410 // RFC 7231, 6.5.9
	StatusLengthRequired               = 411 // RFC 7231, 6.5.10
	StatusPreconditionFailed           = 412 // RFC 7232, 4.2
	StatusRequestEntityTooLarge        = 413 // RFC 7231, 6.5.11
	StatusRequestURITooLong            = 414 // RFC 7231, 6.5.12
	StatusUnsupportedMediaType         = 415 // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4
	StatusExpectationFailed            = 417 // RFC 7231, 6.5.14
	StatusTeapot                       = 418 // RFC 7168, 2.3.3
	StatusMisdirectedRequest           = 421 // RFC 7540, 9.1.2
	StatusUnprocessableEntity          = 422 // RFC 4918, 11.2
	StatusLocked                       = 423 // RFC 4918, 11.3
	StatusFailedDependency             = 424 // RFC 4918, 11.4
	StatusUpgradeRequired              = 426 // RFC 7231, 6.5.15
	StatusPreconditionRequired         = 428 // RFC 6585, 3
	StatusTooManyRequests              = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

	StatusInternalServerError           = 500 // RFC 7231, 6.6.1
	StatusNotImplemented                = 501 // RFC 7231, 6.6.2
	StatusBadGateway                    = 502 // RFC 7231, 6.6.3
	StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
	StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

HTTP状态码,参见RFC 2616

View Source
const (
	StatusContinue16           uint16 = 100
	StatusSwitchingProtocols16 uint16 = 101
	StatusProcessing16         uint16 = 102
	StatusEarlyHints16         uint16 = 103

	StatusOK16                   uint16 = 200
	StatusCreated16              uint16 = 201
	StatusAccepted16             uint16 = 202
	StatusNonAuthoritativeInfo16 uint16 = 203
	StatusNoContent16            uint16 = 204
	StatusResetContent16         uint16 = 205
	StatusPartialContent16       uint16 = 206
	StatusMultiStatus16          uint16 = 207
	StatusAlreadyReported16      uint16 = 208
	StatusIMUsed16               uint16 = 226

	StatusMultipleChoices16   uint16 = 300
	StatusMovedPermanently16  uint16 = 301
	StatusFound16             uint16 = 302
	StatusSeeOther16          uint16 = 303
	StatusNotModified16       uint16 = 304
	StatusUseProxy16          uint16 = 305
	StatusTemporaryRedirect16 uint16 = 307
	StatusPermanentRedirect16 uint16 = 308

	StatusBadRequest16                   uint16 = 400
	StatusUnauthorized16                 uint16 = 401
	StatusPaymentRequired16              uint16 = 402
	StatusForbidden16                    uint16 = 403
	StatusNotFound16                     uint16 = 404
	StatusMethodNotAllowed16             uint16 = 405
	StatusNotAcceptable16                uint16 = 406
	StatusProxyAuthRequired16            uint16 = 407
	StatusRequestTimeout16               uint16 = 408
	StatusConflict16                     uint16 = 409
	StatusGone16                         uint16 = 410
	StatusLengthRequired16               uint16 = 411
	StatusPreconditionFailed16           uint16 = 412
	StatusRequestEntityTooLarge16        uint16 = 413
	StatusRequestURITooLong16            uint16 = 414
	StatusUnsupportedMediaType16         uint16 = 415
	StatusRequestedRangeNotSatisfiable16 uint16 = 416
	StatusExpectationFailed16            uint16 = 417
	StatusTeapot16                       uint16 = 418
	StatusMisdirectedRequest16           uint16 = 421
	StatusUnprocessableEntity16          uint16 = 422
	StatusLocked16                       uint16 = 423
	StatusFailedDependency16             uint16 = 424
	StatusUpgradeRequired16              uint16 = 426
	StatusPreconditionRequired16         uint16 = 428
	StatusTooManyRequests16              uint16 = 429
	StatusRequestHeaderFieldsTooLarge16  uint16 = 431
	StatusUnavailableForLegalReasons16   uint16 = 451

	StatusInternalServerError16           uint16 = 500
	StatusNotImplemented16                uint16 = 501
	StatusBadGateway16                    uint16 = 502
	StatusServiceUnavailable16            uint16 = 503
	StatusGatewayTimeout16                uint16 = 504
	StatusHTTPVersionNotSupported16       uint16 = 505
	StatusVariantAlsoNegotiates16         uint16 = 506
	StatusInsufficientStorage16           uint16 = 507
	StatusLoopDetected16                  uint16 = 508
	StatusNotExtended16                   uint16 = 510
	StatusNetworkAuthenticationRequired16 uint16 = 511
)

Variables

View Source
var ErrMachineTimeUnSynchronize = errors.New("机器时钟后跳,timeGen()生成时间戳,早于SnowFlakeId记录的时间戳")

ErrMachineTimeUnSynchronize 定义错误

Functions

func AllocBuffer

func AllocBuffer() *bytes.Buffer

func AllocSlice

func AllocSlice() *[]byte

func BytesToString

func BytesToString(b []byte) string

BytesToString Bytes转String 转后不要修改Bytes

func ChangeDefaultByteSize

func ChangeDefaultByteSize(n uint64)

func ErrorWithFullStack

func ErrorWithFullStack(w error) string

func ErrorWithStack

func ErrorWithStack(err error) string

func FormatRecover

func FormatRecover() ([]byte, any)

func FreeBuffer

func FreeBuffer(x *bytes.Buffer)

func FreeSlice

func FreeSlice(x *[]byte)

func GetWorkID

func GetWorkID(id int64) int64

GetWorkID 取得工作机器id

func Hash64FNV1A

func Hash64FNV1A[T string | []byte](data T) uint64

FNV-1a算法

func Hash64WY

func Hash64WY[T string | []byte](data T, seed uint64) uint64

Hash64WY returns a 64bit digest of the data with different ones for every seed.

func IntegerEqual

func IntegerEqual[T Integer](a, b []T) bool

IntegerEqual 判断两个整数切片的内容是否完全相同

func MetaDictEncode

func MetaDictEncode(m MetaDict[string]) []byte

Encode 编码 将字典编码为字节切片。

func MetaDictEncoder

func MetaDictEncoder(m MetaDict[string], w io.Writer) error

func PrivateIP4

func PrivateIP4() string

PrivateIP4 本地IP4地址

func ReplaceAttr

func ReplaceAttr(_ []string, a slog.Attr) slog.Attr

func StringToBytes

func StringToBytes(s string) (b []byte)

StringToBytes String转Bytes 转后不要修改Bytes

func WrapStack

func WrapStack(skip int, err error) error

Types

type ByTier

type ByTier []*Computer

func (ByTier) Len

func (t ByTier) Len() int

func (ByTier) Less

func (t ByTier) Less(i, j int) bool

func (ByTier) Swap

func (t ByTier) Swap(i, j int)

type Cell

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

type Computer

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

Computer 衍生 - 衍生能缓存计算结果,避免重复的计算 惰性求值(lazy evaluate)- 只有被使用到的才会计算结果

func NewComputer

func NewComputer(effect func(any), evaluate func(...Parent) any, p ...Parent) *Computer

NewComputer 线程不安全

func (*Computer) Load

func (c *Computer) Load() any

Load 线程不安全,需控制在evaluate函数内运行

func (*Computer) Operate

func (c *Computer) Operate(u *Universe)

Operate 非原子性,有一定的延迟。

type CopyOnWriteList

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

CopyOnWriteList (COW)需要修改的时候拷贝一个副本出来,适用不频繁写的场景 修改时新数据原子替换旧数据地址,旧数据由GC回收。

func NewCopyOnWriteList

func NewCopyOnWriteList() *CopyOnWriteList

NewCopyOnWriteList 新增

func (*CopyOnWriteList) Add

func (l *CopyOnWriteList) Add(element any)

Add 增加

func (*CopyOnWriteList) List

func (l *CopyOnWriteList) List() []any

List 列

func (*CopyOnWriteList) Remove

func (l *CopyOnWriteList) Remove(judge func(any) bool)

Remove 移除

type IValidator

type IValidator interface {
	Var(any, string) error
	Struct(any) error
}

IValidator 接口

type IdempotentCache

type IdempotentCache[T string | []byte] struct {
	// contains filtered or unexported fields
}

IdempotentCache 幂等函数缓存,幂等方法,是指可以使用相同参数重复执行,并能获得相同结果的函数

func (*IdempotentCache[T]) Get

func (ic *IdempotentCache[T]) Get(in T) any

Get 用于获取缓存中的结果

func (*IdempotentCache[T]) Init

func (ic *IdempotentCache[T]) Init(power, seed uint64, do func(T) any)

Init 初始化 power表示缓存大小的指数,seed表示hash的种子,do表示要缓存的幂等函数

type Integer

type Integer interface {
	int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64
}

type MetaDict

type MetaDict[T iMetaDict] struct {
	Key   []uint64
	Value []T
}

MetaDict 非线程安全,key数量超过5个后,效率低于map

func MetaDictDecode

func MetaDictDecode(data []byte) (m MetaDict[string])

Decode 解码 将字节切片解码为字典。

func (MetaDict[iMetaDict]) Del

func (m MetaDict[iMetaDict]) Del(key string) MetaDict[iMetaDict]

Del 根据给定的键删除相应的键值对。

func (MetaDict[iMetaDict]) Get

func (m MetaDict[iMetaDict]) Get(key string) (v iMetaDict, ok bool)

Get 根据给定的键返回相应的值。如果键存在,则返回对应的值和true;如果键不存在,则返回空字符串和false。

func (MetaDict[iMetaDict]) GetAll

func (m MetaDict[iMetaDict]) GetAll() (s []iMetaDict)

GetAll

func (MetaDict[iMetaDict]) Len

func (m MetaDict[iMetaDict]) Len() int

Len 长度

func (MetaDict[iMetaDict]) Set

func (m MetaDict[iMetaDict]) Set(key string, value iMetaDict) MetaDict[iMetaDict]

Set 设置给定键的值,如果该键已存在,则更新值;如果不存在,则添加新的键值对。

type Parent

type Parent interface {
	Load() any
}

type Signal

type Signal struct {
	atomic.Value
	// contains filtered or unexported fields
}

func NewSignal

func NewSignal(v any, do func(any)) *Signal

线程不安全

func (*Signal) Set

func (s *Signal) Set(u *Universe, a any)

Set 非原子性,有一定的延迟。

type SnowFlakeID

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

SnowFlakeID 工作站

func NewSnowFlakeID

func NewSnowFlakeID(id int64, startupTime int64) *SnowFlakeID

NewSnowFlakeID 工作组

func (*SnowFlakeID) GetWorkID

func (s *SnowFlakeID) GetWorkID() int64

GetWorkID 取得工作机器id

func (*SnowFlakeID) NextID

func (s *SnowFlakeID) NextID() (int64, error)

NextID 取得 snowflake id.

type Timing

type Timing struct {
	AddTaskChan chan task
	// contains filtered or unexported fields
}

func NewTiming

func NewTiming(p func(error)) *Timing

NewTiming 新建

func (*Timing) AddTask

func (t *Timing) AddTask(next time.Time, f func() time.Duration) error

AddTask 加入任务

func (*Timing) Stop

func (t *Timing) Stop()

Stop 停止

type TokenBucketLimiter

type TokenBucketLimiter struct {
	//限流器速率,每秒处理的令牌数
	LimitRate int64
	//限流器大小,存放令牌的最大值
	LimitSize int64
	//加入的时间间隔
	Snippet time.Duration
	// contains filtered or unexported fields
}

Limiter 限流器 Token Bucket(令牌桶) 每隔一段时间加入一批令牌,达到上限后,不再增加。

func NewTokenBucketLimiter

func NewTokenBucketLimiter(limitRate, limitSize int64, snippet time.Duration) *TokenBucketLimiter

NewTokenBucketLimiter limitRate, limitSize,snippet数值较小时,准确度低。

func (*TokenBucketLimiter) Close

func (t *TokenBucketLimiter) Close()

Close 关闭。

func (*TokenBucketLimiter) Run

func (t *TokenBucketLimiter) Run()

func (*TokenBucketLimiter) Take

func (t *TokenBucketLimiter) Take(n int64) error

Wait 等待,申请n个令牌,取不到足够数量时返回错误。

func (*TokenBucketLimiter) Task

func (t *TokenBucketLimiter) Task() time.Duration

type Universe

type Universe struct {
	SetSignalChan chan setSignalMsg
	ComputerChan  chan *Computer
	// contains filtered or unexported fields
}

func NewUniverse

func NewUniverse() *Universe

func (*Universe) Close

func (u *Universe) Close()

Close 关闭

func (*Universe) Run

func (u *Universe) Run()

Jump to

Keyboard shortcuts

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