Documentation ¶
Index ¶
- Variables
- func ASCIITrim(s string) string
- func BeginWatchMgr()
- func CRandBytes(numBytes int) []byte
- func CRandHex(numDigits int) string
- func CReader() io.Reader
- func CheckAndPrintError(err error)
- func EncodeUvarint(w io.Writer, u uint64) (err error)
- func EndWatchMgr()
- func EnsureDir(dir string, mode os.FileMode) error
- func EqualHashes(hash1, hash2 []byte) bool
- func Fingerprint(slice []byte) []byte
- func IsASCIIText(s string) bool
- func IsZeros(slice []byte) bool
- func Kill() error
- func LeftPadBytes(slice []byte, l int) []byte
- func MaxInt(a, b int) int
- func MaxUint(a, b uint) uint
- func MinInt(a, b int) int
- func MinUint(a, b uint) uint
- func MixEntropy(seedBytes []byte)
- func PanicSanity(v interface{})
- func PrefixEndBytes(prefix []byte) []byte
- func ProtocolAndAddress(listenAddr string) (string, string)
- func RandFloat64() float64
- func RandInt() int
- func RandInt31n(n int32) int32
- func RandInt63n(n int64) int64
- func RandIntn(n int) int
- func RandPerm(n int) []int
- func RandStr(length int) string
- func RightPadBytes(slice []byte, l int) []byte
- func RlpHash(x interface{}) (h common.Hash)
- func SplitAndTrim(s, sep, cutset string) []string
- func TrimmedString(b []byte) string
- func WatchsCountInMgr() uint64
- func WriteFileAtomic(filename string, data []byte, perm os.FileMode) (err error)
- type Address
- type BaseService
- func (bs *BaseService) IsRunning() bool
- func (bs *BaseService) OnReset() error
- func (bs *BaseService) OnStart() error
- func (bs *BaseService) OnStop()
- func (bs *BaseService) Quit() <-chan struct{}
- func (bs *BaseService) Reset() error
- func (bs *BaseService) Start() error
- func (bs *BaseService) Stop() error
- func (bs *BaseService) String() string
- func (bs *BaseService) Wait()
- type BitArray
- func (bA *BitArray) And(o *BitArray) *BitArray
- func (bA *BitArray) Bytes() []byte
- func (bA *BitArray) Copy() *BitArray
- func (bA *BitArray) GetIndex(i uint) 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() (uint, bool)
- func (bA *BitArray) SetIndex(i uint, v bool) bool
- func (bA *BitArray) Size() uint
- 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 CMap
- type Comparable
- 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
- type PeerInValidators
- type RepeatTimer
- type Service
- type SimpleProof
- type SimpleProofNode
- type TWatch
- 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
- type WatchMgr
Constants ¶
This section is empty.
Variables ¶
var ( ErrAlreadyStarted = errors.New("already started") ErrAlreadyStopped = errors.New("already stopped") )
var ( // WatchFinishTime used to handle the end event in every watch WatchFinishTime = 3 // MaxLockTime used to judge the watch is locked MaxLockTime = 60 // MaxWatchInChan MaxWatchInChan = 20000 )
var DurationStat = newDurationStat()
Functions ¶
func BeginWatchMgr ¶
func BeginWatchMgr()
func CRandHex ¶
CRandHex returns a hex encoded string that's floor(numDigits/2) * 2 long.
Note: CRandHex(24) gives 96 bits of randomness that are usually strong enough for most purposes.
func CheckAndPrintError ¶
func CheckAndPrintError(err error)
func EndWatchMgr ¶
func EndWatchMgr()
func EqualHashes ¶
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 IsASCIIText ¶
Returns true if s is a non-empty printable non-tab ascii character.
func LeftPadBytes ¶
func MixEntropy ¶
func MixEntropy(seedBytes []byte)
Mix additional bytes of randomness, e.g. from hardware, user-input, etc. It is OK to call it multiple times. It does not diminish security.
func PanicSanity ¶
func PanicSanity(v interface{})
func PrefixEndBytes ¶
PrefixEndBytes returns the end byteslice for a noninclusive range that would include all byte slices for which the input is the prefix
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 RandFloat64 ¶
func RandFloat64() float64
func RandInt ¶
func RandInt() int
-----------------------------------------------------------------------------
func RandInt31n ¶
func RandInt63n ¶
func RightPadBytes ¶
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 TrimmedString ¶
func WatchsCountInMgr ¶
func WatchsCountInMgr() uint64
Types ¶
type BaseService ¶
type BaseService struct {
// contains filtered or unexported fields
}
Classical-inheritance-style service declarations. Services can be started, then stopped, then optionally restarted.
Users can override the OnStart/OnStop methods. In the absence of errors, these methods are guaranteed to be called at most once. If OnStart returns an error, service won't be marked as started, so the user can call Start again.
A call to Reset will panic, unless OnReset is overwritten, allowing OnStart/OnStop to be called again.
The caller must ensure that Start and Stop are not called concurrently.
It is ok to call Stop without calling Start first.
Typical usage:
type FooService struct { BaseService // private fields } func NewFooService() *FooService { fs := &FooService{ // init } fs.BaseService = *NewBaseService(log, "FooService", fs) return fs } func (fs *FooService) OnStart() error { fs.BaseService.OnStart() // Always call the overridden method. // initialize private fields // start subroutines, etc. } func (fs *FooService) OnStop() error { fs.BaseService.OnStop() // Always call the overridden method. // close/destroy private fields // stop subroutines, etc. }
func NewBaseService ¶
func NewBaseService(name string, impl Service) *BaseService
NewBaseService creates a new BaseService.
func (*BaseService) IsRunning ¶
func (bs *BaseService) IsRunning() bool
IsRunning implements Service by returning true or false depending on the service's state.
func (*BaseService) OnReset ¶
func (bs *BaseService) OnReset() error
OnReset implements Service by panicking.
func (*BaseService) OnStart ¶
func (bs *BaseService) OnStart() error
OnStart implements Service by doing nothing. NOTE: Do not put anything in here, that way users don't need to call BaseService.OnStart()
func (*BaseService) OnStop ¶
func (bs *BaseService) OnStop()
OnStop implements Service by doing nothing. NOTE: Do not put anything in here, that way users don't need to call BaseService.OnStop()
func (*BaseService) Quit ¶
func (bs *BaseService) Quit() <-chan struct{}
Quit Implements Service by returning a quit channel.
func (*BaseService) Reset ¶
func (bs *BaseService) Reset() error
Reset implements Service by calling OnReset callback (if defined). An error will be returned if the service is running.
func (*BaseService) Start ¶
func (bs *BaseService) Start() error
Start implements Service by calling OnStart (if defined). An error will be returned if the service is already running or stopped. Not to start the stopped service, you need to call Reset.
func (*BaseService) Stop ¶
func (bs *BaseService) Stop() error
Stop implements Service by calling OnStop (if defined) and closing quit channel. An error will be returned if the service is already stopped.
func (*BaseService) String ¶
func (bs *BaseService) String() string
String implements Servce by returning a string representation of the service.
type BitArray ¶
type BitArray struct { Mtx sync.Mutex Bits uint `json:"bits"` // NOTE: persisted via reflect, must be exported Elems []uint64 `json:"elems"` // NOTE: persisted via reflect, must be exported }
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 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 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 PeerInValidators ¶
----------------------------------------------------------------------------- PeerInValidators judge the peer whether in validators set
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 Service ¶
type Service interface { // Start the service. // If it's already started or stopped, will return an error. // If OnStart() returns an error, it's returned by Start() Start() error OnStart() error // Stop the service. // If it's already stopped, will return an error. // OnStop must never error. Stop() error OnStop() // Reset the service. // Panics by default - must be overwritten to enable reset. Reset() error OnReset() error // Return true if the service is running IsRunning() bool // Quit returns a channel, which is closed once service is stopped. Quit() <-chan struct{} // String representation of the service String() string }
Service defines a service that can be started, stopped, and reset.
type SimpleProof ¶
type SimpleProof struct { Total int `json:"total"` // Total number of items. Index int `json:"index"` // Index of item to prove. LeafHash []byte `json:"leaf_hash"` // Hash of item value. Aunts [][]byte `json:"aunts"` // Hashes from leaf's sibling to a root's child. }
SimpleProof represents a simple Merkle proof. NOTE: The convention for proofs is to include leaf hashes but to exclude the root hash. This convention is implemented across IAVL range proofs as well. Keep this consistent unless there's a very good reason to change everything. This also affects the generalized proof system as well.
func SimpleProofsFromByteSlices ¶
func SimpleProofsFromByteSlices(items [][]byte) (rootHash []byte, proofs []*SimpleProof)
SimpleProofsFromByteSlices computes inclusion proof for given items. proofs[0] is the proof for items[0].
func (*SimpleProof) ComputeRootHash ¶
func (sp *SimpleProof) ComputeRootHash() []byte
ComputeRootHash Compute the root hash given a leaf hash. Does not verify the result.
func (*SimpleProof) String ¶
func (sp *SimpleProof) String() string
String implements the stringer interface for SimpleProof. It is a wrapper around StringIndented.
func (*SimpleProof) StringIndented ¶
func (sp *SimpleProof) StringIndented(indent string) string
StringIndented generates a canonical string representation of a SimpleProof.
type SimpleProofNode ¶
type SimpleProofNode struct { Hash []byte Parent *SimpleProofNode Left *SimpleProofNode // Left sibling (only one of Left,Right is set) Right *SimpleProofNode // Right sibling (only one of Left,Right is set) }
SimpleProofNode is a helper structure to construct merkle proof. The node and the tree is thrown away afterwards. Exactly one of node.Left and node.Right is nil, unless node is the root, in which case both are nil. node.Parent.Hash = hash(node.Hash, node.Right.Hash) or hash(node.Left.Hash, node.Hash), depending on whether node is a left/right child.
func (*SimpleProofNode) FlattenAunts ¶
func (spn *SimpleProofNode) FlattenAunts() [][]byte
FlattenAunts will return the inner hashes for the item corresponding to the leaf, starting from a leaf SimpleProofNode.
type TWatch ¶
type TWatch struct { ID uint64 // contains filtered or unexported fields }
----------------------------------------------------------------------------- TWatch watch and output the cost time for exec
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.