github.com/iotexproject/iotex-core@v1.14.1-rc1/pkg/util/byteutil/byteutil.go (about)

     1  // Copyright (c) 2022 IoTeX Foundation
     2  // This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability
     3  // or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed.
     4  // This source code is governed by Apache License 2.0 that can be found in the LICENSE file.
     5  
     6  package byteutil
     7  
     8  import (
     9  	"encoding/binary"
    10  
    11  	"github.com/iotexproject/iotex-core/pkg/enc"
    12  )
    13  
    14  // Uint32ToBytes converts a uint32 to 4 bytes in little-endian
    15  func Uint32ToBytes(value uint32) []byte {
    16  	bytes := make([]byte, 4)
    17  	enc.MachineEndian.PutUint32(bytes, value)
    18  	return bytes
    19  }
    20  
    21  // Uint64ToBytes converts a uint64 to 8 bytes in little-endian
    22  func Uint64ToBytes(value uint64) []byte {
    23  	bytes := make([]byte, 8)
    24  	enc.MachineEndian.PutUint64(bytes, value)
    25  	return bytes
    26  }
    27  
    28  // BytesToUint64 converts 8 bytes to uint64 in little-endian
    29  func BytesToUint64(value []byte) uint64 {
    30  	return enc.MachineEndian.Uint64(value)
    31  }
    32  
    33  // Must is a helper wraps a call to a function returning ([]byte, error) and panics if the error is not nil.
    34  func Must(d []byte, err error) []byte {
    35  	if err != nil {
    36  		panic(err)
    37  	}
    38  	return d
    39  }
    40  
    41  // convert number sequence 0, 1, 2, ... n to big-endian results in byte-sorted []byte slice
    42  // we leverage this nice property to search/iterate action index stored within a bucket
    43  
    44  // Uint32ToBytesBigEndian converts a uint32 to 4 bytes in big-endian
    45  func Uint32ToBytesBigEndian(value uint32) []byte {
    46  	bytes := make([]byte, 4)
    47  	binary.BigEndian.PutUint32(bytes, value)
    48  	return bytes
    49  }
    50  
    51  // Uint64ToBytesBigEndian converts a uint64 to 8 bytes in big-endian
    52  func Uint64ToBytesBigEndian(value uint64) []byte {
    53  	bytes := make([]byte, 8)
    54  	binary.BigEndian.PutUint64(bytes, value)
    55  	return bytes
    56  }
    57  
    58  // BytesToUint64BigEndian converts 8 bytes to uint64 in big-endian
    59  func BytesToUint64BigEndian(value []byte) uint64 {
    60  	return binary.BigEndian.Uint64(value)
    61  }
    62  
    63  // BoolToByte converts bool to byte
    64  func BoolToByte(value bool) byte {
    65  	if value {
    66  		return 1
    67  	}
    68  	return 0
    69  }