zr

package module
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2022 License: MIT Imports: 24 Imported by: 5

README

[Zr] Zircon-Go Library

Go Report Card
Functions and classes to manipulate basic data types, unit test, etc.

This library module works on all build platforms. There are other related library packages, some of which may depend on a particular OS, mainly github.com/balacode/zr_win.

To Install:

Just run:

go get github.com/balacode/zr

Summary:

bool.go: functions to work with boolean values.

bytes.go: a class to handle a block of bytes, with methods to insert, read, delete, etc.

bytes_func.go: functions to manipulate byte slices.

calendar.go: a class to present multiple dates and values in a calendar grid format.

currency.go: a fast data type for working with currency values. It is an int64 adjusted to give 4 fixed decimal places.

dates.go: functions to work with dates

debug.go: functions to help debugging

go_lang.go: convert any value to its representation in Go Language syntax

int_tuple.go: type that provides an integer tuple (a struct made up of two integers)

logging.go: provides error/warning logging and related functions.

numbers.go: functions to convert numeric types, check if a string is numeric and format numbers.

reflect.go: various functions to work with reflection.

settings.go: a simple container and interface to read and write settings.

strings.go: various functions to work with strings, that are not found in the standard library, for example functions to replace words in strings and make multiple replacements simultaneously.

string_aligner.go: aligns strings in columns.

timer.go: a class to capture starting and ending times of multiple events and generate a report of total time spent at each stage.

unittest.go: various functions to help unit testing.

uuid.go: generate UUIDs with UUID() or check if a string is a valid UUID with IsUUID()

Documentation

Overview

Package zr implements the Zircon-Go library.

Index

Constants

View Source
const (
	// EFailedOperation _ _
	EFailedOperation = "failed operation"

	// EFailedParsing _ _
	EFailedParsing = "failed parsing"

	// EFailedReading _ _
	EFailedReading = "failed reading"

	// EFailedWriting _ _
	EFailedWriting = "failed writing"

	// EInvalid _ _
	EInvalid = "invalid"

	// EInvalidArg _ _
	EInvalidArg = "invalid argument"

	// EInvalidType _ _
	EInvalidType = "invalid type"

	// ENil _ _
	ENil = "value is nil"

	// ENilReceiver indicates a method call on a nil object.
	ENilReceiver = "nil receiver"

	// ENoDef _ _
	ENoDef = "not defined"

	// ENotFound _ _
	ENotFound = "not found"

	// ENotHandled _ _
	ENotHandled = "not handled"

	// EOverflow indicates an arithmetic overflow.
	EOverflow = "overflow"
)
View Source
const (
	// CurrencyIntLimit specifies the highest (and lowest
	// when negative) integer component that currency
	// can hold, about 922.33 trillion.
	// The exact number is 922(t)337(b)203(m)685,476.
	//
	// This limit exists because an int64, on which Currency is based, can hold
	// up to 9,223,372,036,854,775,807. Out of this 4 digits are used for the
	// decimal part, i.e. 922,337,203,685,477.5807. The limit is set to this
	// number minus 1, so that all decimals from .0000 to .9999. can be used.
	CurrencyIntLimit = 922337203685476

	// MinCurrencyI64 is the lowest internal value that Currency can hold.
	MinCurrencyI64 = -9223372036854769999

	// MaxCurrencyI64 is the highest internal value that Currency can hold.
	MaxCurrencyI64 = 9223372036854769999
)
View Source
const (
	// MaxInt _ _
	MaxInt = int(MaxUint >> 1)

	// MaxUint _ _
	MaxUint = ^uint(0)

	// MinInt _ _
	MinInt = -MaxInt - 1
)
View Source
const IgnoreCase = CaseMode(1)

IgnoreCase constant specifies that text comparisons should not be case sensitive.

View Source
const IgnoreWord = WordMode(1)

IgnoreWord constant specifies that string searches should not match distinct words.

View Source
const MatchCase = CaseMode(2)

MatchCase constant specifies that text comparisons should be case sensitive.

View Source
const MatchWord = WordMode(2)

MatchWord constant specifies that string searches should match distinct words.

View Source
const (
	// SPACES is a string of all white-space characters,
	// which includes spaces, tabs, and newline characters.
	SPACES = " \a\b\f\n\r\t\v"
)

Variables

View Source
var (
	// ISODateEx is a regular expression that matches
	// date strings in "YYYY-MM-DD" format.
	ISODateEx = regexp.MustCompile(`^\d\d\d\d-\d\d-\d\d$`)

	// ISODateTimeEx is a regular expression that matches
	// date and time strings in "YYYY-MM-DDThh:mm:ss"
	// format or "YYYY-MM-DD hh:mm:ss" format.
	ISODateTimeEx = regexp.MustCompile(
		`^\d\d\d\d-\d\d-\d\d[ T]\d\d:\d\d:\d\d$`)

	// ISODateTimeEx is a regular expression that matches
	// time strings in "hh:mm:ss" format.
	ISOTimeEx = regexp.MustCompile(`^\d\d:\d\d:\d\d$`)
)
View Source
var (
	// PL is fmt.Println() but is used only for debugging.
	PL = fmt.Println

	// VL is VerboseLog() but is used only for debugging.
	VL = VerboseLog

	// TabSpace specifies the string to use as a single tab
	// (used by GoStringEx() to indent code)
	TabSpace = "    "
)
View Source
var DateFormatsDMY = []struct {
	Pat string // regular expression pattern to match
	In  string // use this date format to parse inupt
	Out string // use this date format to output
}{
	{
		Pat: `^\d{4}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2}:\d{1,2}$`,
		In:  "2006-01-02 15:04:05",
		Out: "2/Jan/2006 03:04pm",
	},
	{
		Pat: `^\d{4}-\d{1,2}-\d{1,2}$`,
		In:  "2006-01-02",
		Out: "2/Jan/2006",
	},

} //                                                              DateFormatsDMY

DateFormatsDMY _ _

View Source
var DigitNamesEN = []string{
	"Zero", "One", "Two", "Three", "Four",
	"Five", "Six", "Seven", "Eight", "Nine",
}

DigitNamesEN are English names of decimal digits 0 to 9. These constants are mainly used by IntInWordsEN().

View Source
var MonthNamesEN = []string{
	"January", "February", "March", "April", "May", "June",
	"July", "August", "September", "October", "November", "December",

} //                                                                MonthNamesEN

MonthNamesEN is a string array of English month names.

View Source
var NumberEx = regexp.MustCompile(`^[-]?\d+[.]?\d*$`)

NumberEx is a regular expression that matches positive or negative decimal real numbers. A single '-' precedes negative numbers but '+' is not matched for positive numbers. A number can contain a single decimal point.

View Source
var TErrorCount int

TErrorCount records the number of logged errors when TBeginError() is called. This is then compared when TCheckError() gets called.

View Source
var TeensEN = []string{
	"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen",
	"Sixteen", "Seventeen", "Eighteen", "Nineteen",
}

TeensEN are English names of numbers from 11 to 19. These constants are mainly used by IntInWordsEN().

View Source
var TensEN = []string{
	"Ten", "Twenty", "Thirty", "Forty", "Fifty",
	"Sixty", "Seventy", "Eighty", "Ninety",
}

TensEN are English names of tens (10, 20,.. 90) These constants are mainly used by IntInWordsEN().

Functions

func After

func After(s string, find ...string) string

After returns the part of 's' immediately after the last 'find' string.

func AmountInWordsEN

func AmountInWordsEN(n Currency, fmt string) string

AmountInWordsEN returns the currency value as an English description in words This function is useful for showing amounts in invoices, etc.

Uses English language names, hence the 'EN' suffix.

fmt: a string specifying the currency format:

format_ = "<Large-Single>;<Large-Plural>;<S-Single>;<S-Plural>;<Only>"
Large-Single - Large Denomination, Singular. E.g. "Dollar"
Large-Plural - Large Denomination, Plural.   E.g. "Dollars"
S-Single     - Small Denomination, Singular. E.g. "Cent"
S-Plural     - Small Denomination, Plural.   E.g. "Cents"

All the format specifiers are optional but must follow in
the order specified. If a plural specifier is omitted, then
an "s" is added to the singular specifier for values greater
than 1. If the singular specifier is omitted, Then the
plural is used for all values (Used for some currencies).
If both specifiers are omitted for either denomination, the
denomination will not be returned. See the examples below.

Returns: The amount in words as a string, including the currency

and the word "Only". Uses proper capitalisation.

Example: PARAMETER RESULT

(11.02,";;Cent;Only")   "Two Cents Only"
(11.02,"Dollar;;Cent")  "Eleven Dollars and Two Cents"
(11.02,"Euro")          "Eleven Euros"
(11.02,"Pound;;;Pence") "Eleven Pounds and Two Pence"

func AppendRuneBytes

func AppendRuneBytes(dest *[]byte, r rune) int

AppendRuneBytes appends a rune to the specified buffer, encoded as UTF-8. Note that 'dest' is a pointer to a byte slice, to allow the slice to be updated. Returns the number of bytes used to encode the rune. If the rune is not valid, returns -1 and doesn't change 'dest'.

func AppendToTextFile

func AppendToTextFile(filename, text string)

AppendToTextFile appends 'text' to file named 'filename'.

func Assert

func Assert(expect bool) bool

Assert checks if the 'expect' condition is true. If the condition is false, it outputs an 'ASSERTION FAILED' message to the standard output, including the function, line number and list of functions on the call stack.

func Base64ErrorDetails

func Base64ErrorDetails(err error, data string)

Base64ErrorDetails _ _

func BlankZero

func BlankZero(s string) string

BlankZero returns a blank string when given a string containing only zeros, decimal points and white-spaces. Any string that doesn't contain '0' is returned unchanged.

func Bool

func Bool(value interface{}) bool

Bool converts any simple numeric type or string to bool.

  • Dereferences pointers to evaluate the pointed-to type.
  • Converts nil to false.
  • Converts all nonzero numbers to true and zeros to false.
  • Converts only strings that equal 'true', '1' or '-1' (case-insensitive) to true, all other strings to false.

Note: fmt.Stringer (or fmt.GoStringer) interfaces are not treated as strings to avoid bugs from implicit conversion. Use the String method.

func BoolE

func BoolE(value interface{}) (bool, error)

BoolE converts any simple numeric type or string to bool.

  • Dereferences pointers to evaluate the pointed-to type.
  • Converts nil to false.
  • Converts all nonzero numbers to true and zeros to false.
  • Converts only strings that equal 'true', '1' or '-1' (case-insensitive) to true, all other strings to false.

Note: fmt.Stringer (or fmt.GoStringer) interfaces are not treated as strings to avoid bugs from implicit conversion. Use the String method.

func ByteSizeString

func ByteSizeString(sizeInBytes int64, useSI bool) string

ByteSizeString returns a human-friendly byte count string. E.g. 1024 gives '1 KiB', 1048576 gives '1 MiB'. If you set 'useSI' to true, uses multiples of 1000 (SI units) instead of 1024 (binary units) and suffixes 'KB' instead of 'KiB', etc.

func CallerList

func CallerList() []string

CallerList returns a human-friendly list of strings showing the call stack with each calling method or function's name and line number.

The most immediate callers are listed first, followed by their callers, and so on. For brevity, 'runtime.*' and 'syscall.*' and other top-level callers are not included.

func Callers

func Callers(options ...interface{}) string

Callers returns a human-friendly string showing the call stack with each calling method or function's name and line number. The most immediate callers are shown first, followed by their callers, and so on. For brevity, 'runtime.*' and 'syscall.*' etc. top-level callers are not included.

func CamelCase

func CamelCase(s string) string

CamelCase converts an identifier from underscore naming convention to camel case naming convention: 'some_name' becomes 'someName'.

func ClearBytes

func ClearBytes(slice *[]byte)

ClearBytes removes all bytes from a byte slice, retaining its underlying array and its allocated capacity.

func CommaDelimit

func CommaDelimit(number string, decimalPlaces int) string

TODO: CommaDelimit should accept interface{} in number CommaDelimit delimits a numeric string with commas (grouped every three digits) and also sets the required number of decimal places. Numbers are not rounded, just cut at the required number of decimals.

func CompactSpaces

func CompactSpaces(s string) string

CompactSpaces reduces all multiple white-spaces in string to a single space, also converting newlines and tabs to space. E.g. "a\n b c" becomes "a b c".

func CompressBytes

func CompressBytes(data []byte) []byte

CompressBytes compresses an array of bytes returns the ZLIB-compressed bytes.

func ConsumeGB

func ConsumeGB(gigabytes float64)

ConsumeGB consumes, then releases a large amount of RAM for testing.

func ContainsI

func ContainsI(s, substr string) bool

ContainsI returns true if 's' contains 'substr', ignoring case. It always returns true if 'substr' is a blank string.

func ContainsWord

func ContainsWord(s, word string, caseMode CaseMode) bool

ContainsWord returns true if 's' contains 'word', provided 'word' is a distinct word in 's', that is, the characters before and after 'word' are not alphanumeric or underscores. It always returns true if 'word' is a blank string. Specify MatchCase or IgnoreCase to determine if the case should me matched or ignored.

func CountCRLF

func CountCRLF(s string) (count, countCR, countLF int)

CountCRLF returns the number of carriage returns and line feeds in the given string in 3 components: CR+LF count, CR count, LF count.

func D

func D(message string, args ...interface{})

D writes a formatted debug message and to the console. Same as fmt.Printf(), but appends a newline at the end.

func DC

func DC(message string, args ...interface{})

DC writes a formatted debug message and the call stack to the console.

func DL

func DL(message string, args ...interface{})

DL writes a formatted debug message to log file "<process>.log" in the program's current directory. The message is not output to the console.

func DLC

func DLC(message string, args ...interface{})

DLC writes a formatted debug message and the call stack to log file "<process>.log" in the program's current directory. The message is not output to the console.

func DV

func DV(label string, values ...interface{})

DV displays human-friendly values for debugging.

label: the value's label, you should usually specify

the name of a variable or some tag here.

values: one or more values you want to display.

func DateOf

func DateOf(value interface{}) time.Time

DateOf converts any string-like value to time.Time without returning an error if the conversion failed, in which case it logs an error and returns a zero-value time.Time.

If value is a zero-length string, returns a zero-value time.Time but does not log a warning.

It also accepts a time.Time as input.

In both cases the returned Time type will contain only the date part without the time or time zone components.

Note: fmt.Stringer (or fmt.GoStringer) interfaces are not treated as strings to avoid bugs from implicit conversion. Use the String method.

func DayMth

func DayMth(value interface{}) string

DayMth returns a day-and-month string of the format "d mmm" when given a time.Time value or a date string.

func DaysInMonth

func DaysInMonth(year int, month time.Month) int

DaysInMonth returns the number of days in the specified year and month. (If year is less than 1 or greater than 9999, returns 0)

func DebugMode

func DebugMode() bool

DebugMode _ _

func DebugString

func DebugString(value interface{}, optIndentAt ...int) string

DebugString takes any kind of value and returns a string. Calls itself when describing slices, etc.

func DescribeStruct

func DescribeStruct(structPtr interface{}) string

DescribeStruct _ _

func DisableErrors

func DisableErrors(optDisable ...bool)

DisableErrors _ _

func EnableErrors

func EnableErrors(optEnable ...bool)

EnableErrors _ _

func EqualStringSlices

func EqualStringSlices(a, b []string) bool

EqualStringSlices reports whether two string slices a and b are identical.

func Error

func Error(args ...interface{}) error

Error outputs an error message to the standard output and to a log file named "<process>.log" in the program's current directory, It also outputs the call stack (names and line numbers of callers.) Error has no effect if disableErrors flag is set to true. Returns an error value initialized with the message.

func FindChar

func FindChar(s string, ch byte, beginIndex int) int

FindChar _ _

func FindInSlice

func FindInSlice(s string, start, end int, substr string) int

FindInSlice _ _

func First

func First(s string, count int) string

First _ _

func Float64

func Float64(value interface{}) float64

Float64 converts any simple numeric type or string to float64.

  • Dereferences pointers to evaluate the pointed-to type.
  • Converts nil to 0.
  • Converts boolean true to 1, false to 0.
  • Converts numeric strings to float64.
  • Converts strings using strconv.ParseFloat(). If a string can't be converted, returns 0.

This function can be used in cases where a simple cast won't work, and to easily convert interface{} to a float64.

Note: fmt.Stringer (or fmt.GoStringer) interfaces are not treated as strings to avoid bugs from implicit conversion. Use the String method.

If the value can not be converted to float64, returns zero and an error. Float64 logs the error (when logging is active).

func Float64E

func Float64E(value interface{}) (float64, error)

Float64E converts any simple numeric type or string to float64.

  • Dereferences pointers to evaluate the pointed-to type.
  • Converts nil to 0.
  • Converts boolean true to 1, false to 0.
  • Converts numeric strings to float64.
  • Converts strings using strconv.ParseFloat(). If a string can't be converted, returns 0.

This function can be used in cases where a simple cast won't work, and to easily convert interface{} to a float64.

Note: fmt.Stringer (or fmt.GoStringer) interfaces are not treated as strings to avoid bugs from implicit conversion. Use the String method.

If the value can not be converted to float64, returns zero and an error. Float64E does not log the error.

func FoldXorBytes

func FoldXorBytes(ar []byte, returnLen int) []byte

FoldXorBytes creates a shorter byte array from a longer byte array by overwriting the shorter array's elements using a XOR operation. This function is mainly used to shorten long hashes to get a shorter ID (only where the full hash precision is not necessary).

func FormatDateEN

func FormatDateEN(format string, date time.Time) string

FormatDateEN formats date using the specified format. Uses English language names, hence the 'EN' suffix.

func FuncName

func FuncName(callDepth int) string

FuncName returns the function name of the caller.

func GetErrorCount

func GetErrorCount() int

GetErrorCount returns the number of errors that occurred.

func GetLastLogMessage

func GetLastLogMessage() string

GetLastLogMessage returns the last logged message. Log messages are commonly emitted by Error().

func GetPart

func GetPart(s, prefix, suffix string) string

GetPart returns the substring between 'prefix' and 'suffix'. When the prefix is blank, returns the part from the beginning of 's'. When the suffix is blank, returns the part up to the end of 's'. I.e. if prefix and suffix are both blank, returns 's'. When either prefix or suffix is not found, returns a zero-length string.

func GetShowSourceFileNames

func GetShowSourceFileNames() bool

GetShowSourceFileNames _ _

func GetStructInt

func GetStructInt(structPtr interface{}, field string) (int, bool)

GetStructInt returns the string value from the named field in a struct. If the field is not found, returns ("", false).

func GetStructString

func GetStructString(structPtr interface{}, field string) (string, bool)

GetStructString returns the string value from the named field in a struct. If the field is not found, returns ("", false).

func GetStructType

func GetStructType(structPtr interface{}) (reflect.Type, bool)

GetStructType gets the reflection type of a pointer to a struct, or returns (nil, false) if it does not point to a struct.

func GetVerboseMode

func GetVerboseMode() bool

GetVerboseMode _ _

func GoName

func GoName(s string) string

GoName converts a name to a Go language convention name. It removes underscores from names and changes names to 'TitleCase'.

func GoString

func GoString(value interface{}, optIndentAt ...int) string

GoString converts fundamental types to strings in Go Language syntax. You can copy its output and paste in source code if needed.

If the type of value implements fmt.GoStringer or zr.GoStringerEx interfaces, uses the method provided by the interface.

optIndentAt: omit this optional argument to place all output

on one line, or specify 0 or more tab positions
to indent the output on multiple lines.

func HasFlags

func HasFlags(flags ...string) bool

HasFlags returns true if the command line used to start the program contains any of the specified flags. A flag must start with one or more '-' characters. The comparison is case-sensitive.

func HexStringOfBytes

func HexStringOfBytes(ar []byte) string

HexStringOfBytes converts a byte array to a string of hexadecimal digits.

func IMPLEMENT

func IMPLEMENT(args ...interface{})

IMPLEMENT reports a call to an unimplemented function or method at runtime, by printing the name of the function and the function that called it.

IMPLEMENT() should be placed on the first line of a function.

You can specify additional arguments to print with Println(). There is no need to specify the name of the unimplemented function as it is automatically read from the call stack.

func IfString

func IfString(condition bool, trueStr, falseStr string) string

IfString is a conditional IF expression: If 'condition' is true, returns string 'trueStr', otherwise returns string 'falseStr'. Not to be confused with IfStr() function, which uses Str objects.

func IndexOfString

func IndexOfString(s string, ar []string) int

IndexOfString returns the index of string [s] in string slice [ar].

func IndexSliceStructValue

func IndexSliceStructValue(
	input interface{},
	fieldName string,
	checker func(value interface{}) bool,
) (int, error)

IndexSliceStructValue _ _

func InsertBytes

func InsertBytes(dest *[]byte, pos int, src ...[]byte)

InsertBytes inserts a copy of a byte slice into another byte slice.

func Int

func Int(value interface{}) int

Int converts any simple numeric type or string to int.

  • Dereferences pointers to evaluate the pointed-to type.
  • Converts nil to 0.
  • Converts boolean true to 1, false to 0.
  • Converts numeric strings to int. Parsing a string continues until the first non-numeric character. Therefore a string like '123AA456' converts to '123'.

This function can be used in cases where a simple cast won't work, and to easily convert interface{} to an int.

Note: fmt.Stringer (or fmt.GoStringer) interfaces are not treated as strings to avoid bugs from implicit conversion. Use the String method.

If the value can not be converted to int, returns zero and logs an error (when logging is active).

func IntE

func IntE(value interface{}) (int, error)

IntE converts any simple numeric type or string to int.

  • Dereferences pointers to evaluate the pointed-to type.
  • Converts nil to 0.
  • Converts boolean true to 1, false to 0.
  • Converts numeric strings to int. Parsing a string continues until the first non-numeric character. Therefore a string like '123AA456' converts to '123'. while a non-numeric string converts to 0.

This function can be used in cases where a simple cast won't work, and to easily convert interface{} to an int.

Note: fmt.Stringer (or fmt.GoStringer) interfaces are not treated as strings to avoid bugs from implicit conversion. Use the String method.

If the value can not be converted to int, returns zero and an error. IntE does not log the error.

func IntInWordsEN

func IntInWordsEN(number int64) string

IntInWordsEN returns the given number as a description in words. Uses English language names, hence the 'EN' suffix. This function is useful for showing amounts in invoices, etc. 'number' must be a positive integer in the range of 0 to 1 trillion. E.g. IntInWordsEN(256) returns "Two Hundred and Fifty Six"

func IsBool

func IsBool(value interface{}) bool

IsBool returns true if value can be converted to a boolean.

If value is any numeric type or bool, returns true. If value is nil, returns false. If value is a string, returns true if it is "TRUE", "FALSE", "0", or "1". If value is any other type, returns false.

Note: fmt.Stringer (or fmt.GoStringer) interfaces are not treated as strings to avoid bugs from implicit conversion. Use the String method.

func IsDate

func IsDate(value interface{}) bool

IsDate returns true if the specified value can be converted to a date.

Note: fmt.Stringer (or fmt.GoStringer) interfaces are not treated as strings to avoid bugs from implicit conversion. Use the String method.

func IsDateOnly

func IsDateOnly(tm time.Time) bool

IsDateOnly returns true if 'tm' does not have a time portion, I.e. the hour, minute, second and nanosecond are all zero

func IsIdentifier

func IsIdentifier(s string) bool

IsIdentifier checks if 's' contains only letters, numbers or underscores.

func IsNumber

func IsNumber(value interface{}) bool

IsNumber returns true if value is a number or numeric string, or false otherwise. It also accepts pointers to numeric types and strings. Always returns false if value is nil or bool, even though Int() can convert bool to 1 or 0.

func IsUUID

func IsUUID(value interface{}) bool

IsUUID returns true if the given string is a well-formed UUID string. It accepts both the standard UUID with '-' and the shortened 32-character UUID. If the type of value is not a string or *string, returns false.

Note: fmt.Stringer (or fmt.GoStringer) interfaces are not treated as strings to avoid bugs from implicit conversion. Use the String method.

func IsWhiteSpace

func IsWhiteSpace(s string) bool

IsWhiteSpace returns true if all the characters in a string are white-spaces.

func JSUnescape

func JSUnescape(s string) string

JSUnescape unescapes a string escaped with the JavaScript escape() function (which is deprecated). In such escaped strings: % is followed by a 2-digit hex value. e.g. escaped string "%25" becomes "%", "%20" becomes " ", etc.

func JSUnescapeStruct

func JSUnescapeStruct(structPtr interface{})

JSUnescapeStruct unescapes all the strings in a struct that have been escaped with the JavaScript escape() function (which is deprecated). In such escaped strings: % is followed by a 2-digit hex value. e.g. escaped string "%25" becomes "%", "%20" becomes " ", etc.

func Last

func Last(s string, count int) string

Last _ _

func LineBeginIndex

func LineBeginIndex(s string, index int) int

LineBeginIndex _ _

func LineBeginIndexB

func LineBeginIndexB(s []byte, index int) int

LineBeginIndexB _ _

func LineEndIndex

func LineEndIndex(s string, index int) int

LineEndIndex _ _

func LineEndIndexB

func LineEndIndexB(s []byte, index int) int

LineEndIndexB _ _

func LineNo

func LineNo(callDepth int) int

LineNo returns the line number of the caller.

func LineOfIndex

func LineOfIndex(s string, index int) string

LineOfIndex _ _

func LineOffsetUTF8

func LineOffsetUTF8(data []byte, lineIndex int) (byteOffset, charOffset int)

LineOffsetUTF8 returns the byte and character offsets of the beginning of a line specified by 'lineIndex', within a UTF8-encoded slice of bytes ('data').

func Log

func Log(args ...interface{})

Log outputs a message string to the standard output and to a log file named "<process>.log" in the program's current directory. It also outputs the call stack (names and line numbers of callers.)

func Logf

func Logf(format string, args ...interface{})

Logf outputs a formatted message to the standard output and to a log file named "<process>.log" in the program's current directory. The 'format' parameter accepts a format string, followed by one or more optional arguments, exactly like fmt.Printf() and fmt.Errorf() It also outputs the call stack (names and line numbers of callers.)

func MaxIntOf

func MaxIntOf(values []int) (max int, found bool)

MaxIntOf returns the maximum value in a slice of integers (and true in the second returned value) or 0 and false if the slice is empty.

func MinMaxGap

func MinMaxGap(values []int) (min, max int)

MinMaxGap returns the lowest and highest unique integer that can fit in a gap in a series of integers. E.g. given 1, 4, and 7 this would be 2 and 6. Returns the resulting integers if there is a gap, or MaxInt and MinInt if there is no gap in the series.

func MonthNameEN

func MonthNameEN(monthNo int, shortName ...bool) string

MonthNameEN returns the English month name given a month number. E.g. "January", "February", etc. Uses English language names, hence the 'EN' suffix.

func MonthNumberEN

func MonthNumberEN(monthName string) int

MonthNumberEN returns a month number from 1 to 12, given an English month name. Accepts either a full month name like 'December', or a 3-character string like 'Dec'. The case is not important. If the string is not a month name, returns zero. Uses English language names, hence the 'EN' suffix.

func MthYear

func MthYear(value interface{}) string

MthYear returns a date string of the format "Mmm yyyy" when given a time.Time value or a date string.

func NoE

func NoE(any interface{}, err error) interface{}

NoE strips the error result from a function returning a value and an error. Cast the result to the correct type. For example: Eg. data := NoE(os.ReadFile(sourceFile)).([]byte)

func OBSOLETE

func OBSOLETE(args ...interface{})

OBSOLETE reports a call to an obsolete function or method at runtime, by printing the name of the function and the function that called it. The output is done using Println().

You can rename obsolete functions by adding an 'OLD' suffix to obsolete names. When one *OLD function calls another *OLD function, OBSOLETE won't report further obsolete calls to reduce message clutter.

OBSOLETE() should be placed on the first line of a function.

You can specify additional arguments to print with Println(). There is no need to specify the name of the obsolete function as it is automatically read from the call stack.

func Padf

func Padf(minLength int, format string, args ...interface{}) string

Padf suffixes a string with spaces to make sure it is at least 'minLength' characters wide. I.e. the string is left-aligned. If the string is wider than 'minLength', returns the string as it is.

func ParseDate

func ParseDate(s string) (year, month, day int)

ParseDate reads a date string and returns the year, month and day number.

func PrintfAsync

func PrintfAsync(format string, args ...interface{})

PrintfAsync prints output to the standard output like fmt.Printf(), but asynchronously using the log loop goroutine. This prevents the program from being slowed down by output to console. (This slow-down may occur on Windows)

func RandomBytes

func RandomBytes(length int) []byte

RandomBytes generates and returns a random slice of bytes

func RemoveBytes

func RemoveBytes(dest *[]byte, pos, count int)

RemoveBytes removes the specified number of bytes from a byte slice.

func ReplaceEx1

func ReplaceEx1(s, find, repl string, count int, caseMode CaseMode) string

ReplaceEx1 _ _ Specify MatchCase or IgnoreCase for case mode.

func ReplaceI

func ReplaceI(s, find, repl string, optCount ...int) string

ReplaceI replaces 'find' with 'repl' ignoring case.

func ReplaceMany

func ReplaceMany(
	s string,
	finds []string,
	repls []string,
	count int,
	caseMode CaseMode,
	wordMode WordMode,
) string

ReplaceMany makes multiple string replacements in a single pass. Replacing is prioritized, with longest strings among 'finds' replaced first before shorter strings.

With this function you can exchange or transpose values, which simple replace() functions can not do without making temporary replacements.

It is much faster to call ReplaceMany() with a batch of different replacements (even thousands of items), than to call a simple replace() function repeatedly. However if you only need to replace one string, then standard strings.Replace() or zr.ReplaceWord() and similar functions run faster when making an isolated replacement.

Internally, ReplaceMany() works with Unicode characters, therefore 's', 'finds' and 'repls' can be ANSI or UTF-8 encoded strings.

Parameters:

s: the string being replaced.

finds: a list of strings to find. each item will be replaced

with the matching item in repls, so the length of
'finds' and 'repls' must be the same.

repls: a list of replacement strings.

count: maximum number of replacements to make, or -1 for unlimited.

caseMode: use MatchCase for case-sensitive search string matching

or IgnoreCase for case-insensitive search string matching.

wordMode: use MatchWord to match whole words only, or IgnoreWord to

replace everything. Distinct words are comprised of letters,
numbers and underscores.

func ReplaceWord

func ReplaceWord(s, find, repl string, caseMode CaseMode) string

ReplaceWord replaces a word in a string. _ _ Specify MatchCase or IgnoreCase for case mode.

Examples:

ReplaceWord("ab b c", "b", "z", MatchCase)   // returns "ab z c"
ReplaceWord("ab b c", "B", "Z", IgnoreCase)  // returns "ab Z c"

func RuneOffset

func RuneOffset(slice []byte, runeIndex int) (byteIndex int)

RuneOffset reads a byte slice and returns the byte position of the rune at runeIndex, or -1 if the index is out of range.

func RunningLogFilename

func RunningLogFilename() string

RunningLogFilename returns the name of the log file used by the current process

func SetDebugMode

func SetDebugMode(val bool)

SetDebugMode _ _

func SetPart

func SetPart(s, prefix, suffix, part string) string

SetPart __ // TODO: describe and create unit test

func SetShowSourceFileNames

func SetShowSourceFileNames(val bool)

SetShowSourceFileNames _ _

func SetSlice

func SetSlice(s string, start, end int, substr string) string

SetSlice _ _

func SetStructInt

func SetStructInt(structPtr interface{}, field string, val int) bool

SetStructInt _ _

func SetStructString

func SetStructString(structPtr interface{}, field, val string) bool

SetStructString _ _

func SetVerboseMode

func SetVerboseMode(val bool)

SetVerboseMode _ _

func ShowSpaces

func ShowSpaces(s string) string

ShowSpaces replaces spaces, tabs and line breaks with visible placeholders.

func SkipChars

func SkipChars(s string, start int, chars string) int

SkipChars _ _

func SkipName

func SkipName(s string, start int) int

SkipName _ _

func SkipSpaces

func SkipSpaces(s string, start int) int

SkipSpaces _ _

func Slice

func Slice(s string, beginIndex, endIndex int) string

Slice returns a substring starting from 'beginIndex' and ending just before, but not including 'endIndex'.

beginIndex is the starting position. Must not be less than zero in which the function treats it as zero and logs an error.

endIndex is the ending position, just after the last required element. If endIndex is -1, returns everything from beginIndex up to the end.

func SplitQuoted

func SplitQuoted(s string) []string

SplitQuoted splits s into an array of strings, using spaces as delimiters, but leaving the spaces within quoted substrings. E.g. given "'a b c' 123", returns ["A B C", 123]. Works with single quotes ('), double quotes (") and back quotes (`). A substring that is started with one type of quote can contain quotes of other types, which are treated as normal characters until the substring is closed.

func StrOneOf

func StrOneOf(s string, matches ...string) bool

StrOneOf returns true if the first string 's' matches any one of the strings that follow, or false otherwise. For example: StrOneOf("b", "a", "b", "c") returns true StrOneOf("d", "a", "b", "c") returns false

func String

func String(value interface{}) string

String converts value to a string.

If the value can not be converted to a string, returns a zero length string and logs an error (when logging is active).

func StringDateDMY

func StringDateDMY(s string) string

StringDateDMY returns a short date using the "dd/mmm/yyyy" format. given an ISO-8601 formatted date string. E.g. given "2017-04-18" it returns "18/Apr/2017".

func StringDateYMD

func StringDateYMD(s string) string

StringDateYMD returns a short date using the "yyyy-mm-dd" format.

func StringE

func StringE(value interface{}) (string, error)

StringE converts value to a string, and also returns an error (or nil).

If the value can not be converted to a string, returns a zero length string and an error. StringE does not log the error.

func StringYear

func StringYear(value interface{}) string

StringYear _ _

func Substr

func Substr(s string, charIndex, charCount int) string

Substr returns a substring given a string and the index (charIndex) and substring length (charCount). If the length is -1, returns a string of all characters starting from the given index.

func TArrayEqual

func TArrayEqual(t *testing.T, expect, value interface{}) bool

TArrayEqual checks if two arrays are equal

func TBegin

func TBegin(t *testing.T)

TBegin prints a heading with the name of the tested module.

func TBeginError

func TBeginError()

TBeginError begins a check for an error condition.

func TBytesEqual

func TBytesEqual(t *testing.T, a, b []byte)

TBytesEqual checks if two byte slices have the same length and content

func TCaller

func TCaller() string

TCaller returns the name of the unit test function.

func TCheckError

func TCheckError(t *testing.T, expectMessages ...string)

TCheckError finishes a check for an error. Between calls to TBeginError() and TCheckError() there should be one error (logged with Error()). If not, call TFail() to trigger t.Error() because the test has failed.

Place calls to TBeginError() and TCheckError() within your unit tests. For example:

func TestMyFunc(t *testing.T) {
    TBeginError()  // <- begin check for error
    MyFunc(-1)     // <- calling this function with -1 should log an error
    TCheckError(t) // <- finish check (if no error, call t.Error()
}

func TEqual

func TEqual(t *testing.T, result interface{}, expect interface{}) bool

TEqual asserts that result is equal to expect.

func TFail

func TFail(t *testing.T, a ...interface{})

TFail _ _

func TFailf

func TFailf(t *testing.T, format string, a ...interface{})

TFailf _ _

func TFalse

func TFalse(t *testing.T, result bool) bool

TFalse asserts that the result value is false. If the assertion fails, invokes t.Error() to fail the unit test. Returns true if the assertion passed, or false if it failed.

func TM

func TM(messages ...string)

TM outputs milliseconds elapsed between calls to TM() to standard output. To start timing, call TM() without any arguments.

func TTrue

func TTrue(t *testing.T, result bool) bool

TTrue asserts that the result value is true. If the assertion fails, invokes t.Error() to fail the unit test. Returns true if the assertion passed, or false if it failed.

func Timestamp

func Timestamp(optWithMS ...bool) string

Timestamp returns a timestamp string using the current local time. The format is: 'YYYY-MM-DD hh:mm:ss' (18 characters). I.e. date, and 24-hour time with seconds, and optional milliseconds The time zone is not included.

func TitleCase

func TitleCase(s string) string

TitleCase changes a string to title case.

func TokenGet

func TokenGet(list string, index int, sep string) string

TokenGet __ // TODO: rename to GetToken, GetTokenEx. create SetToken

func TokenGetEx

func TokenGetEx(list string, index int, sep string, ignoreEnd bool) string

TokenGetEx _ _

func TrueCount

func TrueCount(values ...bool) int

TrueCount _ _

func UUID

func UUID() string

UUID generates and returns a new UUID (Universally Unique Identifier). The format is 'XXXXXXXX-XXXX-4XXX-ZXXX-XXXXXXXXXXXX' where every X is a random upper-case hex digit, and Z must be one of '8', '9', 'A' or 'B'.

func UncompressBytes

func UncompressBytes(data []byte) []byte

UncompressBytes uncompresses a ZLIB-compressed array of bytes.

func VerboseLog

func VerboseLog(args ...interface{})

VerboseLog sends output to the log loop, but only when verbose mode is set to true.

func VerboseLogf

func VerboseLogf(format string, args ...interface{})

VerboseLogf outputs a formatted message to the standard output and to a log file named "<process>.log" in the program's current directory, only when verbose mode is set to true. The 'format' parameter accepts a format string, followed by one or more optional arguments, exactly like fmt.Printf() and fmt.Errorf() It also outputs the call stack (names and line numbers of callers.)

func VersionTime

func VersionTime() string

VersionTime returns the library version as a date/time string.

func WordIndex

func WordIndex(s, word string, caseMode CaseMode) int

WordIndex returns the index of the first instance of word in s, or -1 if word is not present in s. Specify MatchCase or IgnoreCase for case mode.

func WriteGoString

func WriteGoString(
	value interface{},
	useGoStringer bool,
	indentAt int,
	buf *bytes.Buffer,
)

WriteGoString writes a fundamental type in Go language syntax to a buffer.

It is called by zr.GoString() function and various types' GoString() methods to generate their results.

value: the value being read

useGoStringer: when true, calls GoString() or GoStringEx() if

value implements any of these methods.

indentAt: specifies if output should be on a single

line (-1) or indented to a number of tab stops.

buf: pointer to output buffer

func XorBytes

func XorBytes(data, cipher []byte) []byte

XorBytes _ _

func YMD

func YMD(t time.Time) string

YMD returns a date using the 'yyyy-mm-dd' format.

Types

type Bytes

type Bytes struct {
	// contains filtered or unexported fields

} //                                                                       Bytes

Bytes wraps an array of bytes and provides byte-manipulation methods.

func BytesAlloc

func BytesAlloc(size int) Bytes

BytesAlloc creates a new Bytes object with a pre-allocated size.

func BytesAllocUTF8

func BytesAllocUTF8(s string) Bytes

BytesAllocUTF8 creates a new Bytes object by UTF-8 encoding the string 's'.

func BytesWrap

func BytesWrap(ar []byte) Bytes

BytesWrap creates a new Bytes object by wrapping a byte array 'data'.

func (*Bytes) Append

func (ob *Bytes) Append(b Bytes)

Append appends another Bytes object to the end of this object.

func (*Bytes) AppendChar

func (ob *Bytes) AppendChar(ch rune) int

AppendChar appends a Unicode character encoded in UTF-8 format to the end. Returns the number of bytes used to encode the character. If the character is not valid, returns -1 and doesn't change the object.

func (*Bytes) Cap

func (ob *Bytes) Cap() int

Cap returns the allocated capacity of this object.

func (*Bytes) FindByte

func (ob *Bytes) FindByte(b byte) int

FindByte returns the index of the first occurrence of byte 'b'.

func (*Bytes) GetByte

func (ob *Bytes) GetByte(index int) byte

GetByte returns the byte at the specified byte index.

func (*Bytes) GetBytes

func (ob *Bytes) GetBytes() []byte

GetBytes returns a raw byte array of bytes in this object.

func (*Bytes) GetChar

func (ob *Bytes) GetChar(index int) CharSize

GetChar returns the Unicode character at the specified byte index. Assumes that the data is encoded in UTF-8 format. Note that the index is the byte index, not the character number.

func (*Bytes) Insert

func (ob *Bytes) Insert(index int, data Bytes, count int) int

Insert inserts a sequence of 'data' bytes at position 'index' into object. Returns the number of bytes inserted.

func (*Bytes) Remove

func (ob *Bytes) Remove(index, count int)

Remove removes 'count' bytes from position starting at 'index'.

func (*Bytes) Reset

func (ob *Bytes) Reset()

Reset empties the contents of this object making Size() equal zero, but does not release the allocated memory, so Cap() remains the same.

func (*Bytes) Resize

func (ob *Bytes) Resize(size int)

Resize resizes the Bytes object so that Size() equals 'size'. If the new size is smaller than the old size, the contents is truncated. If it is bigger, appends zeros to pad the contents.

func (*Bytes) SetByte

func (ob *Bytes) SetByte(index int, val byte)

SetByte _ _

func (*Bytes) Size

func (ob *Bytes) Size() int

Size returns the written size of this object. (Always less than capacity)

func (*Bytes) Slice

func (ob *Bytes) Slice(beginIndex, endIndex int) Bytes

Slice returns a Bytes object that is a slice of this object. The slice references the original array so no new memory allocation is made.

beginIndex is the starting position. Must not be less than zero in which the function treats it as zero and logs an error.

endIndex is the ending position, just after the last required element. If endIndex is -1, returns everything from beginIndex up to the end.

func (*Bytes) String

func (ob *Bytes) String() string

String returns a string based on previously-written bytes and implements the fmt.Stringer interface.

type Calendar

type Calendar struct {
	// contains filtered or unexported fields

} //                                                                    Calendar

Calendar provides logic for generating calendar grids from dates and values.

func (*Calendar) AddMonth

func (ob *Calendar) AddMonth(year int, month time.Month) error

AddMonth adds a month to the calendar, without setting any values. The year must range from 1 to 9999.

func (*Calendar) HasMonth

func (ob *Calendar) HasMonth(year int, month time.Month) bool

HasMonth returns true if the month specified by year and month has been added to the calendar

func (*Calendar) Set

func (ob *Calendar) Set(date, value interface{})

Set assigns the specified value to the specified date. It automatically converts 'date' to time.Time

func (*Calendar) SetWeekTotals added in v1.1.1

func (ob *Calendar) SetWeekTotals(v bool)

SetWeekTotals disables or enables weekly subtotals.

func (*Calendar) String

func (ob *Calendar) String() string

String returns the calendar as a text string and implements the fmt.Stringer interface.

The output may contain multiple months, in which case the months are arranged in ascending order.

See the sample output in the body of the function.

type CaseMode

type CaseMode uint

CaseMode type specifies if text comparisons are case sensitive. Various functions have a CaseMode parameter.

There are two possible values:

IgnoreCase: text is matched irrespective of letter capitalization. MatchCase: case must be matched exactly.

type CharSize

type CharSize struct {
	Val  rune
	Size int

} //                                                                    CharSize

CharSize holds a character value and its UTF-8 encoded size in bytes.

type Currency

type Currency struct {
	// contains filtered or unexported fields

} //                                                                    Currency

Currency represents a currency value with up to four decimal places. It is stored internally as a 64-bit integer. This gives it a range from -922,337,203,685,477.5808 to 922,337,203,685,477.5807

func CurrencyE

func CurrencyE(value interface{}) (Currency, error)

CurrencyE converts any compatible value to a Currency. This includes simple numeric types and strings.

- Dereferences pointers to evaluate the pointed-to type. - Converts nil to 0. - Converts signed and unsigned integers, and floats to Currency. - Converts numeric strings to Currency. - Converts boolean true to 1, false to 0.

Note: fmt.Stringer (or fmt.GoStringer) interfaces are not treated as strings to avoid bugs from implicit conversion. Use the String method.

If the value can not be converted to Currency, returns a zero-value Currency and an error. Does not log the error.

func CurrencyOf

func CurrencyOf(value interface{}) Currency

CurrencyOf converts any compatible value type to a Currency. This includes all numeric types and strings. If a string is not numeric, logs an error and sets the Currency to zero.

- Dereferences pointers to evaluate the pointed-to type. - Converts nil to 0. - Converts signed and unsigned integers, and floats to Currency. - Converts numeric strings to Currency. - Converts boolean true to 1, false to 0.

If the value can not be converted to Currency, returns a zero-value Currency and logs an error (when logging is active).

func CurrencyOfS

func CurrencyOfS(s string) Currency

CurrencyOfS converts a numeric string to a Currency. If the string is not numeric, logs an error and sets the Currency to zero.

func CurrencyRaw

func CurrencyRaw(i64 int64) Currency

CurrencyRaw initializes a currency value from a scaled 64-bit integer. The decimal point is moved left 4 decimal places. For example, a i64 value of 15500 results in a currency value of 1.55

func (Currency) Add

func (n Currency) Add(nums ...Currency) Currency

Add adds one or more currency values and returns a new Currency object. The value in the object to which this method is applied isn't changed. If there is an overflow, sets the Currency's internal value to math.MinInt64 or math.MaxInt64 depending on if the result is negative.

func (Currency) AddFloat

func (n Currency) AddFloat(nums ...float64) Currency

AddFloat adds one or more floating-point numbers to a currency object and returns the result. The object's value isn't changed.

func (Currency) AddInt

func (n Currency) AddInt(nums ...int) Currency

AddInt adds one or more integer values to a currency object and returns the result. The object's value isn't changed.

func (Currency) Div

func (n Currency) Div(nums ...Currency) Currency

Div divides a currency object by one or more currency values and returns the result. The object's value isn't changed.

func (Currency) DivFloat

func (n Currency) DivFloat(nums ...float64) Currency

DivFloat divides a currency object by one or more floating-point numbers and returns the result. The object's value isn't changed.

func (Currency) DivInt

func (n Currency) DivInt(nums ...int) Currency

DivInt divides a currency object by one or more integer values and returns the result. The object's value isn't changed.

func (Currency) Float64

func (n Currency) Float64() float64

Float64 returns the currency value as a float64 value.

func (Currency) Fmt

func (n Currency) Fmt(decimalPlaces int) string

Fmt returns the currency value as a a string delimited with commas (grouped every three digits) and having the specified number of decimal places. When decimalPlaces is negative, the resulting number's decimals will vary.

func (Currency) GoString

func (n Currency) GoString() string

GoString outputs the value as a Go language string, It implements the fmt.GoStringer interface.

func (Currency) InWordsEN

func (n Currency) InWordsEN(fmt string) string

InWordsEN returns the currency value as an English description in words This function is useful for showing amounts in invoices, etc.

Uses English language names, hence the 'EN' suffix.

fmt: a string specifying the currency format:

format_ = "<Large-Single>;<Large-Plural>;<S-Single>;<S-Plural>;<Only>"
Large-Single - Large Denomination, Singular. E.g. "Dollar"
Large-Plural - Large Denomination, Plural.   E.g. "Dollars"
S-Single     - Small Denomination, Singular. E.g. "Cent"
S-Plural     - Small Denomination, Plural.   E.g. "Cents"

All the format specifiers are optional but must follow in
the order specified. If a plural specifier is omitted, then
an "s" is added to the singular specifier for values greater
than 1. If the singular specifier is omitted, Then the
plural is used for all values (Used for some currencies).
If both specifiers are omitted for either denomination, the
denomination will not be returned. See the examples below.

Returns: The amount in words as a string, including the currency

and the word "Only". Uses proper capitalisation.

Example: PARAMETER RESULT

(11.02,";;Cent;Only")   "Two Cents Only"
(11.02,"Dollar;;Cent")  "Eleven Dollars and Two Cents"
(11.02,"Euro")          "Eleven Euros"
(11.02,"Pound;;;Pence") "Eleven Pounds and Two Pence"

func (Currency) Int

func (n Currency) Int() int64

Int returns the currency value as an int value.

func (Currency) Int64

func (n Currency) Int64() int64

Int64 returns the currency value as an int64 value.

func (Currency) IsEqual

func (n Currency) IsEqual(value interface{}) bool

IsEqual returns true if the value of the currency object is negative.

func (Currency) IsGreater

func (n Currency) IsGreater(value interface{}) bool

IsGreater returns true if the object is greater than value.

func (Currency) IsGreaterOrEqual

func (n Currency) IsGreaterOrEqual(value interface{}) bool

IsGreaterOrEqual returns true if the object is greater or equal to value.

func (Currency) IsLesser

func (n Currency) IsLesser(value interface{}) bool

IsLesser returns true if the object is lesser than value.

func (Currency) IsLesserOrEqual

func (n Currency) IsLesserOrEqual(value interface{}) bool

IsLesserOrEqual returns true if the object is lesser or equal to value.

func (Currency) IsNegative

func (n Currency) IsNegative() bool

IsNegative returns true if the value of the currency object is negative.

func (Currency) IsZero

func (n Currency) IsZero() bool

IsZero returns true if the value of the currency object is zero.

func (Currency) MarshalJSON

func (n Currency) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON encoding of zr.Currency.

func (Currency) Mul

func (n Currency) Mul(nums ...Currency) Currency

Mul multiplies a currency object by one or more currency values and returns the result. The object's value isn't changed.

func (Currency) MulFloat

func (n Currency) MulFloat(nums ...float64) Currency

MulFloat multiplies a currency object by one or more floating-point numbers and returns the result. The object's value isn't changed.

func (Currency) MulInt

func (n Currency) MulInt(nums ...int) Currency

MulInt multiplies a currency object by one or more integer values and returns the result. The object's value isn't changed.

func (Currency) Overflow

func (n Currency) Overflow() int

Overflow returns 1 if the currency contains a positive overflow, -1 if it contains a negative overflow, or 0 if there is no overflow

Overflows occur when an arithmeric operation's result exceeds the storage capacity of Currency.

func (Currency) Raw

func (n Currency) Raw() int64

Raw returns the internal int64 used to store the currency value.

func (Currency) String

func (n Currency) String() string

String returns a string representing the currency value and implements the fmt.Stringer interface.

func (Currency) Sub

func (n Currency) Sub(nums ...Currency) Currency

Sub subtracts one or more currency values from a currency object and returns the result. The object's value isn't changed.

func (Currency) SubFloat

func (n Currency) SubFloat(nums ...float64) Currency

SubFloat subtracts one or more floating-point numbers from a currency object and returns the result. The object's value isn't changed.

func (Currency) SubInt

func (n Currency) SubInt(nums ...int) Currency

SubInt subtracts one or more integer values from a currency object and returns the result. The object's value isn't changed.

func (*Currency) UnmarshalJSON

func (n *Currency) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals a JSON description of zr.Currency. This method alters the object's value.

type DateRange

type DateRange struct {
	From time.Time
	To   time.Time

} //                                                                   DateRange

DateRange represents a time period.

func DateRangeOf

func DateRangeOf(s string) DateRange

DateRangeOf creates and returns a DateRange structure from a string. _ _

func (DateRange) IsNull

func (ob DateRange) IsNull() bool

IsNull returns true if the date range doesn't represent any period.

func (DateRange) String

func (ob DateRange) String() string

String returns a string representation of the DateRange structure and implements the fmt.Stringer interface.

type GoStringerEx

type GoStringerEx interface {
	GoStringEx(indentAt int) string

} //                                                                GoStringerEx

GoStringerEx interface is implemented by objects that can output their definitions in Go language syntax. It extends the standard fmt.GoStringer interface with an optional indent parameter.

type HideCallers

type HideCallers struct{}

HideCallers hides the call stack when passed as one of the arguments to Error() and Callers(). It does not interfere with other output.

type IntTuple

type IntTuple struct{ A, B int }

IntTuple holds a tuple (pair) of integer values.

func (IntTuple) String

func (ob IntTuple) String() string

String returns a string representation of the IntTuple structure and implements the fmt.Stringer interface.

type IntTuples

type IntTuples []IntTuple

IntTuples holds multiple tuples (pairs) of integer values. It implements the sort.Inteface to make sorting easy.

func (IntTuples) Len

func (ob IntTuples) Len() int

Len is the number of elements in the collection. (sort.Interface)

func (IntTuples) Less

func (ob IntTuples) Less(i, j int) bool

Less reports whether the element with index 'i' should sort before element[j]. (sort.Interface)

func (IntTuples) Swap

func (ob IntTuples) Swap(i, j int)

Swap swaps the elements with indexes i and j. (sort.Interface)

type MaxDepth

type MaxDepth int

MaxDepth specifies the highest caller in the call stack that should be output by Error() and Callers(), when passed as one of the arguments to these functions. The function that called the current function is 1, etc. It does not interfere with other output.

type MinDepth

type MinDepth int

MinDepth specifies the closest caller in the call stack that should be output by Error() and Callers(), when passed as one of the arguments to these functions. The function that called the current function is 1, etc. It does not interfere with other output.

type Settings

type Settings struct {
	// contains filtered or unexported fields

} //                                                                    Settings

Settings _ _

func (*Settings) Dump

func (ob *Settings) Dump()

Dump prints out all settings and their stored values to console.

func (*Settings) ExtendGet

func (ob *Settings) ExtendGet(
	handler func(name, value string, exists bool) string,
)

ExtendGet makes 'handler' process every call to GetSetting()

func (*Settings) ExtendHas

func (ob *Settings) ExtendHas(
	handler func(name, value string, exists bool) bool,
)

ExtendHas makes 'handler' process every call to HasSetting()

func (*Settings) ExtendSet

func (ob *Settings) ExtendSet(
	handler func(name string, old, value interface{}) *string,
)

ExtendSet makes 'handle' process every call to SetSetting()

func (*Settings) GetSetting

func (ob *Settings) GetSetting(name string) string

GetSetting _ _

func (*Settings) HasSetting

func (ob *Settings) HasSetting(name string) bool

HasSetting _ _

func (*Settings) SetSetting

func (ob *Settings) SetSetting(name string, value interface{})

SetSetting _ _

type SettingsAccessor

type SettingsAccessor interface {
	GetSetting(name string) string
	HasSetting(name string) bool
	SetSetting(name string, value interface{})
	Dump()

} //                                                            SettingsAccessor

SettingsAccessor _ _

type StringAligner

type StringAligner struct {
	Values  [][]string
	Width   map[int]int
	Padding int
	Prefix  string
	Suffix  string

} //                                                               StringAligner

StringAligner left-aligns columns of strings.

func (*StringAligner) Clear

func (ob *StringAligner) Clear()

Clear erases the content of the object.

func (*StringAligner) String

func (ob *StringAligner) String() string

String outputs the previously-written rows with columns aligned by spaces and implements the fmt.Stringer interface.

func (*StringAligner) Write

func (ob *StringAligner) Write(row ...string)

Write writes a row of strings to the object.

func (*StringAligner) WriteBreak

func (ob *StringAligner) WriteBreak()

WriteBreak writes a row of strings to the object.

type StringStack

type StringStack struct {
	// contains filtered or unexported fields

} //                                                                 StringStack

StringStack is a simple string stack class.

func (*StringStack) ChangeTop

func (ob *StringStack) ChangeTop(s string) string

ChangeTop changes the topmost (most recently added) string in the stack. It returns the existing string. If the stack was empty, appends the string.

func (*StringStack) Pop

func (ob *StringStack) Pop() string

Pop returns and removes the most recently added string from the stack.

func (*StringStack) Push

func (ob *StringStack) Push(s string) string

Push adds string 's' to the top of the stack. It returns 's'.

func (*StringStack) Top

func (ob *StringStack) Top() string

Top returns the topmost, most recently added string on the stack, without altering the stack.

type TStringer

type TStringer struct {
	// contains filtered or unexported fields

} //                                                                   TStringer

TStringer is a mock type that provides the fmt.Stringer interface.

func NewTStringer

func NewTStringer(s string) TStringer

NewTStringer _ _

func (TStringer) GoString

func (ob TStringer) GoString() string

GoString _ _

func (*TStringer) Set

func (ob *TStringer) Set(s string)

Set sets the string that will be returned by the String() and GoString() methods.

func (TStringer) String

func (ob TStringer) String() string

String _ _

type Timer

type Timer struct {
	Mutex        sync.RWMutex
	Tasks        map[string]*TimerTask
	LastTaskName string
	PrintEvents  bool

} //                                                                       Timer

Timer gathers timing statistics for multiple tasks, for example to collect the total time spent executing functions. Timing begins by calling Start() with the name of a timed task, and ends by calling Stop(taskName). You can make multiple calls to Start() and Stop() for the same task. Timer will accumulate the total time spent on each task and the number of times it was executed.

To get a timing report: call the Print() method to output the report to the console. You can also get the report using the String() method, or call GetTasks() to obtain a map of named tasks and their timing statistics.

You can reuse the same Timer by calling Reset() to clear its contents.

The current version of Timer should not be used to time the same task running in parallel.

Example:

import "github.com/balacode/zr"

func (*Timer) GetTasks

func (ob *Timer) GetTasks() map[string]*TimerTask

GetTasks returns a map of named tasks and their timing statistics.

func (*Timer) Print

func (ob *Timer) Print(prefix ...string)

Print prints out a timing report to the console (i.e. standard output) Shows the name of each task, the total time spent on the task, the number of times the task was executed, and the average running time in seconds rounded to 4 decimal places.

func (*Timer) Rename added in v1.1.0

func (ob *Timer) Rename(taskName, newName string) string

Rename renames a timed task. If there is an existing task with the same name as newTaskName, the old task will be merged with the existing task. The times of the two tasks will be combined.

Returns newTaskName

func (*Timer) ReportByTimeSpent added in v1.1.0

func (ob *Timer) ReportByTimeSpent() string

ReportByTimeSpent returns the timing report as a string, with items sorted by time spent in descending order.

func (*Timer) Reset

func (ob *Timer) Reset()

Reset clears all timing data from the timer.

func (*Timer) Start

func (ob *Timer) Start(taskName string) string

Start begins timing the named task. Make sure you call Stop() when the task is complete. You can start and stop the same task multiple times, provided you call Stop() after every Start().

func (*Timer) Stop

func (ob *Timer) Stop(taskName string)

Stop stops timing the named task and stores the time spent in the Timer.

func (*Timer) StopLast

func (ob *Timer) StopLast()

StopLast _ _

func (*Timer) String

func (ob *Timer) String() string

String returns the timing report as a string, and implements the fmt.Stringer interface.

type TimerTask

type TimerTask struct {
	Count     int
	SerialNo  int
	StartTime time.Time
	TotalMs   float32

} //                                                                   TimerTask

TimerTask holds the timing statistics of a timed task.

type WordMode

type WordMode uint

WordMode type determines if a search should match whole words when searching (or replacing, etc.) a string.

Words are composed of alphabetic and numeric characters and underscores.

There are two possible values: IgnoreWord: do not match distinct words. MatchWord: match distinct words.

Jump to

Keyboard shortcuts

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