OSDN Git Service

new repo
[bytom/vapor.git] / vendor / github.com / tendermint / tmlibs / common / word.go
1 package common
2
3 import (
4         "bytes"
5         "sort"
6 )
7
8 var (
9         Zero256 = Word256{0}
10         One256  = Word256{1}
11 )
12
13 type Word256 [32]byte
14
15 func (w Word256) String() string        { return string(w[:]) }
16 func (w Word256) TrimmedString() string { return TrimmedString(w.Bytes()) }
17 func (w Word256) Copy() Word256         { return w }
18 func (w Word256) Bytes() []byte         { return w[:] } // copied.
19 func (w Word256) Prefix(n int) []byte   { return w[:n] }
20 func (w Word256) Postfix(n int) []byte  { return w[32-n:] }
21 func (w Word256) IsZero() bool {
22         accum := byte(0)
23         for _, byt := range w {
24                 accum |= byt
25         }
26         return accum == 0
27 }
28 func (w Word256) Compare(other Word256) int {
29         return bytes.Compare(w[:], other[:])
30 }
31
32 func Uint64ToWord256(i uint64) Word256 {
33         buf := [8]byte{}
34         PutUint64BE(buf[:], i)
35         return LeftPadWord256(buf[:])
36 }
37
38 func Int64ToWord256(i int64) Word256 {
39         buf := [8]byte{}
40         PutInt64BE(buf[:], i)
41         return LeftPadWord256(buf[:])
42 }
43
44 func RightPadWord256(bz []byte) (word Word256) {
45         copy(word[:], bz)
46         return
47 }
48
49 func LeftPadWord256(bz []byte) (word Word256) {
50         copy(word[32-len(bz):], bz)
51         return
52 }
53
54 func Uint64FromWord256(word Word256) uint64 {
55         buf := word.Postfix(8)
56         return GetUint64BE(buf)
57 }
58
59 func Int64FromWord256(word Word256) int64 {
60         buf := word.Postfix(8)
61         return GetInt64BE(buf)
62 }
63
64 //-------------------------------------
65
66 type Tuple256 struct {
67         First  Word256
68         Second Word256
69 }
70
71 func (tuple Tuple256) Compare(other Tuple256) int {
72         firstCompare := tuple.First.Compare(other.First)
73         if firstCompare == 0 {
74                 return tuple.Second.Compare(other.Second)
75         } else {
76                 return firstCompare
77         }
78 }
79
80 func Tuple256Split(t Tuple256) (Word256, Word256) {
81         return t.First, t.Second
82 }
83
84 type Tuple256Slice []Tuple256
85
86 func (p Tuple256Slice) Len() int { return len(p) }
87 func (p Tuple256Slice) Less(i, j int) bool {
88         return p[i].Compare(p[j]) < 0
89 }
90 func (p Tuple256Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
91 func (p Tuple256Slice) Sort()         { sort.Sort(p) }