util

package
v0.0.0-rc2 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2024 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultSampleLen = 1000
)

Variables

View Source
var (
	WrappedKey = ContextKey("wrapped")
)

Functions

func AnnoDominiBeginning

func AnnoDominiBeginning(loc *time.Location) time.Time

AnnoDominiBeginning returns the first time instant of the AD (modern) epoch in the given location

func BackoffLogger

func BackoffLogger(logger log.Logger, msg string) func(error, time.Duration)

BackoffLogger uses level "warn" by default

func BackoffLoggerDebug

func BackoffLoggerDebug(logger log.Logger, msg string) func(error, time.Duration)

func BackoffLoggerWarn

func BackoffLoggerWarn(logger log.Logger, msg string) func(error, time.Duration)

func BeforeChristEnding

func BeforeChristEnding(loc *time.Location) time.Time

BeforeChristEnding returns the first time instant AFTER the end of the BC (pre-modern) epoch in the given location

func BoolPtr

func BoolPtr(res bool) *bool

func Coalesce

func Coalesce[Value any](pointer *Value, defaultValue Value) Value

func CoalesceError

func CoalesceError(err, defaultErr error) (result error)

func CoalesceZero

func CoalesceZero[Value comparable](value Value, defaultValue Value) Value

func ContextWithTimestamp

func ContextWithTimestamp(ctx context.Context, ts time.Time) context.Context

func DeepSizeof

func DeepSizeof(v interface{}) uint64

func DefaultSample

func DefaultSample(s string) string

func DelayFunc

func DelayFunc(fn func(), d time.Duration) *delayedFunc

DelayFunc delays the execution of the given func by the given duration. The execution can be cancelled.

func EnsureNoStringValsOnTheEdges

func EnsureNoStringValsOnTheEdges(s string) error

func ExtractStructFromScanResult

func ExtractStructFromScanResult(scanResult interface{}, structForExtracting interface{}) interface{}

func FalsePtr

func FalsePtr() *bool

func FieldsNumSerializedInYson

func FieldsNumSerializedInYson(currStruct interface{}) int

func ForEachErr

func ForEachErr[S ~[]T, T any](s S, fn func(T) error) error

ForEachErr is for calling function for each element of slice which may return error. All errors that occur during processing are stored in multi error object.

func FullSize

func FullSize(size []int) []int

func GetCurrentGoroutineCallstack

func GetCurrentGoroutineCallstack() string

func GetFreePort

func GetFreePort() (port int, resultError error)

GetFreePort returns free port in operating system that you can use for deploying your service

func GetMiniCallstack

func GetMiniCallstack(depth int) []string

func GetTimestampFromContext

func GetTimestampFromContext(ctx context.Context) (time.Time, error)

func GetTimestampFromContextOrNow

func GetTimestampFromContextOrNow(ctx context.Context) time.Time

func Hash

func Hash(content string) string

func HashSha256

func HashSha256(data []byte) string

func IsASCIIPrintable

func IsASCIIPrintable(s string) bool

IsASCIIPrintable - determines if this is string (safe to printing) or binary buffer taken from: https://stackoverflow.com/a/24677132

func IsFieldYsonKey

func IsFieldYsonKey(field reflect.StructField) bool

func IsOpen

func IsOpen(ch <-chan struct{}) bool

IsOpen Beware, this function consumes an item from the channel. Use only on channels without data, i.e. which are only closed but not written into.

func IsTwoStructTypesTheSame

func IsTwoStructTypesTheSame(a, b interface{}) bool

func JSONMarshalUnescape

func JSONMarshalUnescape(v any) ([]byte, error)

JSONMarshalUnescape writes the JSON encoding of v to the byte slice, does not make HTML Escape (like json.Marshal).

func Less

func Less(chain ...Comparable) bool

func LowerCamelCase

func LowerCamelCase(s string) string

LowerCamelCase converts a string into camel case starting with a lower case letter.

func MakeChanWithError

func MakeChanWithError(err error) chan error

MakeChanWithError constructs a buffered channel with capacity 1, writes the given error into it and returns the channel

func MakeUnitedStruct

func MakeUnitedStruct(copyVals bool, structs ...interface{}) interface{}

func MakeUnitedStructByKeyVal

func MakeUnitedStructByKeyVal(copyVals bool, key interface{}, value interface{}) interface{}

func MapErr

func MapErr[S ~[]T, T, M any](s S, fn func(T) (M, error)) ([]M, error)

MapErr is for applying mapping function to slice which may return error. All errors that occur during processing are stored in multi error object.

func MapFromJSON

func MapFromJSON(from interface{}, to interface{}) error

func MapKeysInOrder

func MapKeysInOrder[K constraints.Ordered, V any](m map[K]V) []K

MapKeysInOrder returns a sorted slice of all the keys in the given map

func MapProtoJSON

func MapProtoJSON(from proto.Message, to proto.Message) error

func NewIfNil

func NewIfNil[T any](ptr **T) *T

NewIfNil returns specified ptr, initializing it with new object if ptr is nil

func ParallelDo

func ParallelDo(ctx context.Context, count, parallelDegree int, executor func(i int) error) error

func ParallelDoWithContextAbort

func ParallelDoWithContextAbort(ctx context.Context, count, parallelDegree int, executor func(i int, ctx context.Context) error) error

func Prefix

func Prefix(s string, prefixLen int) string

func Receive

func Receive[T any](ctx context.Context, workCh <-chan T) (T, bool)

func Sample

func Sample(s string, maxSampleLen int) string

func SampleBytes

func SampleBytes(data []byte, maxSampleLen int) []byte

func SampleHex

func SampleHex(data []byte, maxSampleLen int) string

func Send

func Send[T any](ctx context.Context, workCh chan<- T, val T) bool

func SizeOfStruct

func SizeOfStruct(v interface{}) uint64

func Snakify

func Snakify(str string) string

func SplitStatements

func SplitStatements(s string) []string

func TailSample

func TailSample(s string, maxSampleLen int) string

func ToSnakeCase

func ToSnakeCase(str string) string

func ToString

func ToString(errors []error) string

ToString returns a string representation of errors. Any nil errors in the slice are skipped.

func TruePtr

func TruePtr() *bool

func Unwrap

func Unwrap(err error) error

func UpperCamelCase

func UpperCamelCase(s string) string

UpperCamelCase converts a string into camel case starting with a upper case letter.

func ValidateKey

func ValidateKey(in interface{}) error

func ValidateVal

func ValidateVal(in interface{}) error

func WrapErrCh

func WrapErrCh(headerErr error, errCh chan error) error

func XDIndex

func XDIndex(i int, fullSize []int) []int

Types

type ChannelReader

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

func NewChannelReader

func NewChannelReader() *ChannelReader

func (*ChannelReader) Close

func (r *ChannelReader) Close()

func (*ChannelReader) Input

func (r *ChannelReader) Input() chan<- []byte

func (*ChannelReader) Read

func (r *ChannelReader) Read(dst []byte) (int, error)

type Comparable

type Comparable interface {
	// Return:
	// * 0 if values inside Comparable are equal
	// * a negative value if the left one is less than the right one
	// * a positive value if the left one is more than the right one
	Compare() int
}

type Comparator

type Comparator[T constraints.Ordered] struct {
	// contains filtered or unexported fields
}

func NewComparator

func NewComparator[T constraints.Ordered](left, right T) *Comparator[T]

func (Comparator[T]) Compare

func (c Comparator[T]) Compare() int

type ContextKey

type ContextKey string

type Errors

type Errors []error

Errors is a slice of error.

func AppendErr

func AppendErr(errors []error, err error) Errors

AppendErr appends err to errors if it is not nil and returns the result. If err is nil, it is not appended.

func AppendErrs

func AppendErrs(errors []error, newErrs []error) Errors

AppendErrs appends newErrs to errors and returns the result. If newErrs is empty, nothing is appended.

func NewErrs

func NewErrs(err ...error) Errors

NewErrs returns a slice of error. Nil errors are thrown away If no errors are left in list, returns nil.

func PrefixErrors

func PrefixErrors(errs Errors, pfx string) Errors

PrefixErrors prefixes each error within the supplied Errors slice with the string pfx.

func UniqueErrors

func UniqueErrors(errs Errors) Errors

UniqueErrors returns the unique errors from the supplied Errors slice. Errors are considered equal if they have equal stringified values.

func (Errors) As

func (e Errors) As(target any) bool

func (Errors) Empty

func (e Errors) Empty() bool

func (Errors) Error

func (e Errors) Error() string

Error implements the error#Error method.

func (Errors) Is

func (e Errors) Is(err error) bool

func (Errors) String

func (e Errors) String() string

String implements the stringer#String method.

type HasherSha256

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

use hasher with once allocated slice [sha256.Size]byte for result instead of sha256.Sum256() function to avoid extra memory allocations

func NewHasherSha256

func NewHasherSha256() *HasherSha256

func (*HasherSha256) Sum

func (h *HasherSha256) Sum(data []byte) []byte

type LineSplitter

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

LineSplitter splits text, taking into account line breaks, and writes those entries into the given writer.

func NewLineSplitter

func NewLineSplitter(reader io.Reader, writer io.Writer) *LineSplitter

func NewLineSplitterSize

func NewLineSplitterSize(reader io.Reader, writer io.Writer, size int) *LineSplitter

func (*LineSplitter) ConsumeRow

func (s *LineSplitter) ConsumeRow() error

ConsumeRow reads one line from the input and writes it into the writer.

type Rollbacks

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

Rollbacks is cancellable caller of rollback functions. Not thread safe.

Use case scenario: transactional initialization

func NewResource() (*MyResource, err) {
   rollbacks := Rollbacks{}
   defer rollbacks.Do() // #1 defer call of rollbacks during initialization

   resource1, err := aquisiteResource1()
   rollbacks.add(func() {resource1.Close()} // #2 Closing resource is being put into rollbacks phase
   if err != nil {
      return nil, err // #3 on exit, all rollbacks functions are being called due to comment #1
   }
   resource2, err := aquisiteResource2()
   rollbacks.add(func() {resource1.Retain()} // #4
   if err != nil {
      return nil, err // #5 if error occured, both resources in #2 and #4 will be freed on deferred call in #1
   }

   rollbacks.Cancel() // #6 when we come to point where object with resources is correctly initialized, cancel rollbacks
   return &MyResource{ resource1, resource2}, nil // when deferred #1 called, no resource free happen due to comment #6
}

func (*Rollbacks) Add

func (r *Rollbacks) Add(f func())

func (*Rollbacks) AddCloser

func (r *Rollbacks) AddCloser(closer io.Closer, logger log.Logger, warningMessage string)

func (*Rollbacks) Cancel

func (r *Rollbacks) Cancel()

func (*Rollbacks) Do

func (r *Rollbacks) Do()

type SmartTimer

type SmartTimer struct {
	Duration time.Duration
	// contains filtered or unexported fields
}

SmartTimer is an object that can be waited on for time to pass.

  • Supports concurrent operations;
  • Properly works with zero and negative duration;

The timer has three states:

  • Fired: the initial state;
  • Paused: the timer is paused and is waiting for its start;
  • Ticking: the timer is ticking and will become fired when the interval set passes.

func NewSmartTimer

func NewSmartTimer(d time.Duration) *SmartTimer

NewSmartTimer constructs a timer with the given duration and puts it into "fired" state.

func (*SmartTimer) C

func (t *SmartTimer) C() <-chan time.Time

C returns a channel a read from which will return when the timer goes from "ticking" to "fired" state.

func (*SmartTimer) HasFired

func (t *SmartTimer) HasFired() bool

HasFired returns true if the timer is in "fired" state.

func (*SmartTimer) Pause

func (t *SmartTimer) Pause()

Pause moves the timer to "paused" state.

func (*SmartTimer) Restart

func (t *SmartTimer) Restart()

Restart starts the timer with the duration set in its constructor, moving it to "ticking" state. If the Duration is zero, moves the timer directly to "fired" state. If the timer is already in "ticking" state, the method restarts the timer.

type Values

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

func (Values) GetTS

func (v Values) GetTS() time.Time

type XDArray

type XDArray struct {
	Data []interface{}
}

XDArray Multidimensional array with arbitrary item type

func EmptyXDArray

func EmptyXDArray() *XDArray

func NewXDArray

func NewXDArray(size []int) (*XDArray, error)

func (*XDArray) Set

func (xda *XDArray) Set(index []int, value interface{}) error

Jump to

Keyboard shortcuts

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