github.com/klaytn/klaytn@v1.12.1/common/bytes.go (about)

     1  // Modifications Copyright 2018 The klaytn Authors
     2  // Copyright 2015 The go-ethereum Authors
     3  // This file is part of the go-ethereum library.
     4  //
     5  // The go-ethereum library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Lesser General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // The go-ethereum library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU Lesser General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public License
    16  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    17  //
    18  // This file is derived from common/bytes.go (2018/06/04).
    19  // Modified and improved for the klaytn development.
    20  
    21  package common
    22  
    23  import (
    24  	"crypto/rand"
    25  	"encoding/binary"
    26  	"encoding/hex"
    27  	"io"
    28  )
    29  
    30  // ToHex returns the hex representation of b, prefixed with '0x'.
    31  // For empty slices, the return value is "0x0".
    32  //
    33  // Deprecated: use hexutil.Encode instead.
    34  func ToHex(b []byte) string {
    35  	hex := Bytes2Hex(b)
    36  	if len(hex) == 0 {
    37  		hex = "0"
    38  	}
    39  	return "0x" + hex
    40  }
    41  
    42  // FromHex returns the bytes represented by the hexadecimal string s.
    43  // s may be prefixed with "0x".
    44  func FromHex(s string) []byte {
    45  	if len(s) > 1 {
    46  		if s[0:2] == "0x" || s[0:2] == "0X" {
    47  			s = s[2:]
    48  		}
    49  	}
    50  	if len(s)%2 == 1 {
    51  		s = "0" + s
    52  	}
    53  	return Hex2Bytes(s)
    54  }
    55  
    56  // CopyBytes returns an exact copy of the provided bytes.
    57  func CopyBytes(b []byte) (copiedBytes []byte) {
    58  	if b == nil {
    59  		return nil
    60  	}
    61  	copiedBytes = make([]byte, len(b))
    62  	copy(copiedBytes, b)
    63  
    64  	return
    65  }
    66  
    67  // hasHexPrefix validates str begins with '0x' or '0X'.
    68  func hasHexPrefix(str string) bool {
    69  	return len(str) >= 2 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X')
    70  }
    71  
    72  // isHexCharacter returns bool of c being a valid hexadecimal.
    73  func isHexCharacter(c byte) bool {
    74  	return ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F')
    75  }
    76  
    77  // isHex validates whether each byte is valid hexadecimal string.
    78  func isHex(str string) bool {
    79  	if len(str)%2 != 0 {
    80  		return false
    81  	}
    82  	for _, c := range []byte(str) {
    83  		if !isHexCharacter(c) {
    84  			return false
    85  		}
    86  	}
    87  	return true
    88  }
    89  
    90  // Bytes2Hex returns the hexadecimal encoding of d.
    91  func Bytes2Hex(d []byte) string {
    92  	return hex.EncodeToString(d)
    93  }
    94  
    95  // Hex2Bytes returns the bytes represented by the hexadecimal string str.
    96  func Hex2Bytes(str string) []byte {
    97  	h, _ := hex.DecodeString(str)
    98  	return h
    99  }
   100  
   101  // Hex2BytesFixed returns bytes of a specified fixed length flen.
   102  func Hex2BytesFixed(str string, flen int) []byte {
   103  	h, _ := hex.DecodeString(str)
   104  	if len(h) == flen {
   105  		return h
   106  	} else {
   107  		if len(h) > flen {
   108  			return h[len(h)-flen:]
   109  		} else {
   110  			hh := make([]byte, flen)
   111  			copy(hh[flen-len(h):flen], h[:])
   112  			return hh
   113  		}
   114  	}
   115  }
   116  
   117  // RightPadBytes zero-pads slice to the right up to length l.
   118  func RightPadBytes(slice []byte, l int) []byte {
   119  	if l <= len(slice) {
   120  		return slice
   121  	}
   122  
   123  	padded := make([]byte, l)
   124  	copy(padded, slice)
   125  
   126  	return padded
   127  }
   128  
   129  // LeftPadBytes zero-pads slice to the left up to length l.
   130  func LeftPadBytes(slice []byte, l int) []byte {
   131  	if l <= len(slice) {
   132  		return slice
   133  	}
   134  
   135  	padded := make([]byte, l)
   136  	copy(padded[l-len(slice):], slice)
   137  
   138  	return padded
   139  }
   140  
   141  // TrimLeftZeroes returns a subslice of s without leading zeroes
   142  func TrimLeftZeroes(s []byte) []byte {
   143  	idx := 0
   144  	for ; idx < len(s); idx++ {
   145  		if s[idx] != 0 {
   146  			break
   147  		}
   148  	}
   149  	return s[idx:]
   150  }
   151  
   152  // TrimRightZeroes returns a subslice of s without trailing zeroes
   153  func TrimRightZeroes(s []byte) []byte {
   154  	idx := len(s)
   155  	for ; idx > 0; idx-- {
   156  		if s[idx-1] != 0 {
   157  			break
   158  		}
   159  	}
   160  	return s[:idx]
   161  }
   162  
   163  func MakeRandomBytes(n int) []byte {
   164  	s := make([]byte, n)
   165  	_, err := io.ReadFull(rand.Reader, s)
   166  	if err != nil {
   167  		return nil
   168  	}
   169  	return s
   170  }
   171  
   172  // IntToByteLittleEndian encodes a number as little endian uint64
   173  func Int64ToByteLittleEndian(num uint64) []byte {
   174  	enc := make([]byte, 8)
   175  	binary.LittleEndian.PutUint64(enc, num)
   176  
   177  	return enc
   178  }
   179  
   180  // Int64ToByteBigEndian encodes a number as big endian uint64
   181  func Int64ToByteBigEndian(number uint64) []byte {
   182  	enc := make([]byte, 8)
   183  	binary.BigEndian.PutUint64(enc, number)
   184  
   185  	return enc
   186  }
   187  
   188  type Entry struct {
   189  	Key, Val []byte
   190  }
   191  
   192  // CreateEntries creates random key/value pairs.
   193  func CreateEntries(entryNum int) []Entry {
   194  	entries := make([]Entry, entryNum)
   195  	for i := 0; i < entryNum; i++ {
   196  		entries[i] = Entry{Key: MakeRandomBytes(256), Val: MakeRandomBytes(300)}
   197  	}
   198  	return entries
   199  }