help

package
v0.0.0-...-a323530 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 2020 License: GPL-3.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrAlreadyStarted = errors.New("already started")
	ErrAlreadyStopped = errors.New("already stopped")
)
View Source
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
)
View Source
var DurationStat = newDurationStat()

Functions

func ASCIITrim

func ASCIITrim(s string) string

NOTE: Assumes that s is ASCII as per IsASCIIText(), otherwise panics.

func BeginWatchMgr

func BeginWatchMgr()

func CRandBytes

func CRandBytes(numBytes int) []byte

This uses the OS and the Seed(s).

func CRandHex

func CRandHex(numDigits int) string

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 CReader

func CReader() io.Reader

Returns a crand.Reader mixed with user-supplied entropy

func CheckAndPrintError

func CheckAndPrintError(err error)

func EncodeUvarint

func EncodeUvarint(w io.Writer, u uint64) (err error)

func EndWatchMgr

func EndWatchMgr()

func EnsureDir

func EnsureDir(dir string, mode os.FileMode) error

func EqualHashes

func EqualHashes(hash1, hash2 []byte) bool

func Fingerprint

func Fingerprint(slice []byte) []byte

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

func IsASCIIText(s string) bool

Returns true if s is a non-empty printable non-tab ascii character.

func IsZeros

func IsZeros(slice []byte) bool

func Kill

func Kill() error

Kill the running process by sending itself SIGTERM.

func LeftPadBytes

func LeftPadBytes(slice []byte, l int) []byte

func MaxInt

func MaxInt(a, b int) int

-----------------------------------------------------------------------------

func MaxUint

func MaxUint(a, b uint) uint

func MinInt

func MinInt(a, b int) int

func MinUint

func MinUint(a, b uint) uint

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

func PrefixEndBytes(prefix []byte) []byte

PrefixEndBytes returns the end byteslice for a noninclusive range that would include all byte slices for which the input is the prefix

func ProtocolAndAddress

func ProtocolAndAddress(listenAddr string) (string, string)

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 RandInt31n(n int32) int32

func RandInt63n

func RandInt63n(n int64) int64

func RandIntn

func RandIntn(n int) int

func RandPerm

func RandPerm(n int) []int

func RandStr

func RandStr(length int) string

func RightPadBytes

func RightPadBytes(slice []byte, l int) []byte

func RlpHash

func RlpHash(x interface{}) (h common.Hash)

func SplitAndTrim

func SplitAndTrim(s, sep, cutset string) []string

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 TrimmedString(b []byte) string

func WatchsCountInMgr

func WatchsCountInMgr() uint64

func WriteFileAtomic

func WriteFileAtomic(filename string, data []byte, perm os.FileMode) (err error)

WriteFileAtomic creates a temporary file with data and provided perm and swaps it atomically with filename if successful.

Types

type Address

type Address = HexBytes

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.

func (*BaseService) Wait

func (bs *BaseService) Wait()

Wait blocks until the service is stopped.

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

func NewBitArray(bits uint) *BitArray

NewBitArray returns a new bit array. It returns nil if the number of bits is zero.

func (*BitArray) And

func (bA *BitArray) And(o *BitArray) *BitArray

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) Bytes

func (bA *BitArray) Bytes() []byte

Bytes returns the byte representation of the bits within the bitarray.

func (*BitArray) Copy

func (bA *BitArray) Copy() *BitArray

Copy returns a copy of the provided bit array.

func (*BitArray) GetIndex

func (bA *BitArray) GetIndex(i uint) bool

GetIndex returns the bit at index i within the bit array. The behavior is undefined if i >= bA.Bits

func (*BitArray) IsEmpty

func (bA *BitArray) IsEmpty() bool

IsEmpty returns true iff all bits in the bit array are 0

func (*BitArray) IsFull

func (bA *BitArray) IsFull() bool

IsFull returns true iff all bits in the bit array are 1.

func (*BitArray) MarshalJSON

func (bA *BitArray) MarshalJSON() ([]byte, error)

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

func (bA *BitArray) Not() *BitArray

Not returns a bit array resulting from a bitwise Not of the provided bit array.

func (*BitArray) Or

func (bA *BitArray) Or(o *BitArray) *BitArray

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

func (bA *BitArray) PickRandom() (uint, bool)

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

func (bA *BitArray) SetIndex(i uint, v bool) bool

SetIndex sets the bit at index i within the bit array. The behavior is undefined if i >= bA.Bits

func (*BitArray) Size

func (bA *BitArray) Size() uint

Size returns the number of bits in the bitarray

func (*BitArray) String

func (bA *BitArray) String() 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

func (bA *BitArray) StringIndented(indent string) string

StringIndented returns the same thing as String(), but applies the indent at every 10th bit, and twice at every 50th bit.

func (*BitArray) Sub

func (bA *BitArray) Sub(o *BitArray) *BitArray

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

func (bA *BitArray) UnmarshalJSON(bz []byte) error

UnmarshalJSON implements json.Unmarshaler interface by unmarshaling a custom JSON description.

func (*BitArray) Update

func (bA *BitArray) Update(o *BitArray)

Update sets the bA's bits to be that of the other bit array. The copying begins from the begin of both bit arrays.

type CMap

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

CMap is a goroutine-safe map

func NewCMap

func NewCMap() *CMap

func (*CMap) Clear

func (cm *CMap) Clear()

func (*CMap) Delete

func (cm *CMap) Delete(key string)

func (*CMap) Get

func (cm *CMap) Get(key string) interface{}

func (*CMap) Has

func (cm *CMap) Has(key string) bool

func (*CMap) Keys

func (cm *CMap) Keys() []string

func (*CMap) Set

func (cm *CMap) Set(key string, value interface{})

func (*CMap) Size

func (cm *CMap) Size() int

func (*CMap) Values

func (cm *CMap) Values() []interface{}

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 NewHeap

func NewHeap() *Heap

func (*Heap) Len

func (h *Heap) Len() int64

func (*Heap) Peek

func (h *Heap) Peek() interface{}

func (*Heap) Pop

func (h *Heap) Pop() interface{}

func (*Heap) Push

func (h *Heap) Push(value interface{}, priority int)

func (*Heap) PushBytes

func (h *Heap) PushBytes(value interface{}, priority []byte)

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

type PeerInValidators

type PeerInValidators interface {
	HasPeerID(id string) error
}

----------------------------------------------------------------------------- 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) Reset

func (t *RepeatTimer) Reset()

Wait the duration again before firing.

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.

func (*SimpleProof) Verify

func (sp *SimpleProof) Verify(rootHash []byte, leafHash []byte) error

Verify that the SimpleProof proves the root hash. Check sp.Index/sp.Total manually if needed

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

func NewTWatch

func NewTWatch(e float64, s string) *TWatch

NewTWatch make the new watch

func (*TWatch) EndWatch

func (in *TWatch) EndWatch()

EndWatch end the watch

func (*TWatch) Finish

func (in *TWatch) Finish(comment interface{})

Finish count the cost time in watch

type Task

type Task func(i int) (val interface{}, err error, abort bool)

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

type TickerMaker func(dur time.Duration) Ticker

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.

type WatchMgr

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

Directories

Path Synopsis
Package flowrate provides the tools for monitoring and limiting the flow rate of an arbitrary data stream.
Package flowrate provides the tools for monitoring and limiting the flow rate of an arbitrary data stream.

Jump to

Keyboard shortcuts

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