erigon-pulse/erigon-lib/common/hexutility/hex.go
battlmonstr 231e468e19 Add 'erigon-lib/' from commit '93d9c9d9fe4bd8a49f7a98a6bce0f0da7094c7d3'
git-subtree-dir: erigon-lib
git-subtree-mainline: 3c8cbda809
git-subtree-split: 93d9c9d9fe
2023-09-20 14:50:25 +02:00

104 lines
2.3 KiB
Go

/*
Copyright 2021 Erigon contributors
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 hexutility
import (
"encoding/binary"
"encoding/hex"
)
func MustDecodeHex(in string) []byte {
in = strip0x(in)
if len(in)%2 == 1 {
in = "0" + in
}
payload, err := hex.DecodeString(in)
if err != nil {
panic(err)
}
return payload
}
func strip0x(str string) string {
if len(str) >= 2 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X') {
return str[2:]
}
return str
}
// EncodeTs encodes a TimeStamp (BlockNumber or TxNumber or other uin64) as big endian
func EncodeTs(number uint64) []byte {
enc := make([]byte, 8)
binary.BigEndian.PutUint64(enc, number)
return enc
}
// Encode encodes b as a hex string with 0x prefix.
func Encode(b []byte) string {
enc := make([]byte, len(b)*2+2)
copy(enc, "0x")
hex.Encode(enc[2:], b)
return string(enc)
}
func FromHex(s string) []byte {
if Has0xPrefix(s) {
s = s[2:]
}
if len(s)%2 == 1 {
s = "0" + s
}
return Hex2Bytes(s)
}
// Has0xPrefix validates str begins with '0x' or '0X'.
func Has0xPrefix(str string) bool {
return len(str) >= 2 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X')
}
// Hex2Bytes returns the bytes represented by the hexadecimal string str.
func Hex2Bytes(str string) []byte {
h, _ := hex.DecodeString(str)
return h
}
// IsHex validates whether each byte is valid hexadecimal string.
func IsHex(str string) bool {
if len(str)%2 != 0 {
return false
}
for _, c := range []byte(str) {
if !isHexCharacter(c) {
return false
}
}
return true
}
// isHexCharacter returns bool of c being a valid hexadecimal.
func isHexCharacter(c byte) bool {
return ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F')
}
func MustDecodeString(s string) []byte {
r, err := hex.DecodeString(s)
if err != nil {
panic(err)
}
return r
}