forked from studyzy/runestone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
84 lines (77 loc) · 2.01 KB
/
common.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Copyright 2024 The BxELab studyzy Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package runestone
import (
"errors"
"math/big"
"lukechampine.com/uint128"
)
var ErrNone = errors.New("none")
func Encode(n *big.Int) []byte {
var result []byte
for n.Cmp(big.NewInt(128)) >= 0 {
temp := new(big.Int).Set(n)
last := temp.And(n, new(big.Int).SetUint64(0b0111_1111))
result = append(result, last.Or(last, new(big.Int).SetUint64(0b1000_0000)).Bytes()[0])
n.Rsh(n, 7)
}
if len(n.Bytes()) == 0 {
result = append(result, 0)
} else {
result = append(result, n.Bytes()...)
}
return result
}
func Decode(encoded []byte) *big.Int {
result := new(big.Int)
for i := len(encoded) - 1; i >= 0; i-- {
result.Lsh(result, 7)
byteVal := new(big.Int).SetUint64(uint64(encoded[i] & 0b0111_1111))
result.Or(result, byteVal)
}
return result
}
func EncodeUint64(n uint64) []byte {
var result []byte
for n >= 128 {
result = append(result, byte(n&0x7F|0x80))
n >>= 7
}
result = append(result, byte(n))
return result
}
func EncodeUint32(n uint32) []byte {
var result []byte
for n >= 128 {
result = append(result, byte(n&0x7F|0x80))
n >>= 7
}
result = append(result, byte(n))
return result
}
func EncodeUint8(n uint8) []byte {
var result []byte
for n >= 128 {
result = append(result, byte(n&0x7F|0x80))
n >>= 7
}
result = append(result, byte(n))
return result
}
func EncodeUint128(n uint128.Uint128) []byte {
return Encode(n.Big())
}
func EncodeChar(r rune) []byte {
return EncodeUint32(uint32(r))
}