common

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2025 License: GPL-3.0 Imports: 28 Imported by: 3

README

go-common

Common utilities for most Go applications

Documentation

Index

Constants

View Source
const (
	ID_TIME_BYTES   = 8
	ID_SERIAL_BYTES = 8
)
View Source
const (
	DEFAULT_NANOID_LENGTH = 12
)
View Source
const Nil = ID("")

Variables

View Source
var (
	ErrParseMissingValue                   = errors.New("missing argument value")
	ErrParseUnexpectedArgument             = errors.New("unexpected argument: %s")
	ErrParseDuplicatedOptionID             = errors.New("the option with the same id '%d' already exists")
	ErrParseDuplicatedOptionName           = errors.New("the option with the same name '%s' already exists")
	ErrParseMissingOptionNameForID         = errors.New("missing the name for option '%d'")
	ErrParseDuplicatedSubparserID          = errors.New("the subparser with the same id '%d' already exists")
	ErrParseDuplicatedParserName           = errors.New("the subparser with the same name '%s' already exists")
	ErrParseMissingParserNameForID         = errors.New("missing the name for sub-parser '%d'")
	ErrParseArgumentNotFound               = errors.New("argument '%s' not found")
	ErrParseNoArgumentAcceptValue          = errors.New("no argument accepts the value '%s'")
	ErrParsingInvalidSwitchValue           = errors.New("invalid switch value '%s'")
	ErrParsingOptionSetValueAgain          = errors.New("cannot set value of option again: '%s'")
	ErrParsingNumericOptionValueOutOfRange = errors.New("numeric option value out of range: '%d'")
	ErrParsingNumericOptionInvalidInteger  = errors.New("malformed numeric option value '%s'")
	ErrParsingListExceedMaximumCount       = errors.New("list option exceeds max count: %d")
)

argument parser errors

View Source
var (
	ErrDataKeyNotExist   = errors.New("data with key '%s' not exists")
	ErrDataIndexNotExist = errors.New("data with index %d not exists")
	ErrDataTypeMismatch  = errors.New("data type mismatch, expect %s, got %T")
)
View Source
var (
	ErrNilArgument      = errors.New("the argument is nil: %s")
	ErrEmptyArgument    = errors.New("the argument is empty: %s")
	ErrInvalidArgument  = errors.New("the argument is invalid")
	ErrNoEnoughArgument = errors.New("no enough argument")
	ErrNilPointer       = errors.New("nil pointer is used")
	ErrInvalidCasting   = errors.New("invalid type casting")
)

Predefined common error messages

View Source
var DefaultDateTime time.Time = time.Time{}
View Source
var (
	ErrConvertFail = errors.New("convert failed")
)

Errors that indicates the convertion fail.

Functions

func AddOption

func AddOption[T Arg](ap *ArgParser, arg T) T

AddOption adds an option into the parser with the generic type. Panic if the option could not be added.

func AddPositional

func AddPositional[T Arg](ap *ArgParser, arg T) T

AddPositional adds a positional argument into the parser with the generic type. Panic if the positional could not be added.

func Assert

func Assert(assertion any, args ...any)

Assert simulates the traditional assert() behavior.

func Center

func Center(s string, minWidth int) string

func CheckResult

func CheckResult(result *error) error

CheckResult is a helper function to check the result and return the error.

func Clamp

func Clamp[T constraints.Ordered](value, min, max T) T

help functions Clamp 函数接受一个数值类型,并检查输入值是否在指定范围内。 如果输入值超出范围,则使用边界值。

func ConvertAssign

func ConvertAssign(src any, dst any) error

ConvertAssign converts the src type to dst, and store into the dst.

func DaysBetweenTimes

func DaysBetweenTimes(startDate, endDate time.Time) int

func Ellipsis

func Ellipsis(s string, threshold int) string

func Empty

func Empty(s string) bool

Empty returns true if the string is zero length, or contains spaces only.

func EqualsCase

func EqualsCase(s1, s2 string, caseSensitive bool) bool

EqualsCase returns true if two strings are same.

func ExpandUsersAndVars

func ExpandUsersAndVars(value string) string

func ExpandVars

func ExpandVars(value string) string

func FindOption

func FindOption[T Arg](ap *ArgParser, id int) T

FindOption returns the option by id with the generic type. Panics if the option does not exist.

func FindPositional

func FindPositional[T Arg](ap *ArgParser, id int) T

FindPositional returns the positional by id with the generic type. Panics if the positional does not exist.

func FormatDate

func FormatDate(dt time.Time) string

func FormatDateTime

func FormatDateTime(dt time.Time) string

func HasOneOfPrefixesCase

func HasOneOfPrefixesCase(s string, prefixes []string, caseSensitive bool) bool

HasOneOfPrefixesCase returns true if the string has the one of the give prefixes.

func HasPrefixCase

func HasPrefixCase(s, prefix string, caseSensitive bool) bool

HasPrefixCase returns true if the string has the given prefix.

func If

func If[T any](condition bool, trueValue T) T

check if the any is not nil, nil means both nil and empty, and the interface is pointed to a nil value.

func IfElse

func IfElse[T any](condition bool, trueValue T, falseValue T) T

check if the any is not nil, nil means both nil and empty, and the interface is pointed to a nil value. this is a quick way to simulate the ?: operator in C/C++/Java.

func IndexLastNotAny

func IndexLastNotAny(s string, chars string) int

func IndexNotAny

func IndexNotAny(s string, chars string) int

func IsEmpty

func IsEmpty(any any) bool

func IsEmptyString

func IsEmptyString(v string) bool

func IsNil

func IsNil(any any) bool

check if the any is nil, nil means both nil and empty, and the interface is pointed to a nil value. if the any is not nil, it will check the value of the any, if the value is nil, it will return true, otherwise false.

func LeftJustify

func LeftJustify(s string, minWidth int) string

func LoadEnvAsList

func LoadEnvAsList() []string

func LoadEnvAsMap

func LoadEnvAsMap() map[string]string

func LoadEnvBool

func LoadEnvBool(key string, defaultValue bool) bool

func LoadEnvFile

func LoadEnvFile(filename string) error

env file is typeically a file with name .env, it contains key-value pairs like:

KEY1=VALUE1
KEY2=VALUE2

the key/value pairs will be merged into the current environment. LoadEnvFile loads the env file with the given filename into the current environment.

func LoadEnvFloat

func LoadEnvFloat(key string, defaultValue float64) float64

func LoadEnvInt

func LoadEnvInt(key string, defaultValue int) int

func LoadEnvString

func LoadEnvString(key string, defaultValue string) string

func NewError

func NewError(inner error, args ...any) error

func PackDateTime

func PackDateTime(value time.Time) string

func PadCenter

func PadCenter(builder *strings.Builder, minWidth int) *strings.Builder

func PadLeft

func PadLeft(builder *strings.Builder, minWidth int) *strings.Builder

func PadRight

func PadRight(builder *strings.Builder, minWidth int) *strings.Builder

func Panic

func Panic(args ...any)

Panic simulates the traditional panic() behavior.

func PanicResult

func PanicResult(result *error)

PanicResult is a helper function to panic the error if the result is not nil.

func ParseDateTime

func ParseDateTime(value string) (time.Time, error)

func RandomChars

func RandomChars(n int) (string, error)

func ReorderTimes

func ReorderTimes(startDate time.Time, endDate time.Time) (time.Time, time.Time)

func RightJustify

func RightJustify(s string, minWidth int) string

func SetEnvBool

func SetEnvBool(key string, value bool) error

func SetEnvFloat

func SetEnvFloat(key string, value float64) error

func SetEnvInt

func SetEnvInt(key string, value int) error

func SetEnvString

func SetEnvString(key string, value string) error

func SetResult

func SetResult[T any](result *error, err error, value T) T

func TimeAddDays

func TimeAddDays(date time.Time, days int) time.Time

func ToError

func ToError(any any, args ...any) error

ToError creates a new error message with/without variant args.

func Truncate

func Truncate(s string, maxLength int) string

func UnpackBool

func UnpackBool(value any, result *error) bool

func UnpackDateTime

func UnpackDateTime(value any, result *error) time.Time

func UnpackFloat64

func UnpackFloat64(value any, result *error) float64

func UnpackInt

func UnpackInt(value any, result *error) int

func UnpackList

func UnpackList[T any, V any](list DataList, unpacker UnpackFunc[T, V], result *error) []T

UnpackList function unpacks the DataList to a []T. The function uses the unpack function to convert the value to the target type.

func UnpackMap

func UnpackMap[T any, V any](bag DataBag, unpacker UnpackFunc[T, V], result *error) map[string]T

UnpackMap function unpacks the DataBag to a map[string]T. The function uses the unpack function to convert the value to the target type.

func UnpackString

func UnpackString(value any, result *error) string

func UnpackStringWithEnvReplaced

func UnpackStringWithEnvReplaced(value any, result *error) string

func UnsetEnv

func UnsetEnv(key string) error

Types

type Arg

type Arg interface {
	ID() int                                       // returns the ID of the argument
	Names() []string                               // returns the names of the argument
	Usage() string                                 // returns the usage of the argument
	Init()                                         // initialize the argument to reset all default values
	UpdateValueRef()                               // update the value reference if the value reference is set
	Accept(value string) Result[PARSING_RESULT]    // parse and accept the value of the argument
	UsageDetails(ap *ArgParser, list *StringArray) // format the usage details and store them into the string array
}

Arg is the interface for all arguments (include Switches, Options, and Positionals).

type ArgParser

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

ArgParser defines the argument parser.

func NewArgParser

func NewArgParser(id int, names ...string) *ArgParser

NewArgParser creates a new argument parser with the given ID and names.

func (*ArgParser) ActiveSubparser

func (ap *ArgParser) ActiveSubparser() *ArgParser

ActiveSubparser returns the active subparser. Returns nil if no subparser is active (selected).

func (*ArgParser) AddOption

func (ap *ArgParser) AddOption(arg Arg) error

AddOption adds an option into the parser. Any duplicated ID or name will cause an error.

func (*ArgParser) AddPositional

func (p *ArgParser) AddPositional(arg Arg) error

AddPositional adds a positional argument into the parser. Any duplicated ID will cause an error.

func (*ArgParser) AddSubparser

func (ap *ArgParser) AddSubparser(sp *ArgParser) error

AddSubparser add a sub-parser into the parser. The sub-parser should have a unique id and at least one name.

func (*ArgParser) FindOption

func (ap *ArgParser) FindOption(id int) Arg

FindOption returns the option by id. Returns nil if the option does not exist.

func (*ArgParser) FindPositional

func (ap *ArgParser) FindPositional(id int) Arg

FindPositional returns the positional by id. Returns nil if the positional does not exist.

func (*ArgParser) HasPassthru

func (ap *ArgParser) HasPassthru() bool

HasPassthru returns true if the passthru arguments are available.

func (*ArgParser) ID

func (ap *ArgParser) ID() int

ID returns the parser id.

func (*ArgParser) Names

func (ap *ArgParser) Names() []string

Names returns the parser names. Note, the names could be empty for the root parser.

func (*ArgParser) Parse

func (ap *ArgParser) Parse() error

Parse parse the command line from the default os.Args.

func (*ArgParser) ParseWithArgs

func (ap *ArgParser) ParseWithArgs(args []string) error

ParseWithArgs parse the given arguments.

func (*ArgParser) Passthru

func (ap *ArgParser) Passthru() []string

Passthru returns the passthru arguments. If no passthru arguments are available, returns an empty slice.

func (*ArgParser) SetTitle

func (ap *ArgParser) SetTitle(title string) *ArgParser

func (*ArgParser) SetUsage

func (ap *ArgParser) SetUsage(usage string) *ArgParser

SetUsage sets the argument parser usage.

func (*ArgParser) Title

func (ap *ArgParser) Title() string

func (*ArgParser) Usage

func (ap *ArgParser) Usage() string

Usage returns the parser usage.

type DataBag

type DataBag map[string]any

DataBag is a wrapper of map[string]any, and the elements in the map are converted to appropriate types.

func PackMap

func PackMap[T any](m map[string]T) DataBag

PackMap function creates a DataBag from a map[string]any. The function recognized the interface IPackable, so the value that implements IPackable will be packed by calling the Pack method.

func (DataBag) Bag

func (bag DataBag) Bag(key string, result *error) DataBag

func (DataBag) Bool

func (bag DataBag) Bool(key string, result *error) bool

func (DataBag) BoolWithDefault

func (bag DataBag) BoolWithDefault(key string, defaultValue bool) bool

func (DataBag) Contains

func (bag DataBag) Contains(key string) bool

func (DataBag) DateTime

func (bag DataBag) DateTime(key string, result *error) time.Time

func (DataBag) DateTimeWithDefault

func (bag DataBag) DateTimeWithDefault(key string, defaultValue time.Time) time.Time

func (DataBag) Float64

func (bag DataBag) Float64(key string, result *error) float64

func (DataBag) Float64WithDefault

func (bag DataBag) Float64WithDefault(key string, defaultValue float64) float64

func (DataBag) Get

func (bag DataBag) Get(index any) (any, error)

interface IDataParcel

func (DataBag) Int

func (bag DataBag) Int(key string, result *error) int

func (DataBag) IntWithDefault

func (bag DataBag) IntWithDefault(key string, defaultValue int) int

func (DataBag) Len

func (bag DataBag) Len() int

func (DataBag) List

func (bag DataBag) List(key string, result *error) DataList

func (DataBag) String

func (bag DataBag) String(key string, result *error) string

func (DataBag) StringWithDefault

func (bag DataBag) StringWithDefault(key string, defaultValue string) string

func (DataBag) StringWithEnvReplaced

func (bag DataBag) StringWithEnvReplaced(key string, result *error) string

type DataList

type DataList []any

DataList is a wrapper of []any, and the elements in the list are converted to appropriate types.

func PackList

func PackList[T any](list []T) DataList

PackList function creates a DataList from a []any. The function recognized the interface IPackable, so the value that implements IPackable will be packed by calling the Pack method.

func (DataList) Bag

func (list DataList) Bag(index int, result *error) DataBag

func (DataList) Bool

func (list DataList) Bool(index int, result *error) bool

func (DataList) BoolWithDefault

func (list DataList) BoolWithDefault(index int, defaultValue bool) bool

func (DataList) DateTime

func (list DataList) DateTime(index int, result *error) time.Time

func (DataList) DateTimeWithDefault

func (list DataList) DateTimeWithDefault(index int, defaultValue time.Time) time.Time

func (DataList) Float64

func (list DataList) Float64(index int, result *error) float64

func (DataList) Float64WithDefault

func (list DataList) Float64WithDefault(index int, defaultValue float64) float64

func (DataList) Get

func (list DataList) Get(index any) (any, error)

interface IDataParcel

func (DataList) Int

func (list DataList) Int(index int, result *error) int

func (DataList) IntWithDefault

func (list DataList) IntWithDefault(index int, defaultValue int) int

func (DataList) Len

func (list DataList) Len() int

func (DataList) List

func (list DataList) List(index int, result *error) DataList

func (DataList) String

func (list DataList) String(index int, result *error) string

func (DataList) StringWithDefault

func (list DataList) StringWithDefault(index int, defaultValue string) string

type Date

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

func NewDate

func NewDate(year, month, day int) *Date

func NewDateFromTime

func NewDateFromTime(date time.Time) *Date

func (*Date) AddDays

func (dt *Date) AddDays(days int) *Date

func (*Date) Between

func (dt *Date) Between(dt2 *Date) int

func (*Date) String

func (dt *Date) String() string

type Event

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

func NewEvent

func NewEvent(name string) *Event

func NewEventWithHandler

func NewEventWithHandler(name string, handler IEventHandler) *Event

func (*Event) AddHandler

func (event *Event) AddHandler(handler IEventHandler)

func (*Event) Fire

func (event *Event) Fire(arg any)

func (*Event) Name

func (event *Event) Name() string

type IClosable

type IClosable interface {
	Close() error
}

IClosable defines the contract that the object is closable.

type IConvertible

type IConvertible interface {
	ConvertFrom(src any) error
}

IConvertible interface allow the type to export the convert function to convert between the types.

type ID

type ID string

general unique ID

func NewFlakeID

func NewFlakeID() (ID, error)

func NewFlakeIDWithPrefix

func NewFlakeIDWithPrefix(prefix string) (ID, error)

func NewKSUID

func NewKSUID() (ID, error)

func NewKSUIDWithPrefix

func NewKSUIDWithPrefix(prefix string) (ID, error)

func NewMathID

func NewMathID() ID

func NewMathIDWithPrefix

func NewMathIDWithPrefix(prefix string) ID

func NewNanoID

func NewNanoID(length int) (ID, error)

New generates a unique public ID.

func NewNanoIDWithPrefix

func NewNanoIDWithPrefix(prefix string, length int) (ID, error)

func NewObjectID

func NewObjectID() (ID, error)

func NewObjectIDWithPrefix

func NewObjectIDWithPrefix(prefix string) (ID, error)

func NewSnowflakeID

func NewSnowflakeID(nodeID int64) (ID, error)

func NewSnowflakeIDWithPrefix

func NewSnowflakeIDWithPrefix(prefix string, nodeID int64) (ID, error)

func NewULID

func NewULID() (ID, error)

NewULID generates a new ULID. ULID is a unique identifier that is used in distributed systems. The ULID is a 26-character string that consists of the following parts: 1. A 10-character timestamp value, representing the number of milliseconds since the Unix epoch. 2. A 16-character random value. The ULID is generated using the current time and a random value. Example: 01JAEZW7KJ0H1V8MF7K043YHAV

func NewULIDWithPrefix

func NewULIDWithPrefix(prefix string) (ID, error)

func NewUUID

func NewUUID() (ID, error)

func NewUUIDWithPrefix

func NewUUIDWithPrefix(prefix string) (ID, error)

func (ID) ToUint32

func (pid ID) ToUint32() uint32

type IDataParcel

type IDataParcel interface {
	Get(index any) (any, error)
	Len() int
}

IDataParcel is the interface for the data parcel, which provides the methods to get the data by key or index, and the length of the data.

type IEventHandler

type IEventHandler interface {
	SupportedEventNames() []string
	HandleEvent(event *Event, arg any)
}

type IEventSender

type IEventSender interface {
	AddEventHandler(handler IEventHandler)
	Fire(eventName string, arg any)
}

func NewEventSender

func NewEventSender(supportedEventNames ...string) IEventSender

type IPackable

type IPackable interface {
	Pack() DataBag // Pack packs itself into DataBag.
}

IPackable defines the interface which supports packing itself into DataBag.

type IResult

type IResult interface {
	Any() any
	Error() error
	Success() bool
	Failed() bool
}

type IStatusResult

type IStatusResult[S int] interface {
	IResult
	Status() S
}

type NumericOption

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

NumericOption defines a argument

func NewNumericOption

func NewNumericOption(id int, names ...string) *NumericOption

NewNumericOption creates a new numeric option with the given ID and names.

func (*NumericOption) Accept

func (o *NumericOption) Accept(value string) Result[PARSING_RESULT]

Accept parses and accepts the value of the option.

func (*NumericOption) ID

func (o *NumericOption) ID() int

func (*NumericOption) Init

func (o *NumericOption) Init()

Init initializes the option to reset the default value.

func (*NumericOption) Names

func (o *NumericOption) Names() []string

func (*NumericOption) SetDefaultValue

func (o *NumericOption) SetDefaultValue(value int) *NumericOption

SetDefaultValue sets the default value of the option.

func (*NumericOption) SetUsage

func (o *NumericOption) SetUsage(usage string) *NumericOption

SetUsage sets the usage of the option.

func (*NumericOption) SetValueName

func (o *NumericOption) SetValueName(valueName string) *NumericOption

SetValueName sets the name of the value.

func (*NumericOption) SetValueRange

func (o *NumericOption) SetValueRange(min, max int) *NumericOption

SetValueRange sets the range of the value.

func (*NumericOption) SetValueRef

func (o *NumericOption) SetValueRef(valueRef *int) *NumericOption

SetValueRef sets the reference to the value of the option. The value referenced by valueRef will be set automatically

func (*NumericOption) UpdateValueRef

func (o *NumericOption) UpdateValueRef()

UpdateValueRef updates the value reference if the value reference is set.

func (*NumericOption) Usage

func (o *NumericOption) Usage() string

func (*NumericOption) UsageDetails

func (o *NumericOption) UsageDetails(ap *ArgParser, arr *StringArray)

UsageDetails formats the usage details and stores them into the passed in string array.

func (*NumericOption) Value

func (o *NumericOption) Value() int

Value returns the value of the option.

type NumericOptionList

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

NumericOptionList defines a list of numeric options

func NewNumericOptionList

func NewNumericOptionList(id int, names ...string) *NumericOptionList

NewNumericOptionList creates a new numeric option list with the given ID and names.

func (*NumericOptionList) Accept

func (o *NumericOptionList) Accept(value string) Result[PARSING_RESULT]

Accept parses and accepts the value of the option list.

func (*NumericOptionList) ID

func (o *NumericOptionList) ID() int

func (*NumericOptionList) Init

func (o *NumericOptionList) Init()

Init initializes the option list to reset the default values.

func (*NumericOptionList) Names

func (o *NumericOptionList) Names() []string

func (*NumericOptionList) SetCount

func (o *NumericOptionList) SetCount(count int) *NumericOptionList

SetValueRef sets the reference to the values of the options. The values referenced by valueRef will be set automatically

func (*NumericOptionList) SetCountRange

func (o *NumericOptionList) SetCountRange(min, max int) *NumericOptionList

SetCountRange sets the range of the count of the values.

func (*NumericOptionList) SetUsage

func (o *NumericOptionList) SetUsage(usage string) *NumericOptionList

SetUsage sets the usage of the option list.

func (*NumericOptionList) SetValueName

func (o *NumericOptionList) SetValueName(valueName string) *NumericOptionList

SetValueName sets the name of the value.

func (*NumericOptionList) SetValueRange

func (o *NumericOptionList) SetValueRange(min, max int) *NumericOptionList

SetValueRange sets the range of the value.

func (*NumericOptionList) SetValueRef

func (o *NumericOptionList) SetValueRef(valueRef *[]int) *NumericOptionList

SetValueRef sets the reference to the values of the options. The values referenced by valueRef will be set automatically

func (*NumericOptionList) UpdateValueRef

func (o *NumericOptionList) UpdateValueRef()

Accept parses and accepts the value of the option list.

func (*NumericOptionList) Usage

func (o *NumericOptionList) Usage() string

func (*NumericOptionList) UsageDetails

func (o *NumericOptionList) UsageDetails(ap *ArgParser, arr *StringArray)

UsageDetails formats the usage details and stores them into the passed in string array.

func (*NumericOptionList) Values

func (o *NumericOptionList) Values() []int

Values returns the values of the options.

type Optional

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

Optional defines a triple states trigger.

func NewOptional

func NewOptional[T any]() *Optional[T]

NewOptional creates a new triple states trigger.

func (*Optional[T]) Nil

func (t *Optional[T]) Nil() bool

Nil returns true if the triple states has no value, or in the third state.

func (*Optional[T]) NotNil

func (t *Optional[T]) NotNil() bool

NotNil returns true if the triple states has value, either true or false.

func (*Optional[T]) SetNil

func (t *Optional[T]) SetNil()

SetNil sets the triple states to the third state, no value state.

func (*Optional[T]) SetValue

func (t *Optional[T]) SetValue(v T)

SetValue sets the value to true or false.

func (*Optional[T]) Value

func (t *Optional[T]) Value() T

Value returns the value if is not nil.

type PARSING_RESULT

type PARSING_RESULT int

PARSING_RESULT defines the parsing result during the parse process.

const (
	PR_CONTINUE              PARSING_RESULT = iota // the argument is parsed successfully, move to next.
	PR_EXPECT_VALUE                                // the argument expects more values.
	PR_EXPECT_VALUE_OPTIONAL                       // the argument expects additional optional values.
)

type Pool

type Pool[KeyT comparable, ValueT any] struct {
	// contains filtered or unexported fields
}

Pool is a thread-safe map that creates a new value for the pool if the key does not exist.

func NewPool

func NewPool[KeyT comparable, ValueT any](factory PoolFactory[KeyT, ValueT]) *Pool[KeyT, ValueT]

func (*Pool[KeyT, ValueT]) Clear

func (p *Pool[KeyT, ValueT]) Clear()

func (*Pool[KeyT, ValueT]) Clone

func (p *Pool[KeyT, ValueT]) Clone() *Pool[KeyT, ValueT]

func (*Pool[KeyT, ValueT]) Contains

func (p *Pool[KeyT, ValueT]) Contains(key KeyT) bool

func (*Pool[KeyT, ValueT]) Delete

func (p *Pool[KeyT, ValueT]) Delete(key KeyT)

func (*Pool[KeyT, ValueT]) ForEach

func (p *Pool[KeyT, ValueT]) ForEach(f func(key KeyT, value ValueT) bool)

func (*Pool[KeyT, ValueT]) Get

func (p *Pool[KeyT, ValueT]) Get(key KeyT) ValueT

func (*Pool[KeyT, ValueT]) Items

func (p *Pool[KeyT, ValueT]) Items() []struct {
	Key   KeyT
	Value ValueT
}

func (*Pool[KeyT, ValueT]) Keys

func (p *Pool[KeyT, ValueT]) Keys() []KeyT

func (*Pool[KeyT, ValueT]) Len

func (p *Pool[KeyT, ValueT]) Len() int

func (*Pool[KeyT, ValueT]) Map

func (p *Pool[KeyT, ValueT]) Map() map[KeyT]ValueT

func (*Pool[KeyT, ValueT]) Merge

func (p *Pool[KeyT, ValueT]) Merge(other *Pool[KeyT, ValueT])

func (*Pool[KeyT, ValueT]) Set

func (p *Pool[KeyT, ValueT]) Set(key KeyT, value ValueT)

func (*Pool[KeyT, ValueT]) String

func (p *Pool[KeyT, ValueT]) String() string

func (*Pool[KeyT, ValueT]) Values

func (p *Pool[KeyT, ValueT]) Values() []ValueT

type PoolFactory

type PoolFactory[KeyT comparable, ValueT any] func(key KeyT) ValueT

PoolFactory is a function that creates a new value for the pool.

type Positional

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

Positional represents a positional argument like: <file>

func NewPositional

func NewPositional(id int) *Positional

NewPositional creates a new positional argument with the given ID.

func (*Positional) Accept

func (o *Positional) Accept(value string) Result[PARSING_RESULT]

Accept parses and accepts the value of the positional.

func (*Positional) ID

func (o *Positional) ID() int

func (*Positional) Init

func (o *Positional) Init()

Init initializes the positional to reset the default value.

func (*Positional) Names

func (o *Positional) Names() []string

func (*Positional) SetUsage

func (o *Positional) SetUsage(usage string) *Positional

SetUsage sets the usage of the positional.

func (*Positional) SetValueName

func (o *Positional) SetValueName(valueName string) *Positional

SetValueName sets the name of the value.

func (*Positional) SetValueRef

func (o *Positional) SetValueRef(valueRef *string) *Positional

SetValueRef sets the reference to the value of the positional. The value referenced by valueRef will be set automatically

func (*Positional) UpdateValueRef

func (o *Positional) UpdateValueRef()

UpdateValueRef updates the value reference if the value reference is set.

func (*Positional) Usage

func (o *Positional) Usage() string

func (*Positional) UsageDetails

func (o *Positional) UsageDetails(_ *ArgParser, arr *StringArray)

UsageDetails formats the usage details and stores them into the passed in string array.

func (*Positional) Value

func (o *Positional) Value() string

Value returns the value of the positional.

type PositionalList

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

PositionalList represents a list of positional arguments like: <file> <file> ...

func NewPositionalList

func NewPositionalList(id int) *PositionalList

NewPositionalList creates a new positional list with the given ID.

func (*PositionalList) Accept

func (o *PositionalList) Accept(value string) Result[PARSING_RESULT]

Accept parses and accepts the value of the positional list.

func (*PositionalList) ID

func (o *PositionalList) ID() int

func (*PositionalList) Init

func (o *PositionalList) Init()

Init initializes the positional list to reset the default values.

func (*PositionalList) Names

func (o *PositionalList) Names() []string

func (*PositionalList) SetCount

func (o *PositionalList) SetCount(count int) *PositionalList

SetCount sets the count of the values.

func (*PositionalList) SetCountRange

func (o *PositionalList) SetCountRange(min, max int) *PositionalList

SetCountRange sets the range of the count of the values.

func (*PositionalList) SetUsage

func (o *PositionalList) SetUsage(usage string) *PositionalList

SetUsage sets the usage of the positional list.

func (*PositionalList) SetValueName

func (o *PositionalList) SetValueName(valueName string) *PositionalList

SetValueName sets the name of the value.

func (*PositionalList) SetValueRef

func (o *PositionalList) SetValueRef(valueRef *[]string) *PositionalList

SetValueRef sets the reference to the values of the positionals. The values referenced by valueRef will be set automatically

func (*PositionalList) UpdateValueRef

func (o *PositionalList) UpdateValueRef()

UpdateValueRef updates the value reference if the value reference is set.

func (*PositionalList) Usage

func (o *PositionalList) Usage() string

func (*PositionalList) UsageDetails

func (o *PositionalList) UsageDetails(_ *ArgParser, arr *StringArray)

UsageDetails formats the usage details and stores them into the passed in string array.

func (*PositionalList) Values

func (o *PositionalList) Values() []string

Values returns the values of the positionals.

type Result

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

func NewBooleanErrorResult

func NewBooleanErrorResult(err error) Result[bool]

func NewBooleanResult

func NewBooleanResult(result bool) Result[bool]

func NewEmptyResult

func NewEmptyResult[T any]() Result[T]

func NewErrorResult

func NewErrorResult[T any](err error, args ...any) Result[T]

func NewErrorResultFrom

func NewErrorResultFrom[T any, S any](another Result[S]) Result[T]

func NewParsingResult

func NewParsingResult(pr PARSING_RESULT) Result[PARSING_RESULT]

func NewRejectedParsingResult

func NewRejectedParsingResult(err error) Result[PARSING_RESULT]

func NewResult

func NewResult[T any](value T) Result[T]

func NewResultWithError

func NewResultWithError[T any](value T, err error, args ...any) Result[T]

func NewVoidErrorResult

func NewVoidErrorResult(err error) Result[bool]

func NewVoidResult

func NewVoidResult() Result[bool]

func (*Result[T]) Any

func (r *Result[T]) Any() any

func (*Result[T]) Error

func (r *Result[T]) Error() error

func (*Result[T]) Failed

func (r *Result[T]) Failed() bool

func (*Result[T]) IsEmpty

func (r *Result[T]) IsEmpty() bool

func (*Result[T]) RecoverWithValue

func (r *Result[T]) RecoverWithValue(value T)

func (*Result[T]) Success

func (r *Result[T]) Success() bool

func (*Result[T]) Value

func (r *Result[T]) Value() T

type SIMPLE_TOKEN

type SIMPLE_TOKEN int
const (
	STOK_UNDEFINED  SIMPLE_TOKEN = iota
	STOK_EOF                     // end of file/end of token stream
	STOK_IDENTIFIER              // identifier
	STOK_NUMBER                  // integer number constant
	STOK_STRING                  // string constant
	STOK_SPECIAL                 // special character
	STOK_CUSTOM                  // custom token
)

type SimpleReader

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

func NewSimpleReader

func NewSimpleReader(s string) *SimpleReader

func (*SimpleReader) Current

func (r *SimpleReader) Current() rune

func (*SimpleReader) Next

func (r *SimpleReader) Next() bool

func (*SimpleReader) Putback

func (r *SimpleReader) Putback() bool

func (*SimpleReader) ReadWhile

func (r *SimpleReader) ReadWhile(fn func(r rune) bool) string

type SimpleScanner

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

func NewSimpleScanner

func NewSimpleScanner(s string) *SimpleScanner

func (*SimpleScanner) NextToken

func (s *SimpleScanner) NextToken() *SimpleToken

func (*SimpleScanner) PeekChar

func (s *SimpleScanner) PeekChar() rune

func (*SimpleScanner) ReadChar

func (s *SimpleScanner) ReadChar() rune

func (*SimpleScanner) ReadUntil

func (s *SimpleScanner) ReadUntil(chars ...rune) *SimpleToken

type SimpleToken

type SimpleToken struct {
	Token   SIMPLE_TOKEN
	Literal string
}

func (*SimpleToken) IsCustom

func (t *SimpleToken) IsCustom() bool

func (*SimpleToken) IsEOF

func (t *SimpleToken) IsEOF() bool

func (*SimpleToken) IsIdentifier

func (t *SimpleToken) IsIdentifier() bool

func (*SimpleToken) IsNumber

func (t *SimpleToken) IsNumber() bool

func (*SimpleToken) IsSpecial

func (t *SimpleToken) IsSpecial(ch ...rune) bool

func (*SimpleToken) IsString

func (t *SimpleToken) IsString() bool

func (*SimpleToken) SetChar

func (t *SimpleToken) SetChar(token SIMPLE_TOKEN, ch rune) *SimpleToken

func (*SimpleToken) SetString

func (t *SimpleToken) SetString(token SIMPLE_TOKEN, literal string) *SimpleToken

type StatusResult

type StatusResult[S int, T any] struct {
	// contains filtered or unexported fields
}

func NewErrorStatusResult

func NewErrorStatusResult[S int, T any](err error) StatusResult[S, T]

func NewStatusResult

func NewStatusResult[S int, T any](status S, value T) StatusResult[S, T]

func (*StatusResult[S, T]) Any

func (r *StatusResult[S, T]) Any() any

func (*StatusResult[S, T]) Error

func (r *StatusResult[S, T]) Error() error

func (*StatusResult[S, T]) Failed

func (r *StatusResult[S, T]) Failed() bool

func (*StatusResult[S, T]) RecoverWithValue

func (r *StatusResult[S, T]) RecoverWithValue(status S, value T)

func (*StatusResult[S, T]) Status

func (r *StatusResult[S, T]) Status() S

interface IStatusResult

func (*StatusResult[S, T]) Success

func (r *StatusResult[S, T]) Success() bool

func (*StatusResult[S, T]) Value

func (r *StatusResult[S, T]) Value() T

interface IResult

type StringArray

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

func NewStringArray

func NewStringArray() *StringArray

func (*StringArray) Add

func (l *StringArray) Add(s string) *StringArray

func (*StringArray) AddIfNotEmptyf

func (l *StringArray) AddIfNotEmptyf(s string, args ...any) *StringArray

func (*StringArray) AddIfTrue

func (l *StringArray) AddIfTrue(c bool, s string, args ...any) *StringArray

func (*StringArray) Addf

func (l *StringArray) Addf(s string, args ...any) *StringArray

func (*StringArray) Clear

func (l *StringArray) Clear()

func (*StringArray) Join

func (l *StringArray) Join(sep string) string

func (*StringArray) Replace

func (l *StringArray) Replace(old string, new string) *StringArray

func (*StringArray) ToArray

func (l *StringArray) ToArray() []string

type StringBuilder

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

StringBuilder is a string builder which is enhanced from strings.Builder.

func NewStringBuilder

func NewStringBuilder() *StringBuilder

func NewStringBuilderWith

func NewStringBuilderWith(s string) *StringBuilder

func (*StringBuilder) String

func (builder *StringBuilder) String() string

func (*StringBuilder) Write

func (builder *StringBuilder) Write(s string, args ...any)

func (*StringBuilder) Writeln

func (builder *StringBuilder) Writeln(args ...string)

type Switch

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

Switch represents a switch argument like: --verbose, -v

func NewSwitch

func NewSwitch(id int, names ...string) *Switch

NewSwitch creates a new switch argument with the given ID and names.

func (*Switch) Accept

func (o *Switch) Accept(value string) Result[PARSING_RESULT]

Accept parses and accepts the value of the switch.

func (*Switch) ID

func (o *Switch) ID() int

func (*Switch) Init

func (o *Switch) Init()

Init initializes the switch to reset the default value.

func (*Switch) Names

func (o *Switch) Names() []string

func (*Switch) SetDefault

func (o *Switch) SetDefault(defaultValue bool) *Switch

SetDefault sets the default value of the switch.

func (*Switch) SetUsage

func (o *Switch) SetUsage(usage string) *Switch

SetUsage sets the usage of the switch.

func (*Switch) SetValueRef

func (o *Switch) SetValueRef(valueRef *bool) *Switch

SetValueRef sets the reference to the value of the switch. The value referenced by valueRef will be set automatically when the switch is parsed successfully.

func (*Switch) UpdateValueRef

func (o *Switch) UpdateValueRef()

UpdateValueRef updates the value reference if the value reference is set.

func (*Switch) Usage

func (o *Switch) Usage() string

func (*Switch) UsageDetails

func (o *Switch) UsageDetails(ap *ArgParser, arr *StringArray)

UsageDetails formats the usage details and stores them into the passed in string array.

func (*Switch) Value

func (o *Switch) Value() bool

Value returns the value of the switch.

type TextOption

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

TextOption defines a text argument

func NewTextOption

func NewTextOption(id int, names ...string) *TextOption

NewTextOption creates a new text option with the given ID and names.

func (*TextOption) Accept

func (o *TextOption) Accept(value string) Result[PARSING_RESULT]

Accept parses and accepts the value of the option.

func (*TextOption) ID

func (o *TextOption) ID() int

func (*TextOption) Init

func (o *TextOption) Init()

Init initializes the option to reset the default value.

func (*TextOption) Names

func (o *TextOption) Names() []string

func (*TextOption) SetDefaultValue

func (o *TextOption) SetDefaultValue(value string) *TextOption

SetDefaultValue sets the default value of the option.

func (*TextOption) SetUsage

func (o *TextOption) SetUsage(usage string) *TextOption

SetUsage sets the usage of the option.

func (*TextOption) SetValueName

func (o *TextOption) SetValueName(valueName string) *TextOption

SetValueName sets the name of the value.

func (*TextOption) SetValueRef

func (o *TextOption) SetValueRef(valueRef *string) *TextOption

SetValueRef sets the reference to the value of the option. The value referenced by valueRef will be set automatically

func (*TextOption) UpdateValueRef

func (o *TextOption) UpdateValueRef()

UpdateValueRef updates the value reference if the value reference is set.

func (*TextOption) Usage

func (o *TextOption) Usage() string

func (*TextOption) UsageDetails

func (o *TextOption) UsageDetails(ap *ArgParser, arr *StringArray)

UsageDetails formats the usage details and stores them into the passed in string array.

func (*TextOption) Value

func (o *TextOption) Value() string

Value returns the value of the option.

type TextOptionList

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

TextOptionList defines a list of text options

func NewTextOptionList

func NewTextOptionList(id int, names ...string) *TextOptionList

NewTextOptionList creates a new text option list with the given ID and names.

func (*TextOptionList) Accept

func (o *TextOptionList) Accept(value string) Result[PARSING_RESULT]

Accept parses and accepts the value of the option list.

func (*TextOptionList) ID

func (o *TextOptionList) ID() int

func (*TextOptionList) Init

func (o *TextOptionList) Init()

Init initializes the option list to reset the default values.

func (*TextOptionList) Names

func (o *TextOptionList) Names() []string

func (*TextOptionList) SetCount

func (o *TextOptionList) SetCount(count int) *TextOptionList

SetCount sets the count of the values.

func (*TextOptionList) SetCountRange

func (o *TextOptionList) SetCountRange(min, max int) *TextOptionList

SetCountRange sets the range of the count of the values.

func (*TextOptionList) SetUsage

func (o *TextOptionList) SetUsage(usage string) *TextOptionList

SetUsage sets the usage of the option list.

func (*TextOptionList) SetValueName

func (o *TextOptionList) SetValueName(valueName string) *TextOptionList

SetValueName sets the name of the value.

func (*TextOptionList) SetValueRef

func (o *TextOptionList) SetValueRef(valueRef *[]string) *TextOptionList

SetValueRef sets the reference to the values of the options. The values referenced by valueRef will be set automatically

func (*TextOptionList) UpdateValueRef

func (o *TextOptionList) UpdateValueRef()

UpdateValueRef updates the value reference if the value reference is set.

func (*TextOptionList) Usage

func (o *TextOptionList) Usage() string

func (*TextOptionList) UsageDetails

func (o *TextOptionList) UsageDetails(ap *ArgParser, arr *StringArray)

UsageDetails formats the usage details and stores them into the passed in string array.

func (*TextOptionList) Values

func (o *TextOptionList) Values() []string

Values returns the values of the options.

type UnpackFunc

type UnpackFunc[T any, V any] func(value V, result *error) T

UnpackFunc is the function type for unpacking the value to the target type. Where

  • T: the target type the function unpacks to;
  • V: the value type the function unpacks from.

type VALUE_TYPE

type VALUE_TYPE int

VALUE_TYPE defines the type of the value which could be converted and handled in the DataBag or DataList. Note, multiple VALUE_TYPE can be combined together. The special type VT_OPTIONAL is used to indicate that the value is optional, and thus it cannot be used alone.

const (
	VT_UNKNOWN  VALUE_TYPE = 0
	VT_BOOLEAN  VALUE_TYPE = 0x00000001
	VT_INTEGER  VALUE_TYPE = 0x00000002
	VT_FLOAT64  VALUE_TYPE = 0x00000004
	VT_FLOAT32  VALUE_TYPE = 0x00000008
	VT_STRING   VALUE_TYPE = 0x00000010
	VT_DATETIME VALUE_TYPE = 0x00000020
	VT_LIST     VALUE_TYPE = 0x01000000
	VT_BAG      VALUE_TYPE = 0x02000000
	VT_OPTIONAL VALUE_TYPE = 0x80000000 // special type to indicate that the value is optional
)

func GetType

func GetType(value any) VALUE_TYPE

func (VALUE_TYPE) IsOptional

func (t VALUE_TYPE) IsOptional() bool

func (VALUE_TYPE) String

func (t VALUE_TYPE) String() string

Jump to

Keyboard shortcuts

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