github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/common/bytes.go (about) 1 // This file is part of the go-sberex library. The go-sberex library is 2 // free software: you can redistribute it and/or modify it under the terms 3 // of the GNU Lesser General Public License as published by the Free 4 // Software Foundation, either version 3 of the License, or (at your option) 5 // any later version. 6 // 7 // The go-sberex library is distributed in the hope that it will be useful, 8 // but WITHOUT ANY WARRANTY; without even the implied warranty of 9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 10 // General Public License <http://www.gnu.org/licenses/> for more details. 11 12 // Package common contains various helper functions. 13 package common 14 15 import "encoding/hex" 16 17 func ToHex(b []byte) string { 18 hex := Bytes2Hex(b) 19 // Prefer output of "0x0" instead of "0x" 20 if len(hex) == 0 { 21 hex = "0" 22 } 23 return "0x" + hex 24 } 25 26 func FromHex(s string) []byte { 27 if len(s) > 1 { 28 if s[0:2] == "0x" || s[0:2] == "0X" { 29 s = s[2:] 30 } 31 } 32 if len(s)%2 == 1 { 33 s = "0" + s 34 } 35 return Hex2Bytes(s) 36 } 37 38 // Copy bytes 39 // 40 // Returns an exact copy of the provided bytes 41 func CopyBytes(b []byte) (copiedBytes []byte) { 42 if b == nil { 43 return nil 44 } 45 copiedBytes = make([]byte, len(b)) 46 copy(copiedBytes, b) 47 48 return 49 } 50 51 func hasHexPrefix(str string) bool { 52 return len(str) >= 2 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X') 53 } 54 55 func isHexCharacter(c byte) bool { 56 return ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F') 57 } 58 59 func isHex(str string) bool { 60 if len(str)%2 != 0 { 61 return false 62 } 63 for _, c := range []byte(str) { 64 if !isHexCharacter(c) { 65 return false 66 } 67 } 68 return true 69 } 70 71 func Bytes2Hex(d []byte) string { 72 return hex.EncodeToString(d) 73 } 74 75 func Hex2Bytes(str string) []byte { 76 h, _ := hex.DecodeString(str) 77 78 return h 79 } 80 81 func Hex2BytesFixed(str string, flen int) []byte { 82 h, _ := hex.DecodeString(str) 83 if len(h) == flen { 84 return h 85 } else { 86 if len(h) > flen { 87 return h[len(h)-flen:] 88 } else { 89 hh := make([]byte, flen) 90 copy(hh[flen-len(h):flen], h[:]) 91 return hh 92 } 93 } 94 } 95 96 func RightPadBytes(slice []byte, l int) []byte { 97 if l <= len(slice) { 98 return slice 99 } 100 101 padded := make([]byte, l) 102 copy(padded, slice) 103 104 return padded 105 } 106 107 func LeftPadBytes(slice []byte, l int) []byte { 108 if l <= len(slice) { 109 return slice 110 } 111 112 padded := make([]byte, l) 113 copy(padded[l-len(slice):], slice) 114 115 return padded 116 }