utils

package module
v0.0.0-...-d71eb57 Latest Latest
Warning

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

Go to latest
Published: Jan 19, 2024 License: MIT Imports: 18 Imported by: 1

README

Go Reference Report card

utils

Minimalist pure Golang optimized generic utilities for Cleverse projects.

Installation

go get github.com/Cleverse/go-utilities/utils

Documentation

Overview

nolint: wrapcheck

Package utils provides Minimalist and zero-dependency utility functions.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Add0xPrefix

func Add0xPrefix(input string) string

Add0xPrefix returns the input string with 0x prefix.

func ByteSize

func ByteSize(bytes uint64) string

ByteSize returns a human-readable byte string, eg. 10M, 12.5K.

func CopyBytes

func CopyBytes(b []byte) []byte

CopyBytes copies a slice to make it immutable

func CopyMapOfArray

func CopyMapOfArray[K comparable, V any](src map[K][]V) map[K][]V

CopyMapOfArray high performance copy map of array to new map of array with shared backing array. Reference: https://cs.opensource.google/go/go/+/master:src/net/http/header.go;l=94

func CopyString

func CopyString(s string) string

CopyString copies a string to make it immutable

func DecodeHex

func DecodeHex(str string) ([]byte, error)

DecodeHex decodes a hex string into a byte slice. str can be prefixed with 0x.

func Default

func Default[T comparable](value T, defaultValue T) (result T)

Default inspired by Nullish coalescing operator (??) in JavaScript https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing

func DefaultOptional

func DefaultOptional[T comparable](opt []T, defaultValue T) (result T)

DefaultOptional extract optional parameter from variadic function parameter. If parameter is not provided or zero value of type T, return defaultValue.

It's useful to reduce boilerplate code when implementing optional parameter. You won't need to check if parameter is provided or not.

func DerefPtr

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

DerefPtr dereferences ptr and returns the value it points to if no nil, or else returns def.

func DerefPtrOr

func DerefPtrOr[T any](ptr *T, def T) T

DerefPtrOr dereferences ptr and returns the value it points to if no nil, or else returns def.

func Empty

func Empty[T any]() T

Empty returns an empty value of the given type.

func EmptyableToPtr

func EmptyableToPtr[T any](x T) *T

EmptyableToPtr returns a pointer copy of value if it's nonzero. Otherwise, returns nil pointer.

func EqualPtr

func EqualPtr[T comparable](a, b *T) bool

Equal returns true if both arguments are nil or both arguments dereference to the same value.

func Flip0xPrefix

func Flip0xPrefix(input string) string

Flip0xPrefix returns the input string with 0x prefix if it doesn't have 0x prefix, otherwise returns the input string without 0x prefix.

func FromPtr

func FromPtr[T any](x *T) T

FromPtr alias of DerefPtr. returns the pointer value or empty.

func FromPtrOr

func FromPtrOr[T any](x *T, fallback T) T

FromPtrOr alias of DerefPtrOr. returns the pointer value or the fallback value.

func Has0xPrefix

func Has0xPrefix(input string) bool

Has0xPrefix checks if the input string has 0x prefix or not.

Returns `true“ if the input string has 0x prefix, otherwise `false`.

func IsHex

func IsHex(str string) bool

IsHex verifies whether a string can represent a valid hex-encoded or not.

func IsNil

func IsNil(i interface{}) bool

IsNil checks if the given interface value is literally nil.

func IsStruct

func IsStruct(s interface{}) bool

IsStruct returns true if the given variable is a struct or *struct.

func Match

func Match(pattern, value string) bool

Match matches patterns as gitignore pattern. Reference https://git-scm.com/docs/gitignore, https://gist.github.com/jstnlvns/ebaa046fae16543cc9efc7f24bcd0e31

func MatchTwoAsterisk

func MatchTwoAsterisk(pattern, value string) bool

func Merge

func Merge[T comparable](to, from T) T

Merge merges two structs with the same type. merge from -> to.

warning: this function will modify the first struct (to)

func Must

func Must[T any](data T, err any, messageArgs ...interface{}) T

Must is used to simplify error handling. It's helpful to wraps a call to a function returning a value and an error. and panics if err is error or false.

warning: this is not safe, use with caution!! (avoid to use it's in runtime)

func MustNotError

func MustNotError[T any](data T, err error) T

MustNotError is used to simplify error handling.

warning: this is not safe, use with caution!! (avoid to use it's in runtime)

func MustNotOK

func MustNotOK[T any](data T, ok bool) T

MustNotOK is used to simplify ok handling. for case ok should be false.

warning: this is not safe, use with caution!! (avoid to use it's in runtime)

func MustOK

func MustOK[T any](data T, ok bool) T

MustOK is used to simplify ok handling. for case ok should be true.

warning: this is not safe, use with caution!! (avoid to use it's in runtime)

func Optional

func Optional[T any](opt []T) (optional T, ok bool)

Optional extract optional parameter from variadic function parameter. If parameter is not provided, return zero value of type T and false. If parameter is provided, return parameter and true.

Example: func Get(key string, option ...Option) (string, error) { ... }

It's useful to reduce boilerplate code when implementing optional parameter. You won't need to check if parameter is provided or not.

func PrettyStruct

func PrettyStruct(s interface{}) string

PrettyStruct returns pretty json string of the given struct.

func PtrOf

func PtrOf[T any](v T) *T

PtrOf returns a pointer to the given value. alias of ToPtr.

func RandomBytes

func RandomBytes(length int) []byte

RandomBytes returns a random byte slice with the given length with crypto/rand.

func RandomHex

func RandomHex(length int) string

RandomHex returns a random hex string with the given length.

func RandomString

func RandomString(n int) string

func Sleep

func Sleep(ctx context.Context, d time.Duration) error

Sleep is a time.Sleep, but it can be interrupted by context. If interrupted, Sleep returns ctx.Err().

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

// do something every second until do something else finish.
go func() {
	for {
		doSomething()
		if err := Sleep(ctx, 1 * time.Second); err != nil {
			return // interrupted
		}
	}
}()

doSomethingElse()
cancel() // interrupt the goroutine

func StructHasZero

func StructHasZero(s any, includeNested ...bool) bool

StructHasZero returns true if a field in a struct is zero value(has not initialized) if includeNested is true, it will check nested struct (default is false)

func StructZeroFields

func StructZeroFields(s any, checkNested ...bool) []string

StructZeroFields returns name of fields if that's field in a struct is zero value(has not initialized) if checkNested is true, it will check nested struct (default is false)

func ToPtr

func ToPtr[T any](v T) *T

ToPtr returns a pointer to the given value.

func ToString

func ToString(arg interface{}, args ...any) string

ToString Change any supports types to string

func ToZero

func ToZero[T any](value T) (result T)

ToZero alias of Zero. returns zero value of the type of the given value.

func Trim0xPrefix

func Trim0xPrefix(input string) string

Trim0xPrefix returns the input string without 0x prefix.

func UnsafeBytes

func UnsafeBytes(s string) (bs []byte)

UnsafeBytes returns a byte pointer without allocation

func UnsafeMust

func UnsafeMust[T any, E any](data T, e E) T

UnsafeMust is used to simplify error/ok handling by ignoring it in runtime.

warning: this is not safe, use with caution!! be careful when value is pointer, it may be nil. (safe in runtime, but need to check nil before use)

func UnsafeString

func UnsafeString(b []byte) string

UnsafeString returns a string pointer without allocation

func Zero

func Zero[T any](value T) T

Zero returns zero value of the type of the given value.

Types

type FuncMap

type FuncMap map[string]interface{}

type Template

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

Template is a wrapper of text/template and html/template.

func NewTemplate

func NewTemplate(name string, tmpl string, config TemplateConfig) *Template

NewTemplate is a wrapper of text/template and html/template. used to define a template at initialization time without error checking.

Example:

package main

import "github.com/Cleverse/go-utilities/utils"

var HelloWorldTemplate = utils.NewTemplate("hello", "Hello {{.Name}}", utils.TemplateConfig{})

func main() { ... }

func (*Template) Execute

func (t *Template) Execute(wr io.Writer, args interface{}) error

Execute applies a parsed template to the specified data object and writes the output to wr.

func (*Template) ExecuteHTML

func (t *Template) ExecuteHTML(wr io.Writer, args interface{}) error

ExecuteHTML applies a parsed template to the specified data object and writes the output to wr.

func (*Template) HTML

func (t *Template) HTML(args interface{}) (string, error)

HTML applies a parsed template to the specified data object and returns the output as a string.

func (*Template) ParsedTemplate

func (t *Template) ParsedTemplate() (*texttemplate.Template, error)

func (*Template) ParsedTemplateHTML

func (t *Template) ParsedTemplateHTML() (*htmltemplate.Template, error)

func (*Template) String

func (t *Template) String() string

String returns the template string.

func (*Template) Text

func (t *Template) Text(args interface{}) (string, error)

Text applies the template to the given args and returns the result as a string.

type TemplateConfig

type TemplateConfig struct {
	Funcs  FuncMap
	Option []string
}

Jump to

Keyboard shortcuts

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