Documentation ¶
Overview ¶
Package hex utils functions.
Index ¶
- Constants
- Variables
- func ASCIITrim(s string) string
- func DecodeUint64(input string) (uint64, error)
- func EnsureDir(dir string, mode os.FileMode) error
- func Exit(s string)
- func FileExists(filePath string) bool
- func GoPath() string
- func IsASCIIText(s string) bool
- func IsDirEmpty(name string) (bool, error)
- func IsHex(s string) bool
- func Kill() error
- func MustReadFile(filePath string) []byte
- func MustWriteFile(filePath string, contents []byte, mode os.FileMode)
- func NewID() string
- func PanicConsensus(v interface{})
- func PanicCrisis(v interface{})
- func PanicQ(v interface{})
- func PanicSanity(v interface{})
- func Prompt(prompt string, defaultValue string) (string, error)
- 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 Seed(seed int64)
- func SplitAndTrim(s, sep, cutset string) []string
- func StringInSlice(a string, list []string) bool
- func StripHex(s string) string
- func TrapSignal(cb func())
- func WriteFile(filePath string, contents []byte, mode os.FileMode) error
- 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) SetLogger(l log.Logger)
- func (bs *BaseService) Start() error
- func (bs *BaseService) Stop() error
- func (bs *BaseService) String() string
- func (bs *BaseService) Wait()
- type Big
- type Bytes
- func (bz Bytes) Bytes() []byte
- func (bz Bytes) Format(s fmt.State, verb rune)
- func (bz Bytes) Marshal() ([]byte, error)
- func (bz Bytes) MarshalJSON() ([]byte, error)
- func (bz Bytes) String() string
- func (bz *Bytes) Unmarshal(data []byte) error
- func (bz *Bytes) UnmarshalJSON(data []byte) error
- func (bz *Bytes) UnmarshalText(data []byte) error
- type Error
- type FmtError
- type Hash
- func (h Hash) Big() *big.Int
- func (h Hash) Bytes() []byte
- func (h Hash) Format(s fmt.State, c rune)
- func (h Hash) Generate(rand *rand.Rand, size int) reflect.Value
- func (h Hash) Hex() string
- func (h Hash) MarshalJSON() ([]byte, error)
- func (h *Hash) SetBytes(b []byte)
- func (h Hash) String() string
- func (h Hash) TerminalString() string
- func (h *Hash) UnmarshalJSON(input []byte) error
- type Hex
- func (h *Hex) Decode(dst, src []byte) (int, error)
- func (h *Hex) DecodeLen(n int) int
- func (h *Hex) DecodeString(data string) ([]byte, error)
- func (h *Hex) Encode(dst, src []byte) (int, error)
- func (h *Hex) EncodeBig(data *big.Int) []byte
- func (h *Hex) EncodeLen(n int) int
- func (h *Hex) EncodeToString(data []byte) string
- func (h *Hex) EncodeUint(data uint) []byte
- func (h *Hex) EncodeUint64(data uint64) []byte
- func (h *Hex) HasPrefix(data []byte) bool
- func (h *Hex) MustDecodeString(data string) []byte
- func (h *Hex) String() string
- 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 Service
- type Uint
- type Uint64
Constants ¶
const (
HashLength = 32
)
------------------------- package Consts, Vars Lengths of hashes and addresses in bytes.
const (
PREFIX = "0x"
)
------------------------ package Const, Vars
Variables ¶
var ( // errors ErrBig256Range = NewError("hex number > 256 bits") ErrUint64Range = NewError("hex number > 64 bits") ErrUintRange = NewError(fmt.Sprintf("hex number > %d bits", uintBits)) ErrSyntax = NewError("invalid hex string") ErrLeadingZero = NewError("hex number with leading zero digits") ErrEmptyNumber = NewError("hex string \"0x\"") )
var ( // E: Empty Data ErrEmptyData = errors.New("empty hex data") // E: without prefix ErrMissingPrefix = errors.Errorf("hex string without %s prefix", PREFIX) // E: odd length hex string ErrOddLength = errors.New("hex string of odd length") )
errors
var ( ErrAlreadyStarted = errors.New("already started") ErrAlreadyStopped = errors.New("already stopped") )
var Fmt = func(format string, a ...interface{}) string { if len(a) == 0 { return format } return fmt.Sprintf(format, a...) }
Like fmt.Sprintf, but skips formatting if args are empty.
var Ghex = New(PREFIX)
Functions ¶
func DecodeUint64 ¶
func FileExists ¶
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 IsASCIIText ¶
Returns true if s is a non-empty printable non-tab ascii character.
func IsDirEmpty ¶
func MustReadFile ¶
func NewID ¶ added in v1.0.0
func NewID() string
NewID generates a identifier that can be used as an identifier in the RPC interface. e.g. filter and subscription identifier.
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 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.
Types ¶
type BaseService ¶
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(logger log.Logger, 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) SetLogger ¶
func (bs *BaseService) SetLogger(l log.Logger)
SetLogger implements Service by setting a logger.
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 Big ¶
Big marshals/unmarshals as a JSON string with 0x prefix. The zero value marshals as "0x0".
Negative integers are not supported at this time. Attempting to marshal them will return an error. Values larger than 256bits are rejected by Unmarshal but will be marshaled without error.
func (Big) MarshalJSON ¶
MarshalJSON implements encoding.JSONMarshaler.
func (Big) MarshalText ¶
MarshalText implements encoding.TextMarshaler
func (*Big) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
func (*Big) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler
type Bytes ¶
type Bytes []byte
func (Bytes) MarshalJSON ¶
MarshalJSON implement encoding/json Marshaler interface.
func (*Bytes) UnmarshalJSON ¶
This is the point of Bytes.
func (*Bytes) UnmarshalText ¶
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 Hash ¶
type Hash [HashLength]byte
Hash represents the 32 byte Keccak256 hash of arbitrary data.
func BigToHash ¶
BigToHash sets byte representation of b to hash. If b is larger than len(h), b will be cropped from the left.
func BytesToHash ¶
BytesToHash sets b to hash. If b is larger than len(h), b will be cropped from the left.
func HexToHash ¶
HexToHash sets byte representation of s to hash. If b is larger than len(h), b will be cropped from the left.
func (Hash) Format ¶
Format implements fmt.Formatter, forcing the byte slice to be formatted as is, without going through the stringer interface used for logging.
func (Hash) MarshalJSON ¶
func (*Hash) SetBytes ¶
SetBytes sets the hash to the value of b. If b is larger than len(h), b will be cropped from the left.
func (Hash) String ¶
String implements the stringer interface and is used also by the logger when doing full logging into a file.
func (Hash) TerminalString ¶
TerminalString implements log.TerminalStringer, formatting a string for console output during logging.
func (*Hash) UnmarshalJSON ¶
UnmarshalJSON parses a hash in hex syntax.
type Hex ¶
type Hex struct {
// contains filtered or unexported fields
}
Hex Encode and Decode hex string with prefix 0x
func (*Hex) DecodeString ¶
DecodeString decode hex string to []byte
func (*Hex) EncodeToString ¶
EncodeToString encode []byte to string
func (*Hex) EncodeUint64 ¶
EncodeUint64 uint64 to []byte
func (*Hex) MustDecodeString ¶
MustDecode decode hex string to []byte or panic error
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 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 // SetLogger sets a logger. SetLogger(log.Logger) }
Service defines a service that can be started, stopped, and reset.
type Uint ¶
type Uint uint
Uint marshals/unmarshals as a JSON string with 0x prefix.
func (Uint) MarshalJSON ¶
MarshalJSON implements encoding.JSONMarshaler.
func (Uint) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (*Uint) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
func (*Uint) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler.
type Uint64 ¶
type Uint64 uint64
Uint64 marshals/unmarshals as a JSON string with 0x prefix. The zero value marshals as "0x0".
func (Uint64) MarshalJSON ¶
MarshalJSON implements encoding.JSONMarshaler.
func (Uint64) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (*Uint64) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
func (*Uint64) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler