util

package
v0.9.9 Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// start at 1314000 (approx. 4 years in the future) to avoid complexities of
	// delta comparisons and to allow for date adjustments.
	RoundCountMinimum  = 1314000
	RoundCountFilename = `.roundcount`
)

Variables

This section is empty.

Functions

func AddMemoryReporter

func AddMemoryReporter(name string, reporter MemReport)

AddMemoryReporter registers a named memory reporter. Duplicate names are accepted but will appear as separate sections in the report.

func ApproximateMemoryUsage added in v0.9.8

func ApproximateMemoryUsage(i interface{}) uint64

ApproximateMemoryUsage returns a rough estimate of the memory occupied by i. It accounts for slice capacity, string backing arrays, interface values, and deduplicates shared pointer targets. Map internal bucket overhead is not counted. Returns 0 for nil.

func BoolYN

func BoolYN(b bool) string

func BreakIntoParts

func BreakIntoParts(full string) []string

func Compress

func Compress(input []byte) []byte

func ConvertColorShortTags

func ConvertColorShortTags(input string) string

func ConvertForFilename

func ConvertForFilename(input string) string

Make everything lowercase Convert anything that isn't a-z, 0-9 into _

func CopyoverContributor added in v0.9.8

func CopyoverContributor() copyover.Contributor

CopyoverContributor returns the util contributor for registration.

func Decode

func Decode(base64str string) []byte

func Decompress

func Decompress(input []byte) []byte

func Encode

func Encode(blobdata []byte) string

func FilePath

func FilePath(pathParts ...string) string

func FindMatchIn

func FindMatchIn(searchName string, items ...string) (match string, closeMatch string)

func FormatBytes

func FormatBytes(bytes uint64) string

FormatBytes formats a byte count as a human-readable string. Returns "0 B" for zero, otherwise scales to KB/MB/GB/TB/PB/EB.

func FormatDiceRoll

func FormatDiceRoll(attacks int, dCount int, dSides int, bonus int, buffOnCrit []int) string

func FormatNumber

func FormatNumber(n int) string

func GetLockSequence

func GetLockSequence(lockIdentifier string, difficulty int, seed string) string

func GetMatchNumber

func GetMatchNumber(input string) (string, int)

accepts an input and splits it along a # if any. By default returns the full string and 1 as the number.

func GetMemoryReport

func GetMemoryReport() (names []string, trackedResults []map[string]MemoryResult)

GetMemoryReport calls every registered reporter and returns the section names and their results. The two slices are parallel: names[i] corresponds to trackedResults[i].

func GetMyIP

func GetMyIP() string

func GetRoundCount

func GetRoundCount() uint64

func GetServerAddress

func GetServerAddress() string

func GetTurnCount

func GetTurnCount() uint64

func Hash

func Hash(input string) string

func HashBytes

func HashBytes(input []byte) string

func HealthClass

func HealthClass(health int, maxHealth int) string

func IncrementRoundCount

func IncrementRoundCount() uint64

func IncrementTurnCount

func IncrementTurnCount() uint64

func LoadRoundCount

func LoadRoundCount(fpath string) uint64

func LockMud

func LockMud()

Mutex lock intended for synchronizing at a high level between components that may asyncronously access game data

func LogRoll

func LogRoll(name string, rollResult int, targetNumber int)

func ManaClass

func ManaClass(mana int, maxMana int) string

func Md5

func Md5(input string) string

func Md5Bytes

func Md5Bytes(input []byte) []byte

func MemoryUsage

func MemoryUsage(i interface{}) uint64

MemoryUsage is an alias for ApproximateMemoryUsage retained for backwards compatibility with existing callers.

func ParseDiceRoll

func ParseDiceRoll(dRoll string) (attacks int, dCount int, dSides int, bonus int, buffOnCrit []int)

Gets the specifics of the item damage Format: 2@1d3+2#1,2,3

func PercentOfTotal

func PercentOfTotal(value1 int, value2 int) float64

func ProgressBar

func ProgressBar(complete float64, maxBarSize int, barParts ...string) (fullBar string, emptyBar string)

func QuantizeTens

func QuantizeTens(value int, max int) int

Creates a percentage and quantizes it to the nearest 10

func RLockMud

func RLockMud()

func RUnlockMud

func RUnlockMud()

func Rand

func Rand(maxInt int) int

func ReadFile added in v0.9.8

func ReadFile(path string) ([]byte, error)

func RollDice

func RollDice(dice int, sides int) int

Returns X dice rolled with Y sides

func SafeSave

func SafeSave(path string, data []byte) error

SafeSave first saves to a temp file, then renames it to save over the target destination This is to lessen the risk of a partial write being interrupted and corrupting the file due to power loss etc.

func Save

func Save(path string, data []byte, doSafe ...bool) error

Basic save wrapper

func SaveRoundCount

func SaveRoundCount(fpath string)

func ServerGetMemoryUsage

func ServerGetMemoryUsage() map[string]MemoryResult

ServerGetMemoryUsage reads runtime stats and returns them as a MemoryResult map. Entries whose Unit is UnitCount hold plain integer counts, not bytes.

func ServerStats

func ServerStats() string

ServerStats returns a formatted ANSI string summarising Go runtime memory and scheduler statistics. A single ReadMemStats call is shared with ServerGetMemoryUsage when both are needed; call ServerGetMemoryUsageFromStats directly to reuse an already-read MemStats value.

func SetRoundCount

func SetRoundCount(newRoundCount uint64)

func SetServerAddress

func SetServerAddress(addr string)

func SplitButRespectQuotes

func SplitButRespectQuotes(s string) []string

func SplitString

func SplitString(input string, lineWidth int) []string

func SplitStringNL

func SplitStringNL(input string, lineWidth int, nlPrefix ...string) string

Splits a string by adding line breaks at the end of each line

func StringWildcardMatch

func StringWildcardMatch(stringToSearch string, patternToSearch string) bool

func StripANSI

func StripANSI(str string) string

func StripCharsForScreenReaders

func StripCharsForScreenReaders(s string) string

func StripPrepositions

func StripPrepositions(input string) string

Strips out common prepositions from a string

func TrackTime

func TrackTime(name string, timePassed float64)

func UnlockMud

func UnlockMud()

func ValidateWorldFiles

func ValidateWorldFiles(exampleWorldPath string, worldPath string) error

func WriteFile added in v0.9.8

func WriteFile(path string, data []byte, perm os.FileMode) error

Types

type Accumulator

type Accumulator struct {
	Name    string
	Total   float64
	Lowest  float64
	Highest float64
	Count   float64
	Start   time.Time
}

func GetTimeTrackers

func GetTimeTrackers() []Accumulator

func (*Accumulator) Average

func (t *Accumulator) Average() float64

func (*Accumulator) Record

func (t *Accumulator) Record(nextValue float64)

func (*Accumulator) Stats

func (t *Accumulator) Stats() (lowest float64, highest float64, average float64, count float64)

type Hook added in v0.9.8

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

Hook is a generic, type-safe synchronous callback chain. Handlers registered against a Hook receive the current value, may modify it, and return the (possibly modified) value. All registered handlers are called in registration order. The final value is returned to the caller.

Hook is safe for concurrent registration and firing.

Example – defining a hook point in a package:

var OnRoomLook util.Hook[RoomTemplateDetails]

Example – registering a handler from a module:

rooms.OnRoomLook.Register(func(d rooms.RoomTemplateDetails) rooms.RoomTemplateDetails {
    d.Alert("You can fish here!")
    return d
})

Example – firing the hook at the call site:

details = rooms.OnRoomLook.Fire(details)

func (*Hook[T]) Fire added in v0.9.8

func (h *Hook[T]) Fire(data T) T

Fire calls each registered handler in order, passing the return value of each as the input to the next. Returns the final value. If no handlers are registered the original value is returned unchanged.

func (*Hook[T]) Register added in v0.9.8

func (h *Hook[T]) Register(fn func(T) T)

Register adds a handler to the hook. Handlers are called in the order they are registered.

type MemReport

type MemReport func() map[string]MemoryResult

type MemResultUnit added in v0.9.8

type MemResultUnit uint8

MemResultUnit describes what the Memory field of a MemoryResult holds so callers can format it correctly.

const (
	UnitBytes MemResultUnit = iota // Memory holds a byte count
	UnitCount                      // Memory holds a plain integer count (not bytes)
)

type MemoryResult

type MemoryResult struct {
	Memory uint64
	Count  int
	Unit   MemResultUnit
}

Jump to

Keyboard shortcuts

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