Documentation ¶
Index ¶
- Constants
- Variables
- func ASCIITrim(s string) string
- func Black(args ...interface{}) string
- func Blue(args ...interface{}) string
- func Byte32ToByteSlice(b [][32]byte) []byte
- func ByteSliceToByte32(b []byte) [][32]byte
- func ColoredBytes(data []byte, textColor, bytesColor func(...interface{}) string) string
- func Connect(protoAddr string) (net.Conn, error)
- func Cyan(args ...interface{}) string
- func EnsureDir(dir string, mode os.FileMode) error
- func Exit(s string)
- func FileExists(filePath string) bool
- func Fingerprint(slice []byte) []byte
- func GoPath() string
- func Green(args ...interface{}) string
- func IntInSlice(a int, list []int) bool
- func IsASCIIText(s string) bool
- func IsDirEmpty(name string) (bool, error)
- func IsEmpty(o interface{}) bool
- func IsTypedNil(o interface{}) bool
- func Kill() error
- func Magenta(args ...interface{}) string
- func MaxInt(a, b int) int
- func MaxInt64(a, b int64) int64
- func MinInt(a, b int) int
- func MinInt64(a, b int64) int64
- func MustReadFile(filePath string) []byte
- func MustWriteFile(filePath string, contents []byte, mode os.FileMode)
- func PanicConsensus(v interface{})
- func PanicCrisis(v interface{})
- func PanicQ(v interface{})
- func PanicSanity(v interface{})
- func ParseDateRange(dateRange string) (startDate, endDate time.Time, err error)
- func Prompt(prompt string, defaultValue string) (string, error)
- func ProtocolAndAddress(listenAddr string) (string, string)
- func RandBool() bool
- func RandBytes(n int) []byte
- func RandFloat32() float32
- func RandFloat64() float64
- func RandInt() int
- func RandInt16() int16
- func RandInt31() int32
- func RandInt31n(n int32) int32
- func RandInt32() int32
- func RandInt63() int64
- func RandInt63n(n int64) int64
- func RandInt64() int64
- func RandIntn(n int) int
- func RandPerm(n int) []int
- func RandStr(length int) string
- func RandTime() time.Time
- func RandUint() uint
- func RandUint16() uint16
- func RandUint32() uint32
- func RandUint64() uint64
- func ReadFile(filePath string) ([]byte, error)
- func Red(args ...interface{}) string
- func Seed(seed int64)
- func SplitAndTrim(s, sep, cutset string) []string
- func StringInSlice(a string, list []string) bool
- func TrapSignal(cb func())
- func White(args ...interface{}) string
- func WriteFile(filePath string, contents []byte, mode os.FileMode) error
- func WriteFileAtomic(filename string, data []byte, perm os.FileMode) (err error)
- func Yellow(args ...interface{}) string
- type BitArray
- func (bA *BitArray) And(o *BitArray) *BitArray
- func (bA *BitArray) Bytes() []byte
- func (bA *BitArray) Copy() *BitArray
- func (bA *BitArray) Count() int
- func (bA *BitArray) GetIndex(i int) bool
- func (bA *BitArray) IsEmpty() bool
- func (bA *BitArray) IsFull() bool
- func (bA *BitArray) MarshalJSON() ([]byte, error)
- func (bA *BitArray) Not() *BitArray
- func (bA *BitArray) Or(o *BitArray) *BitArray
- func (bA *BitArray) PickRandom() (int, bool)
- func (bA *BitArray) SetIndex(i int, v bool) bool
- func (bA *BitArray) Size() int
- func (bA *BitArray) String() string
- func (bA *BitArray) StringIndented(indent string) string
- func (bA *BitArray) Sub(o *BitArray) *BitArray
- func (bA *BitArray) UnmarshalJSON(bz []byte) error
- func (bA *BitArray) Update(o *BitArray)
- type BufferCloser
- type CMap
- type Comparable
- type Error
- type FmtError
- type Heap
- func (h *Heap) Len() int64
- func (h *Heap) Peek() interface{}
- func (h *Heap) Pop() interface{}
- func (h *Heap) Push(value interface{}, priority int)
- func (h *Heap) PushBytes(value interface{}, priority []byte)
- func (h *Heap) PushComparable(value interface{}, priority Comparable)
- func (h *Heap) Update(value interface{}, priority Comparable)
- type HexBytes
- func (bz HexBytes) Bytes() []byte
- func (bz HexBytes) Format(s fmt.State, verb rune)
- func (bz HexBytes) Marshal() ([]byte, error)
- func (bz HexBytes) MarshalJSON() ([]byte, error)
- func (bz HexBytes) String() string
- func (bz *HexBytes) Unmarshal(data []byte) error
- func (bz *HexBytes) UnmarshalJSON(data []byte) error
- type PrefixedReader
- type Rand
- func (r *Rand) Bool() bool
- func (r *Rand) Bytes(n int) []byte
- func (r *Rand) Float32() float32
- func (r *Rand) Float64() float64
- func (r *Rand) Int() int
- func (r *Rand) Int16() int16
- func (r *Rand) Int31() int32
- func (r *Rand) Int31n(n int32) int32
- func (r *Rand) Int32() int32
- func (r *Rand) Int63() int64
- func (r *Rand) Int63n(n int64) int64
- func (r *Rand) Int64() int64
- func (r *Rand) Intn(n int) int
- func (r *Rand) Perm(n int) []int
- func (r *Rand) Seed(seed int64)
- func (r *Rand) Str(length int) string
- func (r *Rand) Time() time.Time
- func (r *Rand) Uint() uint
- func (r *Rand) Uint16() uint16
- func (r *Rand) Uint32() uint32
- func (r *Rand) Uint64() uint64
- type RepeatTimer
- type Task
- type TaskResult
- type TaskResultCh
- type TaskResultSet
- func (trs *TaskResultSet) Channels() []TaskResultCh
- func (trs *TaskResultSet) FirstError() error
- func (trs *TaskResultSet) FirstValue() interface{}
- func (trs *TaskResultSet) LatestResult(index int) (TaskResult, bool)
- func (trs *TaskResultSet) Reap() *TaskResultSet
- func (trs *TaskResultSet) Wait() *TaskResultSet
- type ThrottleTimer
- type Ticker
- type TickerMaker
Constants ¶
const ( ANSIReset = "\x1b[0m" ANSIBright = "\x1b[1m" ANSIDim = "\x1b[2m" ANSIUnderscore = "\x1b[4m" ANSIBlink = "\x1b[5m" ANSIReverse = "\x1b[7m" ANSIHidden = "\x1b[8m" ANSIFgBlack = "\x1b[30m" ANSIFgRed = "\x1b[31m" ANSIFgGreen = "\x1b[32m" ANSIFgYellow = "\x1b[33m" ANSIFgBlue = "\x1b[34m" ANSIFgMagenta = "\x1b[35m" ANSIFgCyan = "\x1b[36m" ANSIFgWhite = "\x1b[37m" ANSIBgBlack = "\x1b[40m" ANSIBgRed = "\x1b[41m" ANSIBgGreen = "\x1b[42m" ANSIBgYellow = "\x1b[43m" ANSIBgBlue = "\x1b[44m" ANSIBgMagenta = "\x1b[45m" ANSIBgCyan = "\x1b[46m" ANSIBgWhite = "\x1b[47m" )
Variables ¶
var TimeLayout = "2006-01-02" //this represents YYYY-MM-DD
TimeLayout helps to parse a date string of the format YYYY-MM-DD
Intended to be used with the following function: time.Parse(TimeLayout, date)
Functions ¶
func ColoredBytes ¶
func Connect ¶
Connect dials the given address and returns a net.Conn. The protoAddr argument should be prefixed with the protocol, eg. "tcp://127.0.0.1:8080" or "unix:///tmp/test.sock"
func FileExists ¶
func Fingerprint ¶
Fingerprint returns the first 6 bytes of a byte slice. If the slice is less than 6 bytes, the fingerprint contains trailing zeroes.
func GoPath ¶
func GoPath() string
GoPath returns GOPATH env variable value. If it is not set, this function will try to call `go env GOPATH` subcommand.
func IntInSlice ¶
IntInSlice returns true if a is found in the list.
func IsASCIIText ¶
Returns true if s is a non-empty printable non-tab ascii character.
func IsDirEmpty ¶
func IsTypedNil ¶
func IsTypedNil(o interface{}) bool
Go lacks a simple and safe way to see if something is a typed nil. See:
func MustReadFile ¶
func PanicConsensus ¶
func PanicConsensus(v interface{})
Indicates a failure of consensus. Someone was malicious or something has gone horribly wrong. These should really boot us into an "emergency-recover" mode XXX DEPRECATED
func PanicCrisis ¶
func PanicCrisis(v interface{})
A panic here means something has gone horribly wrong, in the form of data corruption or failure of the operating system. In a correct/healthy system, these should never fire. If they do, it's indicative of a much more serious problem. XXX DEPRECATED
func PanicQ ¶
func PanicQ(v interface{})
For those times when we're not sure if we should panic XXX DEPRECATED
func PanicSanity ¶
func PanicSanity(v interface{})
A panic resulting from a sanity check means there is a programmer error and some guarantee is not satisfied. XXX DEPRECATED
func ParseDateRange ¶
ParseDateRange parses a date range string of the format start:end
where the start and end date are of the format YYYY-MM-DD. The parsed dates are time.Time and will return the zero time for unbounded dates, ex: unbounded start: :2000-12-31 unbounded end: 2000-12-31:
func ProtocolAndAddress ¶
ProtocolAndAddress splits an address into the protocol and address components. For instance, "tcp://127.0.0.1:8080" will be split into "tcp" and "127.0.0.1:8080". If the address has no protocol prefix, the default is "tcp".
func RandFloat32 ¶
func RandFloat32() float32
func RandFloat64 ¶
func RandFloat64() float64
func RandInt31n ¶
func RandInt63n ¶
func RandUint16 ¶
func RandUint16() uint16
func RandUint32 ¶
func RandUint32() uint32
func RandUint64 ¶
func RandUint64() uint64
func SplitAndTrim ¶
SplitAndTrim slices s into all subslices separated by sep and returns a slice of the string s with all leading and trailing Unicode code points contained in cutset removed. If sep is empty, SplitAndTrim splits after each UTF-8 sequence. First part is equivalent to strings.SplitN with a count of -1.
func StringInSlice ¶
StringInSlice returns true if a is found the list.
func TrapSignal ¶
func TrapSignal(cb func())
TrapSignal catches the SIGTERM and executes cb function. After that it exits with code 1.
func WriteFileAtomic ¶
WriteFileAtomic creates a temporary file with data and provided perm and swaps it atomically with filename if successful.
Types ¶
type BitArray ¶
type BitArray struct { Bits uint32 `json:"bits"` // NOTE: persisted via reflect, must be exported Elems []uint64 `json:"elems"` // NOTE: persisted via reflect, must be exported // contains filtered or unexported fields }
BitArray is a thread-safe implementation of a bit array.
func NewBitArray ¶
NewBitArray returns a new bit array. It returns nil if the number of bits is zero.
func (*BitArray) And ¶
And returns a bit array resulting from a bitwise AND of the two bit arrays. If the two bit-arrys have different lengths, this truncates the larger of the two bit-arrays from the right. Thus the size of the return value is the minimum of the two provided bit arrays.
func (*BitArray) GetIndex ¶
GetIndex returns the bit at index i within the bit array. The behavior is undefined if i >= bA.Bits
func (*BitArray) MarshalJSON ¶
MarshalJSON implements json.Marshaler interface by marshaling bit array using a custom format: a string of '-' or 'x' where 'x' denotes the 1 bit.
func (*BitArray) Not ¶
Not returns a bit array resulting from a bitwise Not of the provided bit array.
func (*BitArray) Or ¶
Or returns a bit array resulting from a bitwise OR of the two bit arrays. If the two bit-arrys have different lengths, Or right-pads the smaller of the two bit-arrays with zeroes. Thus the size of the return value is the maximum of the two provided bit arrays.
func (*BitArray) PickRandom ¶
PickRandom returns a random index in the bit array, and its value. It uses the global randomness in `random.go` to get this index.
func (*BitArray) SetIndex ¶
SetIndex sets the bit at index i within the bit array. The behavior is undefined if i >= bA.Bits
func (*BitArray) String ¶
String returns a string representation of BitArray: BA{<bit-string>}, where <bit-string> is a sequence of 'x' (1) and '_' (0). The <bit-string> includes spaces and newlines to help people. For a simple sequence of 'x' and '_' characters with no spaces or newlines, see the MarshalJSON() method. Example: "BA{_x_}" or "nil-BitArray" for nil.
func (*BitArray) StringIndented ¶
StringIndented returns the same thing as String(), but applies the indent at every 10th bit, and twice at every 50th bit.
func (*BitArray) Sub ¶
Sub subtracts the two bit-arrays bitwise, without carrying the bits. This is essentially bA.And(o.Not()). If bA is longer than o, o is right padded with zeroes.
func (*BitArray) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler interface by unmarshaling a custom JSON description.
type BufferCloser ¶
NOTE: Not goroutine safe
func NewBufferCloser ¶
func NewBufferCloser(buf []byte) *BufferCloser
func (*BufferCloser) Close ¶
func (bc *BufferCloser) Close() error
func (*BufferCloser) WriteByte ¶
func (bc *BufferCloser) WriteByte(c byte) error
func (*BufferCloser) WriteString ¶
func (bc *BufferCloser) WriteString(s string) (n int, err error)
type CMap ¶
type CMap struct {
// contains filtered or unexported fields
}
CMap is a goroutine-safe map
type Comparable ¶
type Comparable interface {
Less(o interface{}) bool
}
type Error ¶
type Error interface { Error() string Stacktrace() Error Trace(offset int, format string, args ...interface{}) Error Data() interface{} }
Usage with arbitrary error data:
```go
// Error construction type MyError struct{} var err1 error = NewErrorWithData(MyError{}, "my message") ... // Wrapping var err2 error = ErrorWrap(err1, "another message") if (err1 != err2) { panic("should be the same") ... // Error handling switch err2.Data().(type){ case MyError: ... default: ... }
```
func NewErrorWithData ¶
func NewErrorWithData(data interface{}) Error
New Error with specified data.
type FmtError ¶
type FmtError struct {
// contains filtered or unexported fields
}
FmtError is the data type for NewError() (e.g. NewError().Data().(FmtError)) Theoretically it could be used to switch on the format string.
```go
// Error construction var err1 error = NewError("invalid username %v", "BOB") var err2 error = NewError("another kind of error") ... // Error handling switch err1.Data().(cmn.FmtError).Format() { case "invalid username %v": ... case "another kind of error": ... default: ... }
```
type Heap ¶
type Heap struct {
// contains filtered or unexported fields
}
Example usage:
``` h := NewHeap()
h.Push("msg1", 1) h.Push("msg3", 3) h.Push("msg2", 2)
fmt.Println(h.Pop()) // msg1 fmt.Println(h.Pop()) // msg2 fmt.Println(h.Pop()) // msg3 ```
func (*Heap) PushComparable ¶
func (h *Heap) PushComparable(value interface{}, priority Comparable)
func (*Heap) Update ¶
func (h *Heap) Update(value interface{}, priority Comparable)
type HexBytes ¶
type HexBytes []byte
The main purpose of HexBytes is to enable HEX-encoding for json/encoding.
func (HexBytes) MarshalJSON ¶
This is the point of Bytes.
func (*HexBytes) UnmarshalJSON ¶
This is the point of Bytes.
type PrefixedReader ¶
type PrefixedReader struct { Prefix []byte // contains filtered or unexported fields }
func NewPrefixedReader ¶
func NewPrefixedReader(prefix []byte, reader io.Reader) *PrefixedReader
type Rand ¶
Rand is a prng, that is seeded with OS randomness. The OS randomness is obtained from crypto/rand, however none of the provided methods are suitable for cryptographic usage. They all utilize math/rand's prng internally.
All of the methods here are suitable for concurrent use. This is achieved by using a mutex lock on all of the provided methods.
func (*Rand) Intn ¶
Intn returns, as an int, a uniform pseudo-random number in the range [0, n). It panics if n <= 0.
type RepeatTimer ¶
type RepeatTimer struct {
// contains filtered or unexported fields
}
RepeatTimer repeatedly sends a struct{}{} to `.Chan()` after each `dur` period. (It's good for keeping connections alive.) A RepeatTimer must be stopped, or it will keep a goroutine alive.
func NewRepeatTimer ¶
func NewRepeatTimer(name string, dur time.Duration) *RepeatTimer
NewRepeatTimer returns a RepeatTimer with a defaultTicker.
func NewRepeatTimerWithTickerMaker ¶
func NewRepeatTimerWithTickerMaker(name string, dur time.Duration, tm TickerMaker) *RepeatTimer
NewRepeatTimerWithTicker returns a RepeatTimer with the given ticker maker.
func (*RepeatTimer) Chan ¶
func (t *RepeatTimer) Chan() <-chan time.Time
func (*RepeatTimer) Stop ¶
func (t *RepeatTimer) Stop()
type Task ¶
val: the value returned after task execution. err: the error returned during task completion. abort: tells Parallel to return, whether or not all tasks have completed.
type TaskResult ¶
type TaskResult struct { Value interface{} Error error }
type TaskResultCh ¶
type TaskResultCh <-chan TaskResult
type TaskResultSet ¶
type TaskResultSet struct {
// contains filtered or unexported fields
}
func Parallel ¶
func Parallel(tasks ...Task) (trs *TaskResultSet, ok bool)
Run tasks in parallel, with ability to abort early. Returns ok=false iff any of the tasks returned abort=true. NOTE: Do not implement quit features here. Instead, provide convenient concurrent quit-like primitives, passed implicitly via Task closures. (e.g. it's not Parallel's concern how you quit/abort your tasks).
func (*TaskResultSet) Channels ¶
func (trs *TaskResultSet) Channels() []TaskResultCh
func (*TaskResultSet) FirstError ¶
func (trs *TaskResultSet) FirstError() error
Returns the firstmost (by task index) error as discovered by all previous Reap() calls.
func (*TaskResultSet) FirstValue ¶
func (trs *TaskResultSet) FirstValue() interface{}
Returns the firstmost (by task index) error as discovered by all previous Reap() calls.
func (*TaskResultSet) LatestResult ¶
func (trs *TaskResultSet) LatestResult(index int) (TaskResult, bool)
func (*TaskResultSet) Reap ¶
func (trs *TaskResultSet) Reap() *TaskResultSet
NOTE: Not concurrency safe. Writes results to trs.results without waiting for all tasks to complete.
func (*TaskResultSet) Wait ¶
func (trs *TaskResultSet) Wait() *TaskResultSet
NOTE: Not concurrency safe. Like Reap() but waits until all tasks have returned or panic'd.
type ThrottleTimer ¶
type ThrottleTimer struct { Name string Ch chan struct{} // contains filtered or unexported fields }
ThrottleTimer fires an event at most "dur" after each .Set() call. If a short burst of .Set() calls happens, ThrottleTimer fires once. If a long continuous burst of .Set() calls happens, ThrottleTimer fires at most once every "dur".
func NewThrottleTimer ¶
func NewThrottleTimer(name string, dur time.Duration) *ThrottleTimer
func (*ThrottleTimer) Set ¶
func (t *ThrottleTimer) Set()
func (*ThrottleTimer) Stop ¶
func (t *ThrottleTimer) Stop() bool
For ease of .Stop()'ing services before .Start()'ing them, we ignore .Stop()'s on nil ThrottleTimers
func (*ThrottleTimer) Unset ¶
func (t *ThrottleTimer) Unset()
type Ticker ¶
type Ticker interface { // Never changes, never closes. Chan() <-chan time.Time // Stopping a stopped Ticker will panic. Stop() }
Ticker is a basic ticker interface.
type TickerMaker ¶
Used by RepeatTimer the first time, and every time it's Reset() after Stop().
func NewLogicalTickerMaker ¶
func NewLogicalTickerMaker(source chan time.Time) TickerMaker
Construct a TickerMaker that always uses `source`. It's useful for simulating a deterministic clock.