doraemon

package module
v0.6.3 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2025 License: MIT Imports: 29 Imported by: 10

README

doraemon

Installation

go get -u github.com/doraemonkeys/doraemon

Documentation

Index

Examples

Constants

View Source
const DevLocalConfigFileKeyWord = ".local.dev"
View Source
const WindowsReadLnkFileErrorKeyWords = "Incorrect function"

When reading certain abnormal shortcut files on Windows, an error "read xxx: Incorrect function" may occur. These shortcuts are reported as folders when queried using os.Stat() (IsDir() returns true). However, when using os.ReadDir to read the parent folder and query this child shortcut, IsDir() returns false.

Variables

View Source
var PanicHandlers = []func(any){
	func(recoveredErr any) {
		var buf [4096]byte
		n := runtime.Stack(buf[:], false)
		msg := fmt.Sprintf("%v\n%s\n", recoveredErr, buf[:n])
		_ = os.WriteFile(fmt.Sprintf("panic-%s.log",
			time.Now().Format("2006.01.02_15.04.05")),
			[]byte(msg), 0644)
		_, _ = os.Stderr.WriteString("\x1b[31mpanic\x1b[0m: " + msg + "\n")
	},
}

PanicHandlers is the global default panic handler. It will print the panic message and stack trace to the console and write it to a file.

Functions

func Assert added in v0.2.0

func Assert(ok bool)

func AssertEqual added in v0.2.0

func AssertEqual[T comparable](t1, t2 T, tn ...T)

func AssertError added in v0.2.0

func AssertError(err error)

func BytesAsPointer

func BytesAsPointer(b []byte) (unsafe.Pointer, int, int)

func BytesToString

func BytesToString(b []byte) string

BytesToString converts a byte slice to a string without copying. The byte slice must not be modified after the conversion. otherwise, the string may be corrupted.

func Compress

func Compress(file []string, zipFile string) error

Compress compresses the file to the zip file.

func ComputeFileMd5 added in v0.3.0

func ComputeFileMd5(filename string) ([]byte, error)

func ComputeFileSha1 added in v0.3.0

func ComputeFileSha1(filename string) ([]byte, error)

func ComputeMD5 added in v0.3.0

func ComputeMD5(content io.Reader) ([]byte, error)

func ComputeMD5Hex added in v0.3.0

func ComputeMD5Hex(content io.Reader) (string, error)

func ComputeSHA1 added in v0.3.0

func ComputeSHA1(content io.Reader) ([]byte, error)

func ComputeSHA1Hex added in v0.3.0

func ComputeSHA1Hex(content io.Reader) (string, error)

func ComputeSHA256 added in v0.3.0

func ComputeSHA256(content io.Reader) ([]byte, error)

func ComputeSHA256Hex added in v0.3.0

func ComputeSHA256Hex(content io.Reader) (string, error)

func CopyDir

func CopyDir(src, dst string, overwrite bool) error

复制文件夹到指定目录

overwrite为true时,如果目标文件夹存在名字相同的文件则覆盖, overwrite为false时,如果目标文件存在则返回错误。 dst,scr都必须是一个存在的文件夹,否则返回错误。

func CopyFile

func CopyFile(src, dst string, overwrite bool) error

复制文件到指定目录

overwrite为true时,如果目标文件存在则覆盖, overwrite为false时,如果目标文件存在则返回错误。 dst必须是一个存在的文件夹,否则返回错误。 scr为文件的绝对或相对路径(包含文件名)。

func CopyFileOrDir

func CopyFileOrDir(src, dst string, overwrite bool) error

复制文件或文件夹

overwrite为true时,如果目标文件存在则覆盖(dst中的目标文件或文件夹会被直接删除), overwrite为false时,如果目标文件存在则返回错误。 scr,dst 为绝对或相对路径,dst必须是一个文件夹(可以不存在)。

func CreateShortcut

func CreateShortcut(filename, dir string) error

给目录或文件创建快捷方式(filename可以为绝对路径也可以为相对路径,dir必须是绝对路径)

func DebugInfo added in v0.6.0

func DebugInfo() string

DebugInfo collects and returns a string containing various debug information about the current program execution environment.

func DeepCreateEmptyInstance added in v0.6.2

func DeepCreateEmptyInstance(rType reflect.Type) interface{}

DeepCreateEmptyInstance create a empty instance of the type, recursively create the instance of the struct field,include the struct field's pointer

func DefaultHashCalc added in v0.6.2

func DefaultHashCalc[K comparable](shardCount int) func(key K) int

DefaultHashCalc returns a default sharding function using FNV-1a hash.

func ExecutionFilePath

func ExecutionFilePath() (string, error)

获取当前程序源代码的详细路径 D:/Go/workspace/port/network_learn/server/server.go

func FileOrDirIsExist

func FileOrDirIsExist(path string) bool

FileOrDirIsExist Check if a file or directory exists

func FindStructEmptyStringField added in v0.3.1

func FindStructEmptyStringField(s any, ignores map[string]bool) string

查找结构体中的空字符串字段。如果找到,则返回字段名;否则返回空字符串。 string指针可以为空,但是string不可以为空。

func GenRandomAsciiString added in v0.2.1

func GenRandomAsciiString(length int) string

GenRandomAsciiString generate a random string of a specified length, only containing uppercase and lowercase letters and numbers.

func GenRandomString added in v0.2.1

func GenRandomString(charset string, length int) string

func GenerateCPUIntensiveTask added in v0.6.1

func GenerateCPUIntensiveTask(duration time.Duration) func()

GenerateCPUIntensiveTask returns a function that performs a duration CPU-intensive task

func GenerateUniqueFilepath added in v0.6.0

func GenerateUniqueFilepath(filePath string) string

GenerateUniqueFilepath generates a unique filepath by appending a number to the original filepath if the original filepath already exists.

func GetAllNamesInPath

func GetAllNamesInPath(path string) ([]string, error)

获取path路径下的文件(含后缀)和文件夹名称

func GetAllNamesRecursive deprecated

func GetAllNamesRecursive(path string) ([]string, error)

Deprecated: use ListAllRecursively instead

递归获取path下所有文件和文件夹 path决定返回的文件路径是绝对路径还是相对路径。

func GetCStringLen

func GetCStringLen(str unsafe.Pointer) int

func GetCurrentPath

func GetCurrentPath() (string, error)

获取当前程序的执行环境路径(不包含可执行文件名称)

func GetExecutionPath

func GetExecutionPath() (string, error)

获取当前程序所在的绝对路径+文件名

func GetExecutionPath2

func GetExecutionPath2() (string, error)

获取当前程序的执行路径(包含可执行文件名称) C:\Users\*\AppData\Local\Temp\*\exe\main.exe 或 .\main.exe (读取命令参数的方式)

func GetFileNamesRecursive deprecated

func GetFileNamesRecursive(path string) ([]string, error)

Deprecated: 使用 ListFilesRecursively 代替

递归获取path下所有文件(包含子文件夹中的文件)。 path决定返回的文件路径是绝对路径还是相对路径。

func GetFileNmaesInPath

func GetFileNmaesInPath(path string) ([]string, error)

获取path下所有文件名称(含后缀,不含路径)

func GetFolderNamesInPath

func GetFolderNamesInPath(path string) ([]string, error)

获取path路径下的文件夹名称(不含路径)

func GetFolderNamesRecursive deprecated

func GetFolderNamesRecursive(path string) ([]string, error)

Deprecated: use ListDirsRecursively instead

递归获取path下所有文件夹(包含子文件夹) path决定返回的文件路径是绝对路径还是相对路径。

func GetFormatedTimeFromUnixMilli

func GetFormatedTimeFromUnixMilli(rawTime int64, format string) string

时间戳毫秒 -> format time(Local)。 if rawTime is "" , return current time。

func GetFormatedTimeFromUnixMilliStr

func GetFormatedTimeFromUnixMilliStr(rawTime string, format string) (string, error)

时间戳毫秒 -> format time(Local)。 if rawTime is "" , return current time。

func GetMd5 deprecated added in v0.3.0

func GetMd5(content []byte) ([]byte, error)

Deprecated: use MD5 instead

func GetMd5Hex deprecated added in v0.3.0

func GetMd5Hex(content []byte) (string, error)

Deprecated: use MD5Hex instead

func GetRandomUserAgent

func GetRandomUserAgent() string

随机获取user-agent(不含移动端)

func GetSha1 deprecated

func GetSha1(data []byte) ([]byte, error)

Deprecated: use SHA1 instead

func GetSha256 deprecated

func GetSha256(content []byte) ([]byte, error)

Deprecated: use SHA256 instead

func GetYesterday

func GetYesterday() time.Time

获取昨天的日期

func GoWithRecover added in v0.3.0

func GoWithRecover(fn func(), additionalHandlers ...func(recoveredErr any))

func HasAnyPrefix added in v0.6.2

func HasAnyPrefix(s string, prefixs ...string) bool

func HexToBigInt added in v0.5.0

func HexToBigInt(hex string) *big.Int

func HexToInt

func HexToInt(hex string) int64

HexToInt converts a hexadecimal string to an int64 value. If an error occurs during conversion, the function panics.

func HexToInt2 added in v0.3.0

func HexToInt2(hex string) (int64, error)

func HumanReadableByteSize added in v0.6.0

func HumanReadableByteSize[T uint64 | int64 | uint32 | int32 | uint | int](bytes T) string

func InitConfig added in v0.3.4

func InitConfig[T any](
	configFilePath string,
	createDefault func(path string) error,
	unmarshal func(data []byte, v any) error,
) (*T, error)

InitConfig initializes a configuration object of type T from a specified file. If a development-specific configuration file exists (with a ".local.dev" suffix), it will be loaded instead. If the specified configuration file does not exist, it will be created using the provided createDefault function. The unmarshal function is used to parse the configuration file content into the object.

func InitJsonConfig added in v0.3.2

func InitJsonConfig[T any](configFilePath string, createDefault func(path string) error) (*T, error)

InitJsonConfig initializes a JSON configuration object of type T from a file. If the file doesn't exist, it creates a default file using the createDefault function (or a default create function if not provided). It uses JSON unmarshalling to parse the file content into the config object.

func IsAdmin

func IsAdmin() bool

IsAdmin checks if the current process is running with administrative privileges.

func IsChildDir

func IsChildDir(parent, child string) bool

判断child是否是parent的子文件夹(不存在的文件夹会返回false)

func IsChildDir2

func IsChildDir2(parent, child string) bool

判断child是否是parent的子文件夹(为了性能只是简单的判断前缀,需要保证路径分隔符一致)

func IsDir

func IsDir(path string) (is bool, exist bool, err error)

是否为文件夹

func IsFile

func IsFile(path string) (is bool, exist bool, err error)

是否为文件

func IsNil added in v0.3.1

func IsNil(x any) bool

func ListAllRecursively added in v0.6.1

func ListAllRecursively(path string) ([]string, error)

ListAllRecursively recursively retrieves all paths under the specified path, including files and directories. If the path is a file, it returns the path itself. The returned paths are either absolute or relative based on the input path.

func ListDirsRecursively added in v0.6.1

func ListDirsRecursively(path string) ([]string, error)

ListDirsRecursively recursively retrieves all directories under the specified path, including subdirectories. If the path is a directory, it returns the path itself. The returned directory paths are either absolute or relative based on the input path.

func ListFilesRecursively added in v0.6.1

func ListFilesRecursively(path string) ([]string, error)

ListFilesRecursively recursively retrieves all files under the specified path, including files in subdirectories. If the path is a file, it returns the path itself. The returned file paths are either absolute or relative based on the input path.

func MoveFileOrDir

func MoveFileOrDir(src, dst string, overwrite bool) error

移动文件或文件夹到指定目录

overwrite为true时,如果目标文件存在则覆盖(dst中的目标文件或文件夹会被直接删除), overwrite为false时,如果目标文件存在则返回错误。 dst必须是一个存在的文件夹,否则返回错误。 scr为的绝对或相对路径。

func MultiReaderCloser added in v0.5.0

func MultiReaderCloser(readers ...io.ReadCloser) io.ReadCloser

func PressEnterKeyToContinue

func PressEnterKeyToContinue()

func PressEnterKeyToContinue2

func PressEnterKeyToContinue2(ch chan bool)

func PressEnterKeyToContinueWithTimeout

func PressEnterKeyToContinueWithTimeout(timeout time.Duration)

Press Enter Key to Continue with Timeout,超时则退出程序

func ReadAllWithLimitBuffer added in v0.3.5

func ReadAllWithLimitBuffer(reader io.Reader, buf []byte) (n int, err error)

ReadAllWithLimitBuffer reads from reader until EOF or an error occurs. If buf is full before EOF, ReadAllWithLimitBuffer returns an error.

func ReadLines

func ReadLines(reader io.Reader) (lines [][]byte, err error)

ReadLines reads all lines from the given io.Reader and returns them as a slice of byte slices. Each line has leading/trailing whitespace removed.

func ReadStartWithLastLine

func ReadStartWithLastLine(filename string, n int) (string, error)

读取倒数第n行(n从1开始), 若n大于文件行数则返回错误io.EOF。

func ReadTrimmedLines

func ReadTrimmedLines(reader io.Reader) (lines [][]byte, err error)

ReadTrimmedLines reads content from the given io.Reader, splits it into lines, and returns a slice of byte slices. Leading and trailing empty lines (after whitespace trimming) are removed.

func ReverseRead

func ReverseRead(name string, lineNum uint) ([]string, error)

从文件末尾按行读取文件。 name:文件路径 lineNum:读取行数(超过文件行数则读取全文)。 最后一行为空也算读取了一行,会返回此行为空串,若全是空格也会原样返回。 返回的每一行都不包含换行符号。

func ScanFields

func ScanFields(
	lines []string,
	fieldSpaceLimit int,
	recordSpaceLimit int,
	fieldKeyWords map[string]func(string) bool,
) (fields []string, records [][]string, err error)

ScanFields parses a set of text lines (lines) and extracts the field names (fields) from the first line. It then parses the remaining lines as records, where each record is a collection of field values. This function handles a limited number of space characters to separate fields in the records.

Parameters:

  • lines: A slice of strings containing the text lines to be parsed.
  • fieldSpaceLimit: An integer specifying the minimum number of spaces between fields to consider them separate. If 0, any number of spaces is used to separate fields.
  • recordSpaceLimit: An integer specifying the minimum number of spaces between values in a record to consider them separate. If 0, any number of spaces is used to separate values.
  • fieldKeyWords: A map used for fine-grained field association. Keys are field names, and values are functions that take a string (a potential field value) and return true if the value matches that field, helping disambiguate in cases of misalignment.

It is guaranteed that the first line represents field names, and each subsequent line is a valid record.

Returns:

  • fields: A slice of strings representing the names of the fields.
  • records: A slice of string slices, where each inner slice represents a record and contains the values for each field.
  • err: An error object, which is non-nil if an error occurs during parsing (e.g., empty input, no fields found, or an unsupported line format).

Example:

Input lines:
  Name Access  Availability  BlockSize
  C:     3       0           4096
  D:     3                  4096
  E:     3       1           4096
  F:            1           4096

Output:
  fields = ["Name", "Access", "Availability", "BlockSize"]
  records = [
    ["C:", "3", "0", "4096"],
    ["D:", "3", "", "4096"],
    ["E:", "3", "1", "4096"],
    ["F:", "", "1", "4096"],
  ]

func SplitBySpaceLimit

func SplitBySpaceLimit(line string, spaceLimit int) []string

func SplitBySpaceLimit2

func SplitBySpaceLimit2(line string, spaceLimit int) []string

SplitBySpaceLimit2 splits a string by a minimum number of consecutive spaces.

It takes a string `line` and an integer `spaceLimit` as input. It returns a slice of strings, where each string is a part of the original string that was separated by at least `spaceLimit + 1` spaces. Leading and trailing spaces on each split part are trimmed. Empty strings resulting from the split are not included in the output, unless all resulting splits are empty.

Example:

SplitBySpaceLimit2("  foo   bar    baz", 3) == ["foo   bar", "baz"]
SplitBySpaceLimit2("foo       bar", 3)  == ["foo", "bar"]
SplitBySpaceLimit2("   foo   ", 2) == ["foo"]
SplitBySpaceLimit2("      ", 2) == []
SplitBySpaceLimit2("foo", 2) == ["foo"]

func StringAsPointer

func StringAsPointer(s string) (unsafe.Pointer, int)

func StringToBytes

func StringToBytes(s string) []byte

func TrackTime added in v0.3.1

func TrackTime(pre time.Time, message ...string) time.Duration

TrackTime calculates the elapsed time since the given time and prints it.

Usage:

defer TrackTime(time.Now())

func UnCompress

func UnCompress(zipFile, dest string) error

解压

func WriteFile added in v0.6.1

func WriteFile(filePath string, perm fs.FileMode, datas ...[]byte) error

func WriteFile2 added in v0.6.1

func WriteFile2(filePath string, data io.Reader, perm fs.FileMode) error

func WriteFilePreservePerms added in v0.6.2

func WriteFilePreservePerms(name string, data []byte) error

WriteFilePreservePerms writes data to a file named name, preserving existing permissions if the file exists. If the file does not exist, it is created with permissions 0644 (rw-r--r--).

Types

type BufWriteFlushCloser

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

Close automatically Flush and then Close

func NewBufWriteCloser

func NewBufWriteCloser(w io.WriteCloser) *BufWriteFlushCloser

func NewBufWriteCloserSize

func NewBufWriteCloserSize(w io.WriteCloser, size int) *BufWriteFlushCloser

func (*BufWriteFlushCloser) Close

func (b *BufWriteFlushCloser) Close() error

Close closes the BufWriteFlushCloser, flushing the buffer and closing the underlying writer.

func (*BufWriteFlushCloser) Flush

func (b *BufWriteFlushCloser) Flush() error

func (*BufWriteFlushCloser) Write

func (b *BufWriteFlushCloser) Write(p []byte) (n int, err error)

type CheckInRecorder added in v0.6.2

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

CheckInRecorder is a daily check-in recorder that resets at midnight. It's not thread-safe and requires external locking for concurrent access. It uses a uint64 to store the check-in status, each bit represents a day's check-in status: 0 for not checked in, 1 for checked in. It can record up to 64 days.

Example
loc, _ := time.LoadLocation("America/New_York")
recorder := NewEmptyCheckInRecorder(loc)

fmt.Println("Initial record:", recorder.Record())

recorder.CheckIn()

fmt.Println("Record after first check-in:", recorder.Record())

recorder.CheckIn()
fmt.Println("Has signed today:", recorder.HasCheckedInToday())
fmt.Println("Record after same day check-in:", recorder.Record())

mockTime := time.Now().AddDate(0, 0, 2)
recorder.SetClock(func() time.Time { return mockTime })
recorder.CheckIn()

fmt.Println("Record after 2 days later check-in:", recorder.Record())
fmt.Println("check-in on day 0:", recorder.HasCheckIn(0))
fmt.Println("check-in on day 2:", recorder.HasCheckIn(2))

rawRecord, _ := recorder.RawRecord()
fmt.Println("Raw record:", rawRecord)

n := 3
nRecord := recorder.RecordN(n)
fmt.Println("Get record with n = ", n, ":", nRecord)
Output:

Initial record: [false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false]
Record after first check-in: [true false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false]
Has signed today: true
Record after same day check-in: [true false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false]
Record after 2 days later check-in: [true false true false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false]
check-in on day 0: true
check-in on day 2: true
Raw record: 5
Get record with n =  3 : [true false true]

func NewCheckInRecorder added in v0.6.2

func NewCheckInRecorder[T Integer](recordRaw T, lastCheckInTime time.Time) *CheckInRecorder

newCheckInRecorder creates a new CheckInRecorder with existing record and last check-in time.

func NewEmptyCheckInRecorder added in v0.6.2

func NewEmptyCheckInRecorder(location *time.Location) *CheckInRecorder

NewEmptyCheckInRecorder creates a new CheckInRecorder with no check-in history.

func (*CheckInRecorder) CheckIn added in v0.6.2

func (s *CheckInRecorder) CheckIn() bool

CheckIn records a new check-in. It returns false if the user has already checked in today.

func (*CheckInRecorder) ConsecutiveCheckInDays added in v0.6.2

func (s *CheckInRecorder) ConsecutiveCheckInDays() int

ConsecutiveCheckInDays returns the number of consecutive check-in days.

func (*CheckInRecorder) DaysToNextMilestone added in v0.6.2

func (s *CheckInRecorder) DaysToNextMilestone(milestone int) int

DaysToNextMilestone returns the remaining days to reach the next milestone (e.g., 7-day, 30-day).

func (*CheckInRecorder) HasCheckIn added in v0.6.2

func (s *CheckInRecorder) HasCheckIn(day int) bool

HasCheckIn checks if the user has checked in on the specified day (0-based index).

func (*CheckInRecorder) HasCheckedInToday added in v0.6.2

func (s *CheckInRecorder) HasCheckedInToday() bool

HasCheckedInToday checks if the user has already checked in today.

func (*CheckInRecorder) RawRecord added in v0.6.2

func (s *CheckInRecorder) RawRecord() (record uint64, lastCheckInTime time.Time)

RawRecord returns the raw record value and last check-in time.

func (*CheckInRecorder) Record added in v0.6.2

func (s *CheckInRecorder) Record() []bool

Record returns the check-in record as a boolean slice.

func (*CheckInRecorder) RecordN added in v0.6.2

func (s *CheckInRecorder) RecordN(n int) []bool

RecordN returns the check-in record as a boolean slice with the specified length.

func (*CheckInRecorder) SetClock added in v0.6.2

func (s *CheckInRecorder) SetClock(clock func() time.Time)

type ConfigWrapper added in v0.6.2

type ConfigWrapper[T comparable] struct {
	ConfigMu sync.RWMutex
	Config   T
	// contains filtered or unexported fields
}

func NewConfigWrapper added in v0.6.2

func NewConfigWrapper[T comparable](filePath string) *ConfigWrapper[T]

func NewConfigWrapper2 added in v0.6.2

func NewConfigWrapper2[T comparable](filePath string) (*ConfigWrapper[T], error)

func (*ConfigWrapper[T]) Path added in v0.6.2

func (c *ConfigWrapper[T]) Path() string

func (*ConfigWrapper[T]) Reload added in v0.6.2

func (c *ConfigWrapper[T]) Reload() error

Reload will cause panic, Do not use this function.

If you need to reload the configuration, please create a new ConfigWrapper.

func (*ConfigWrapper[T]) Save added in v0.6.2

func (c *ConfigWrapper[T]) Save() error

func (*ConfigWrapper[T]) SaveTo added in v0.6.2

func (c *ConfigWrapper[T]) SaveTo(filePath string) error

func (*ConfigWrapper[T]) SetJsonIndent added in v0.6.2

func (c *ConfigWrapper[T]) SetJsonIndent(jsonIndent string)

type ConnectionStats added in v0.6.2

type ConnectionStats struct {
	ID           string
	BytesRead    uint64
	BytesWritten uint64
	LocalAddr    string
	RemoteAddr   string
	Duration     time.Duration
}

type CopyChecker added in v0.2.0

type CopyChecker uintptr

CopyChecker holds back pointer to itself to detect object copying.

func (*CopyChecker) Check added in v0.2.0

func (c *CopyChecker) Check() error

Check checks if the CopyChecker object has been copied. The Check method records its address the first time it is called and checks whether its address has changed the next time it is called. The Check method is thread-safe and can be called from multiple goroutines.

type Incomparable added in v0.6.1

type Incomparable [0]func()

Incomparable is a zero-width, non-comparable type. Adding it to a struct makes that struct also non-comparable, and generally doesn't add any size (as long as it's first).

type Integer added in v0.6.2

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

Integer is a type constraint for integer types.

type LazyFileWriter added in v0.5.1

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

func NewLazyFileWriter added in v0.5.1

func NewLazyFileWriter(filePath string) *LazyFileWriter

NewLazyFileWriter creates a new LazyFileWriter with the given file path

func (*LazyFileWriter) Close added in v0.5.1

func (w *LazyFileWriter) Close() error

Close closes the file. Close will return an error if it has already been called.

func (*LazyFileWriter) File added in v0.5.1

func (w *LazyFileWriter) File() *os.File

File returns the file handle

func (*LazyFileWriter) IsCreated added in v0.5.1

func (w *LazyFileWriter) IsCreated() bool

IsCreated checks if the file has been created/opened

func (*LazyFileWriter) Name added in v0.5.1

func (w *LazyFileWriter) Name() string

Name returns the base name of the file

func (*LazyFileWriter) Path added in v0.5.1

func (w *LazyFileWriter) Path() string

func (*LazyFileWriter) Sync added in v0.5.1

func (w *LazyFileWriter) Sync() error

Sync flushes file's in-memory state to disk

func (*LazyFileWriter) Write added in v0.5.1

func (w *LazyFileWriter) Write(p []byte) (n int, err error)

Write writes the given bytes to the file, creating the file if it doesn't exist.

type MonitorOption added in v0.6.2

type MonitorOption func(*MonitoredConn)

func WithID added in v0.6.2

func WithID(id string) MonitorOption

func WithReadCallback added in v0.6.2

func WithReadCallback(callback func(id string, data []byte)) MonitorOption

func WithWriteCallback added in v0.6.2

func WithWriteCallback(callback func(id string, data []byte)) MonitorOption

type MonitoredConn added in v0.6.2

type MonitoredConn struct {
	net.Conn
	// contains filtered or unexported fields
}

func NewMonitoredConn added in v0.6.2

func NewMonitoredConn(conn net.Conn, options ...MonitorOption) *MonitoredConn

func (*MonitoredConn) BytesRead added in v0.6.2

func (mc *MonitoredConn) BytesRead() uint64

func (*MonitoredConn) BytesWritten added in v0.6.2

func (mc *MonitoredConn) BytesWritten() uint64

func (*MonitoredConn) Read added in v0.6.2

func (mc *MonitoredConn) Read(b []byte) (n int, err error)

func (*MonitoredConn) Stats added in v0.6.2

func (mc *MonitoredConn) Stats() ConnectionStats

func (*MonitoredConn) Write added in v0.6.2

func (mc *MonitoredConn) Write(b []byte) (n int, err error)

type NoCopy added in v0.2.0

type NoCopy struct{}

NoCopy may be added to structs which must not be copied after the first use.

See https://golang.org/issues/8005#issuecomment-190753527 for details.

Note that it must not be embedded, due to the Lock and Unlock methods.

func (*NoCopy) Lock added in v0.2.0

func (*NoCopy) Lock()

Lock is a no-op used by -copylocks checker from `go vet`.

Don't remove it, as `go vet` won't recognize the type as

func (*NoCopy) Unlock added in v0.2.0

func (*NoCopy) Unlock()

type Pair

type Pair[T1, T2 any] struct {
	First  T1
	Second T2
}

func GetAllNamesInPath2 added in v0.3.0

func GetAllNamesInPath2(path string) ([]Pair[string, bool], error)

获取path路径下的文件(含后缀)和文件夹名称,以及是否为文件夹

type Pool added in v0.6.2

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

Pool contains logic of goroutine reuse.

func NewPool added in v0.6.2

func NewPool(size, queue, spawn int) *Pool

NewPool creates new goroutine pool with given size. It also creates a work queue of given size. Finally, it spawns given amount of goroutines immediately.

func (*Pool) Close added in v0.6.2

func (p *Pool) Close()

Close closes the pool.

After closing, the pool will not accept new tasks and all workers will exit after all the tasks in the queue are finished.

func (*Pool) Go added in v0.6.2

func (p *Pool) Go(task func())

Go schedules task to be executed over pool's workers.

func (*Pool) GoContext added in v0.6.2

func (p *Pool) GoContext(ctx context.Context, task func()) error

type Prize added in v0.6.0

type Prize[T comparable] struct {
	Item   T
	Weight int64
}

Prize represents a prize with a weight

type Publisher added in v0.6.2

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

func NewPublisher added in v0.6.2

func NewPublisher[T any]() *Publisher[T]

func (*Publisher[T]) GetSubscriberCount added in v0.6.2

func (p *Publisher[T]) GetSubscriberCount() int

func (*Publisher[T]) Publish added in v0.6.2

func (p *Publisher[T]) Publish(event T)

func (*Publisher[T]) Subscribe added in v0.6.2

func (p *Publisher[T]) Subscribe(subscriber Subscriber[T])

func (*Publisher[T]) Unsubscribe added in v0.6.2

func (p *Publisher[T]) Unsubscribe(subscriberID string)

type RateLimiter added in v0.6.0

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

func NewRateLimiter added in v0.6.0

func NewRateLimiter(limit int, windowSize time.Duration, subWindowNum int) *RateLimiter

NewRateLimiter creates a new RateLimiter.

Example:

// 100 requests per minute, divided into 6 sub-windows
NewRateLimiter(100, time.Minute, 6)

func (*RateLimiter) Allow added in v0.6.0

func (rl *RateLimiter) Allow(userID string) bool

func (*RateLimiter) CancelCleanup added in v0.6.0

func (rl *RateLimiter) CancelCleanup()

type Result

type Result[T any] struct {
	Err   error
	Value T
}

type ShardedMap added in v0.6.2

type ShardedMap[K comparable, V any] struct {
	// contains filtered or unexported fields
}

ShardedMap is a concurrent map sharded across multiple locks.

func NewMap added in v0.6.2

func NewMap[K comparable, V any](shardCount int, calcFunc func(key K) int) *ShardedMap[K, V]

NewMap creates a new ShardedMap with the specified shard count and sharding function. If calcFunc is nil, it uses DefaultCalc.

func (*ShardedMap[K, V]) Contains added in v0.6.2

func (m *ShardedMap[K, V]) Contains(key K) bool

Contains checks if a key exists in the map.

func (*ShardedMap[K, V]) Delete added in v0.6.2

func (m *ShardedMap[K, V]) Delete(key K)

Delete removes the key-value pair from the map.

func (*ShardedMap[K, V]) Get added in v0.6.2

func (m *ShardedMap[K, V]) Get(key K) (V, bool)

Get retrieves a value from the map, returning the value and a boolean indicating success.

func (*ShardedMap[K, V]) Len added in v0.6.2

func (m *ShardedMap[K, V]) Len() int

Len returns the total number of elements in the map.

func (*ShardedMap[K, V]) LoadOrStore added in v0.6.2

func (m *ShardedMap[K, V]) LoadOrStore(key K, value V) V

LoadOrStore returns the existing value for the key if present. Otherwise, it stores the given value and returns it.

func (*ShardedMap[K, V]) Range added in v0.6.2

func (m *ShardedMap[K, V]) Range(f func(key K, value V) bool)

Range calls f sequentially for each key and value present in the map. If f returns false, range stops the iteration.

func (*ShardedMap[K, V]) Remove added in v0.6.2

func (m *ShardedMap[K, V]) Remove(key K) (V, bool)

Remove removes the key-value pair from the map, returning the removed value and a boolean indicating success.

func (*ShardedMap[K, V]) Set added in v0.6.2

func (m *ShardedMap[K, V]) Set(key K, value V)

Set stores a value for the given key.

func (*ShardedMap[K, V]) ShardIndex added in v0.6.2

func (m *ShardedMap[K, V]) ShardIndex(key K) int

ShardIndex returns the shard index for a given key.

func (*ShardedMap[K, V]) Shards added in v0.6.2

func (m *ShardedMap[K, V]) Shards() int

Shards returns the number of shards in the map.

func (*ShardedMap[K, V]) StoreIfAbsent added in v0.6.2

func (m *ShardedMap[K, V]) StoreIfAbsent(key K, value V)

StoreIfAbsent stores a value only if the key is not present.

func (*ShardedMap[K, V]) StoreIfPresent added in v0.6.2

func (m *ShardedMap[K, V]) StoreIfPresent(key K, value V)

StoreIfPresent stores a value only if the key is already present.

type SimpleKV

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

func NewSimpleKV

func NewSimpleKV(dbPath string) (*SimpleKV, error)

func (*SimpleKV) Delete

func (kv *SimpleKV) Delete(key string) error

func (*SimpleKV) Get

func (kv *SimpleKV) Get(key string) (string, bool)

func (*SimpleKV) Range added in v0.6.2

func (kv *SimpleKV) Range(f func(key, value string) bool)

func (*SimpleKV) Set

func (kv *SimpleKV) Set(key, value string) error

func (*SimpleKV) SetIfNotExist added in v0.2.1

func (kv *SimpleKV) SetIfNotExist(key, value string) (bool, error)

type SlidingWindowRateLimiter added in v0.6.0

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

func NewSlidingWindowRateLimiter added in v0.6.0

func NewSlidingWindowRateLimiter(limit int, windowSize time.Duration, subWindowNum int) *SlidingWindowRateLimiter

func (*SlidingWindowRateLimiter) Allow added in v0.6.0

func (rl *SlidingWindowRateLimiter) Allow() bool

type StdBaseLogger

type StdBaseLogger interface {
	Errorf(string, ...interface{})
	Errorln(...interface{})
	Warnf(string, ...interface{})
	Warnln(...interface{})
	Infof(string, ...interface{})
	Infoln(...interface{})
	Debugf(string, ...interface{})
	Debugln(...interface{})
}

type StdLogger

type StdLogger interface {
	StdBaseLogger
	Panicf(string, ...interface{})
	Panicln(...interface{})
	Tracef(string, ...interface{})
	Traceln(...interface{})
}

type Subscriber added in v0.6.2

type Subscriber[T any] interface {
	// OnEvent will be called when the event occurs.
	// If you need to execute asynchronously, please go a goroutine
	OnEvent(event T)
	// GetID returns the subscriber ID
	GetID() string
}

type Ternary added in v0.5.0

type Ternary int8
const (
	Unknown Ternary = -1
	True    Ternary = 1
	False   Ternary = 0
)

func DirIsExist added in v0.5.0

func DirIsExist(path string) Ternary

DirIsExist Check if a directory exists, return True, False, or Unknown

func FileIsExist

func FileIsExist(path string) Ternary

FileIsExist Check if a file exists, return True, False, or Unknown

func (Ternary) IsFalse added in v0.5.0

func (t Ternary) IsFalse() bool

func (Ternary) IsTrue added in v0.5.0

func (t Ternary) IsTrue() bool

func (Ternary) IsUnknown added in v0.5.0

func (t Ternary) IsUnknown() bool

func (Ternary) String added in v0.5.0

func (t Ternary) String() string

type WaitGroup added in v0.3.0

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

func (*WaitGroup) Start added in v0.3.0

func (w *WaitGroup) Start(fn func())

func (*WaitGroup) Wait added in v0.3.0

func (w *WaitGroup) Wait()

type WeightedRandom added in v0.6.0

type WeightedRandom[T comparable] struct {
	// contains filtered or unexported fields
}

WeightedRandom holds the prizes and their cumulative distribution

func NewWeightedRandom added in v0.6.0

func NewWeightedRandom[T comparable]() *WeightedRandom[T]

func (*WeightedRandom[T]) AddPrize added in v0.6.0

func (wr *WeightedRandom[T]) AddPrize(item T, weight int)

AddPrize adds a new prize with a specified weight to the collection.

func (*WeightedRandom[T]) GetAllPrizes added in v0.6.0

func (wr *WeightedRandom[T]) GetAllPrizes() []Prize[T]

GetAllPrizes returns a copy of all prizes.

func (*WeightedRandom[T]) GetRandomPrize added in v0.6.0

func (wr *WeightedRandom[T]) GetRandomPrize() Prize[T]

GetRandomPrize returns a random prize based on weights.

func (*WeightedRandom[T]) GetRandomPrizeFromSlice added in v0.6.0

func (wr *WeightedRandom[T]) GetRandomPrizeFromSlice(prizes []Prize[T]) Prize[T]

GetRandomPrizeFromSlice selects a random prize from a slice based on weights. It panics if no prize is found.

func (*WeightedRandom[T]) GetRandomPrizeWithTotalWeight added in v0.6.0

func (wr *WeightedRandom[T]) GetRandomPrizeWithTotalWeight() (Prize[T], int64)

GetRandomPrizeWithTotalWeight returns a random prize and the total weight.

func (*WeightedRandom[T]) GetTotalWeight added in v0.6.0

func (wr *WeightedRandom[T]) GetTotalWeight() int64

GetTotalWeight returns the total weight of all prizes.

func (*WeightedRandom[T]) RemovePrize added in v0.6.0

func (wr *WeightedRandom[T]) RemovePrize(item T)

RemovePrize removes a prize from the collection.

type WriteFlushCloser

type WriteFlushCloser interface {
	io.WriteCloser
	Flush() error
}

Directories

Path Synopsis
Record a few snippets of code
Record a few snippets of code
usb
hid
HID package to access Human Interface Devices.
HID package to access Human Interface Devices.
usbdrivedetector
Package usbdrivedetector detects all USB storage devices connected to a computer.
Package usbdrivedetector detects all USB storage devices connected to a computer.

Jump to

Keyboard shortcuts

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