unique

package module
v2.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2024 License: MIT Imports: 7 Imported by: 3

README

unique Build Status license codecov Go Reference

用于生成一个唯一字符串

// 生成由数字和字母组成的唯一字符串,比如 p4k5f81
u := unique.NewString(10)
go u.Serve(context.Background())
u.String()

// 生成由数字组成的唯一字符串,比如 15193130121
u := unique.NewNumber(10)
go u.Serve(context.Background())
u.String()

// 生成由日期与数字组成的唯一字符串,比如 20180222232332-1
u := unique.NewDate(10)
go u.Serve(context.Background())
u.String()

// 或者可以自定义一个 Unique 实例
u := unique.New(10, time.Second, "20060102150405-", 10)
go u.Serve(context.Background())
u.String() // 生成唯一字符串。

安装

go get github.com/issue9/unique/v2

版权

本项目采用 MIT 开源授权许可证,完整的授权说明可在 LICENSE 文件中找到。

Documentation

Overview

Package unique 产生一个唯一字符串

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Rands

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

Rands 生成唯一的随机字符串

Rands 由两部分组成:

  • Unique 负责保证字符串的唯一性,但是内容是有序的;
  • rands.Rands 负责生成混淆的随机字符;

两者结合可以保证生成的内容唯一且无序。相较于 Unique 此对象更具有随机性。

func NewRands added in v2.1.0

func NewRands(bufferSize int, r *rand.Rand, min, max int, bs []byte) *Rands

NewRands 声明 Rands

bufferSize 负责初始化 Uniquerands.Rands 对象; r, min, max, bs 负责初始化 rands.Rands 对象;

func (*Rands) Bytes

func (r *Rands) Bytes() []byte

Bytes 返回 []byte 内容

func (*Rands) Serve

func (r *Rands) Serve(ctx context.Context) error

func (*Rands) String

func (r *Rands) String() string

String 返回字符串内容

type Unique

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

Unique 基于时间戳的唯一不定长字符串

Unique 由两部分组成: 前缀是由一个相对稳定的字符串,与时间相关联; 后缀是一个自增的数值。

每次刷新前缀之后,都会重置后缀的计数器,从头开始。 刷新时间和计数器的步长都是一个随机数。

NOTE: 算法是基于系统时间的。所以必须得保证时间上正确的,否则可能会造成非唯一的情况。 NOTE: 产生的数据有一定的顺序规则。

func New

func New(bufferSize int, duration time.Duration, prefixFormat string, base int) *Unique

New 声明一个新的 Unique

每一秒,最多能产生 math.MaxInt64 个唯一值,需求量超过此值的不适合。

bufferSize 缓存大小,不能小于 1; duration 计数器的重置时间,不能小于 1*time.Second; prefixFormat 格式化 prefix 的方式,若指定,则格式化为时间,否则将时间戳转换为数值; base 数值转换成字符串时,所采用的进制,可以是 [2,36] 之间的值。

func NewDate

func NewDate(bufferSize int) *Unique

NewDate 声明以日期形式表示的 Unique 实例

格式为:20180222232332-1

func NewNumber

func NewNumber(bufferSize int) *Unique

NewNumber 声明以数字形式表示的 Unique 实例

格式为:15193130121

func NewString

func NewString(bufferSize int) *Unique

NewString 声明以字符串形式表示的 Unique 实例

格式为:p4k5f81

func (*Unique) Bytes

func (u *Unique) Bytes() []byte

Bytes 返回 Unique.String 的 []byte 格式

func (*Unique) Serve

func (u *Unique) Serve(ctx context.Context) error

func (*Unique) String

func (u *Unique) String() string

String 返回一个唯一的字符串

Jump to

Keyboard shortcuts

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