base

package module
v3.3.7 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2022 License: BSD-3-Clause Imports: 19 Imported by: 11

README

go-base

Documentation Go Report Card

Common Go utilities that are used across omegaUp's projects.

Documentation

Index

Constants

View Source
const (
	// Kibibyte is 1024 Bytes.
	Kibibyte = Byte(1024)

	// Mebibyte is 1024 Kibibytes.
	Mebibyte = Byte(1024) * Kibibyte

	// Gibibyte is 1024 Mebibytes.
	Gibibyte = Byte(1024) * Mebibyte

	// Tebibyte is 1024 Gibibytes.
	Tebibyte = Byte(1024) * Gibibyte
)

Variables

View Source
var (
	// ErrKeyNotFound will be returned from Get to indicate that the key was not
	// found to prevent returning a zero value.
	ErrKeyNotFound = errors.New("key not found")
)

Functions

func ErrorWithCategory

func ErrorWithCategory(category error, cause error) error

ErrorWithCategory is similar to errors.Wrap, but instead of creating a new error as the wrapping message, a sentinel error is provided as a category. This category can then be inspected with HasErrorCategory.

func FloatToRational

func FloatToRational(floatVal float64) *big.Rat

FloatToRational returns a rational that's within 1e-6 of the floating-point value.

func HasErrorCategory

func HasErrorCategory(err error, category error) bool

HasErrorCategory returns whether the provided error belongs to the provided category.

func Max added in v3.3.1

func Max[T constraints.Ordered](x, y T) T

Max returns the larger of x or y.

func Min added in v3.3.1

func Min[T constraints.Ordered](x, y T) T

Min returns the smaller of x or y.

func NopOpenedCallback

func NopOpenedCallback(*os.File, bool) error

NopOpenedCallback is an OpenedCallback that does nothing.

func ParseRational

func ParseRational(str string) (*big.Rat, error)

ParseRational returns a rational that's within 1e-6 of the floating-point value that has been serialized as a string.

func RationalDiv

func RationalDiv(num, denom *big.Rat) *big.Rat

RationalDiv implements division between two rationals.

func RationalToFloat

func RationalToFloat(val *big.Rat) float64

RationalToFloat returns the closest float value to the given big.Rat.

func UnwrapCauseFromErrorCategory

func UnwrapCauseFromErrorCategory(err error, category error) error

UnwrapCauseFromErrorCategory finds an error with the specified category in the chain and returns its Cause(). Returns nil if no such error was found.

Types

type Byte

type Byte int64

A Byte is a unit of digital information.

func (Byte) Bytes

func (b Byte) Bytes() int64

Bytes returns the Byte as an integer number of bytes.

func (Byte) Gibibytes

func (b Byte) Gibibytes() float64

Gibibytes returns the Byte as an floating point number of Gibibytes.

func (Byte) Kibibytes

func (b Byte) Kibibytes() float64

Kibibytes returns the Byte as an floating point number of Kibibytes.

func (Byte) MarshalJSON

func (b Byte) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface. The result is an integer number of bytes.

func (Byte) Mebibytes

func (b Byte) Mebibytes() float64

Mebibytes returns the Byte as an floating point number of Mebibytes.

func (Byte) Tebibytes

func (b Byte) Tebibytes() float64

Tebibytes returns the Byte as an floating point number of Tebibytes.

func (*Byte) UnmarshalJSON

func (b *Byte) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface. The result can be an integer number of bytes, or a quoted string that MarshalJSON() can understand.

type Duration

type Duration time.Duration

Duration is identical to time.Duration, except it can implements the json.Marshaler interface with time.Duration.String() and time.Duration.ParseDuration().

func (Duration) MarshalJSON

func (d Duration) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface. The duration is a quoted string in RFC 3339 format, with sub-second precision added if present.

func (Duration) Milliseconds

func (d Duration) Milliseconds() float64

Milliseconds returns the duration as a floating point number of milliseconds.

func (Duration) Seconds

func (d Duration) Seconds() float64

Seconds returns the duration as a floating point number of seconds.

func (Duration) String

func (d Duration) String() string

String returns a string representing the duration in the form "72h3m0.5s". Leading zero units are omitted. As a special case, durations less than one second format use a smaller unit (milli-, micro-, or nanoseconds) to ensure that the leading digit is non-zero. The zero duration formats as 0s.

func (*Duration) UnmarshalJSON

func (d *Duration) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface. The duration is expected to be a quoted string that time.ParseDuration() can understand.

type KeyedPool added in v3.3.6

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

KeyedPool is an implementation of a length-bounded set of objects, each of which is associated with a key. If the objects in the pool exceed the maximum length (with a default of 256), the least-recently-used item in the pool will be evicted. Two callbacks can be provided and will be invoked when a new object should atomically be created when calling Get() and a suitable object is not available, and when an object is evicted due to lack of space.

func NewKeyedPool added in v3.3.6

func NewKeyedPool[T any](options KeyedPoolOptions[T]) *KeyedPool[T]

NewKeyedPool creates a new object pool with the provided options.

func (*KeyedPool[T]) Clear added in v3.3.6

func (p *KeyedPool[T]) Clear()

Clear removes all stored items from the pool.

func (*KeyedPool[T]) Get added in v3.3.6

func (p *KeyedPool[T]) Get(key string) (T, error)

Get obtains one element from the pool. If it was already present, the element is removed from the pool and returned. Otherwise, a new one will be created. If the New callback function is missing, it will return ErrKeyNotFound.

func (*KeyedPool[T]) Len added in v3.3.6

func (p *KeyedPool[T]) Len() int

Len returns the number of elements in the pool.

func (*KeyedPool[T]) Put added in v3.3.6

func (p *KeyedPool[T]) Put(key string, value T)

Put inserts an element into the pool. This operation could cause the least-recently-used element to be evicted.

func (*KeyedPool[T]) Remove added in v3.3.6

func (p *KeyedPool[T]) Remove(key string)

Remove removes the objects associated with the provided key from the pool.

type KeyedPoolOptions added in v3.3.6

type KeyedPoolOptions[T any] struct {
	// MaxEntries is the maximum number of items in the pool before an item is
	// evicted. The default is 256 if unset.
	MaxEntries int

	// Shards is the number of shards the pool will be split into to diminish
	// lock contention. The default is 16 if unset.
	Shards int

	// New is a callback that will be invoked if Get() does not find a
	// previously-created object in the pool.
	New func(key string) (T, error)

	// OnEvicted is a callback that will be invoked when an object is evicted
	// from the pool.
	OnEvicted func(key string, value T)
}

KeyedPoolOptions are options that can be passed to NewKeyedPool to customize the pool limits and functionality.

type LRUCache

type LRUCache[T SizedEntry] struct {
	sync.Mutex
	// contains filtered or unexported fields
}

LRUCache handles a pool of sized resources. It has a fixed maximum size with a least-recently used eviction policy.

func NewLRUCache

func NewLRUCache[T SizedEntry](sizeLimit Byte) *LRUCache[T]

NewLRUCache returns an empty LRUCache with the provided size limit.

func (*LRUCache[T]) EntryCount

func (c *LRUCache[T]) EntryCount() int

EntryCount is the number of elements in the LRUCache.

func (*LRUCache[T]) EvictableSize

func (c *LRUCache[T]) EvictableSize() Byte

EvictableSize is the size in bytes of all elements that are being considered for eviction. This is, not currently being used.

func (*LRUCache[T]) Get

func (c *LRUCache[T]) Get(
	key string,
	factory SizedEntryFactory[T],
) (*SizedEntryRef[T], error)

Get atomically gets a previously-created entry if it was found in the cache, or a newly-created one otherwise. It is the caller's responsibility to call Put() with the returned SizedEntryRef method once it's no longer needed so that the underlying resource can be evicted from the cache, if needed.

func (*LRUCache[T]) OvercommittedSize

func (c *LRUCache[T]) OvercommittedSize() Byte

OvercommittedSize is the size in bytes that have been allocated above the LRUCache's size limit. This number can be non-zero when all the elements in the cache are currently being used and cannot yet be evicted.

func (*LRUCache[T]) Put

func (c *LRUCache[T]) Put(r *SizedEntryRef[T])

Put marks a SizedEntryRef as no longer being referred to, so that it can be considered for eviction.

func (*LRUCache[T]) Size

func (c *LRUCache[T]) Size() Byte

Size is the total size in bytes of all the elements in the LRUCache.

type Metrics

type Metrics interface {
	// GaugeAdd increments a gauge. A gauge is a metric that represents a single
	// numerical value that can arbitrarily go up and down.
	GaugeAdd(name string, value float64)

	// CounterAdd increments a counter. A counter is a metric that represents a
	// single numerical value that only ever goes up.
	CounterAdd(name string, value float64)

	// SummaryObserve adds an observation to a summary. A summary is an aggregate
	// metric that supports querying percentiles.
	SummaryObserve(name string, value float64)
}

Metrics is an interface that supports updating different kinds of metrics. All its functions are thread-safe.

type NoOpMetrics

type NoOpMetrics struct {
}

NoOpMetrics is an implementation of Metrics that does nothing.

func (*NoOpMetrics) CounterAdd

func (n *NoOpMetrics) CounterAdd(name string, value float64)

CounterAdd adds the specified value to a counter of the specified name. Value should be non-negative.

func (*NoOpMetrics) GaugeAdd

func (n *NoOpMetrics) GaugeAdd(name string, value float64)

GaugeAdd adds the specified value to a gauge of the specified name.

func (*NoOpMetrics) SummaryObserve

func (n *NoOpMetrics) SummaryObserve(name string, value float64)

SummaryObserve adds the specified value to a summary of the specified name.

type OpenedCallback

type OpenedCallback func(f *os.File, isEmpty bool) error

OpenedCallback allows the caller to specify an action to be performed when the file is opened and before it is available for writing.

type Rat added in v3.2.4

type Rat big.Rat

Rat is identical to big.Rat, except it can implements the json.Marshaler interface so that it can also accept integers.

func (*Rat) MarshalJSON added in v3.2.4

func (r *Rat) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface. If the rational is an integer and it fits on a IEEE 754 number, it will be marshaled as a JSON number. Otherwise it will be marshaled as a string.

func (*Rat) UnmarshalJSON added in v3.2.4

func (r *Rat) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface. If the rational is a number, it will be parsed as one. Otherwise, it will use big.Rat.UnmarshalText.

type RotatingFile

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

A RotatingFile is an io.WriteCloser that supports reopening through SIGHUP. It opens the underlying file in append-only mode. All operations are thread-safe.

func NewRotatingFile

func NewRotatingFile(path string, mode os.FileMode, callback OpenedCallback) (*RotatingFile, error)

NewRotatingFile opens path for writing in append-only mode and listens for SIGHUP so that it can reopen the file automatically.

func (*RotatingFile) Close

func (r *RotatingFile) Close() error

Close closes the underlying file and stops listening for SIGHUP.

func (*RotatingFile) Rotate

func (r *RotatingFile) Rotate() error

Rotate reopens the file and closes the previous one.

func (*RotatingFile) Write

func (r *RotatingFile) Write(b []byte) (int, error)

Write writes the bytes into the underlying file.

func (*RotatingFile) WriteString

func (r *RotatingFile) WriteString(s string) (int, error)

WriteString is like Write, but writes the contents of string s rather than a slice of bytes.

type SizedEntry

type SizedEntry interface {
	// Release will be called upon the entry being evicted from the cache.
	Release()

	// Size returns the number of bytes consumed by the entry.
	Size() Byte
}

A SizedEntry is an entry within the LRUCache that knows its own size.

type SizedEntryFactory

type SizedEntryFactory[T SizedEntry] func(key string) (T, error)

A SizedEntryFactory is a factory that can create a SizedEntry given its key name.

type SizedEntryRef

type SizedEntryRef[T SizedEntry] struct {
	Value T
	// contains filtered or unexported fields
}

A SizedEntryRef is a wrapper around a SizedEntry.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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