util

package
v0.0.0-...-d14a738 Latest Latest
Warning

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

Go to latest
Published: May 17, 2024 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package util provides utility functions and types

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BytesFromString

func BytesFromString(str MutableString) []byte

BytesFromString makes a []byte pointing to the contents of a string.

The string must come from StringFromBytes if the new []byte is to be modified, as normal Go strings have their data allocated in the immutable memory area and any write operation would trigger panics.

func CleanUTF8

func CleanUTF8(s []byte) []byte

func CollectFromChannel

func CollectFromChannel[T any](closedChan <-chan T) []T

CollectFromChannel collect remaining items from a CLOSED channel

func CopySlice

func CopySlice[T any](slice []T) []T

CopySlice copies the slice to a newly-allocated one

func DeepCopyString

func DeepCopyString(str string) string

DeepCopyString copies the given string to a newly-allocated one

Without references to the original backing bytes

func DeepCopyStringFromBytes

func DeepCopyStringFromBytes(str []byte) string

DeepCopyStringFromBytes copies the given []byte to a newly-allocated string

Without references to the original backing bytes

func DeepCopyStrings

func DeepCopyStrings(strList []string) []string

DeepCopyStrings copies the given string list including each of item to newly allocated fields

Without references to the original backing slices

func GetFDFromTCPConn

func GetFDFromTCPConn(conn *net.TCPConn) (uintptr, error)

GetFDFromTCPConn reads socket FD from the given connection

func GetFDFromTCPConnOrPanic

func GetFDFromTCPConnOrPanic(conn *net.TCPConn) uintptr

GetFDFromTCPConnOrPanic tries to get socket FD from the given connection or panic

The connection must have been established first

func GetYamlLocation

func GetYamlLocation(node *yaml.Node) string

GetYamlLocation fetches a descriptive location of YAML node

func IsNetworkClosed

func IsNetworkClosed(err error) bool

IsNetworkClosed checks if the given error tells closing of network connection

func IsNetworkError

func IsNetworkError(err error) bool

IsNetworkError checks whether the given error should be considered a network issue, as opposed to e.g. expired certificate or permission denied

DO NOT use net.Error directly, as we may need to check for other error types in future

func IsNetworkTimeout

func IsNetworkTimeout(err error) bool

IsNetworkTimeout checks if the given error is network timeout

func IsTestGenerationMode

func IsTestGenerationMode() bool

IsTestGenerationMode returns true if we're running in "go test -args gen" to generate expected test outputs

func ListFiles

func ListFiles(directoryOrFilePattern string) ([]string, error)

ListFiles lists non-dir files or first level files under the directories in the given path pattern

func MD5ToHexdigest

func MD5ToHexdigest(content string) string

MD5ToHexdigest computes MD5 for given string and returns hex

func MarshalYaml

func MarshalYaml(source interface{}) (string, error)

MarshalYaml marshals the given source to a YAML string

func MaxInt

func MaxInt(x int, y int) int

MaxInt returns the larger one of given integers

func MinInt

func MinInt(x int, y int) int

MinInt returns the smaller one of given integers

func NewYamlError

func NewYamlError(node *yaml.Node, message string) error

NewYamlError creates a new error with location information of YAML node

func OverwriteNTruncate

func OverwriteNTruncate(main []byte, start int, tail string) []byte

func ReadFileAt

func ReadFileAt(dir *os.File, filename string) ([]byte, error)

ReadFileAt reads full contents of a file in given directory

func SHA512ToHexdigest

func SHA512ToHexdigest(content string) string

SHA512ToHexdigest computes SHA512 for given string and returns hex

func Stack

func Stack() string

Stack returns current stack trace as string

func StatFileAt

func StatFileAt(dir *os.File, filename string) (unix.Stat_t, error)

StatFileAt queries the stat of an existing file in given directory

func TimeFromTimeval

func TimeFromTimeval(val syscall.Timeval) time.Time

TimeFromTimeval creates a Time structure from syscall.Timeval

func TimeToUnixFloat

func TimeToUnixFloat(tm time.Time) float64

TimeToUnixFloat creates Unix epoch seconds from a Time structure

func TrySetTCPReadBuffer

func TrySetTCPReadBuffer(conn *net.TCPConn, max int, min int) (int, error)

TrySetTCPReadBuffer attempts to set read buffer within the range given

func UnlinkFileAt

func UnlinkFileAt(dir *os.File, filename string) error

UnlinkFileAt unlinks an existing file in given directory

func UnmarshalYamlFile

func UnmarshalYamlFile(path string, output interface{}) error

UnmarshalYamlFile loads and unmarshals YAML from file to interface or pointer to struct

func UnmarshalYamlReader

func UnmarshalYamlReader(reader io.Reader, output interface{}) error

UnmarshalYamlReader loads and unmarshals YAML from IO reader to interface or pointer to struct

func UnmarshalYamlString

func UnmarshalYamlString(contents string, output interface{}) error

UnmarshalYamlString loads and unmarshals YAML in string to interface or pointer to struct

func WriteFileAt

func WriteFileAt(dir *os.File, filename string, data []byte, perm os.FileMode) error

WriteFileAt writes to a new file in given directory

Types

type BytesPoolBy2n

type BytesPoolBy2n []*sync.Pool

BytesPoolBy2n is a set of pools by size

BytesPoolBy2n[1] = pool of make([]byte, 2) BytesPoolBy2n[2] = pool of make([]byte, 4) BytesPoolBy2n[8] = pool of make([]byte, 256) ... Local-cache with buffers of recycled []byte has been tried and made minimal improvement

func NewBytesPoolBy2n

func NewBytesPoolBy2n() BytesPoolBy2n

NewBytesPoolBy2n creates a BytesPoolBy2n with all pools initialized

func (BytesPoolBy2n) Get

func (pools BytesPoolBy2n) Get(length int) *[]byte

Get fetches an empty byte array suitable for given length of data The array returned may be longer than the given length

func (BytesPoolBy2n) Put

func (pools BytesPoolBy2n) Put(buf *[]byte)

Put recycles the given byte array into pool The array specified must come from BytesPoolBy2n.Get()

type MutableString

type MutableString = string

MutableString is a string backed by raw []byte, instead of in the immutable memory area like normal Go strings.

Its contents may be changed. But we cannot create a new type or string functions wouldn't work with it.

func StringFromBytes

func StringFromBytes(buf []byte) MutableString

StringFromBytes makes a string backed by a specified []byte.

There is no copying and the resulting string shares the same []byte contents.

If data in the backing slice is changed, the string contents would reflect the changes (NOT normal Go string behavior).

DO NOT use this in tests.

type NetConnWrapper

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

NetConnWrapper wraps a connection with with timeouts updated infrequently in trade of accuracy The real timeouts could be anything from specified timeout values to double of them

func WrapNetConn

func WrapNetConn(conn net.Conn, readTimeout time.Duration, writeTimeout time.Duration) *NetConnWrapper

WrapNetConn creates a NetConnWrapper for given network connection

func (*NetConnWrapper) Read

func (cw *NetConnWrapper) Read(p []byte) (int, error)

func (*NetConnWrapper) ReadDeadline

func (cw *NetConnWrapper) ReadDeadline() time.Time

ReadDeadline returns the current read deadline

func (*NetConnWrapper) Write

func (cw *NetConnWrapper) Write(p []byte) (int, error)

func (*NetConnWrapper) WriteDeadline

func (cw *NetConnWrapper) WriteDeadline() time.Time

WriteDeadline returns the current write deadline

type RunOnce

type RunOnce func(beforeRunning func())

RunOnce is a function wrapper that calls the underlying function at most once

beforeRunning is invoked right before the underlying function is invoked and only if it's going to be invoked. It may be nil.

This can be used to protect e.g. resource closing or cleanup, which should be called exactly once

func NewRunOnce

func NewRunOnce(f func()) RunOnce

NewRunOnce creates a function that would call the given "f" at most once

type TrackedWaitGroup

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

func (*TrackedWaitGroup) Add

func (twg *TrackedWaitGroup) Add(delta int)

func (*TrackedWaitGroup) Done

func (twg *TrackedWaitGroup) Done()

func (*TrackedWaitGroup) Peek

func (twg *TrackedWaitGroup) Peek() int

func (*TrackedWaitGroup) Wait

func (twg *TrackedWaitGroup) Wait()

Directories

Path Synopsis
Package localcachedmap provides a map with thread-local caches (copy-on-reference)
Package localcachedmap provides a map with thread-local caches (copy-on-reference)
Package stringtemplate provides string expansion by pre-compiled templates, for example:
Package stringtemplate provides string expansion by pre-compiled templates, for example:
Package stringunescape provides Unescaper(s) for escaped strings
Package stringunescape provides Unescaper(s) for escaped strings

Jump to

Keyboard shortcuts

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