pad
Pads a byte slice or hex string with leading or trailing zeros
pad
Pads a byte slice or hex string with leading or trailing zeros to reach a target size.
Import
import "github.com/ChefBingbong/viem-go/utils/data"Usage
By default, Pad pads a value with leading zeros up to 32 bytes.
import "github.com/ChefBingbong/viem-go/utils/data"
// Pad bytes (default: left, 32 bytes)result, _ := data.Pad([]byte{0xa4, 0xe1, 0x2a, 0x45})// []byte{0x00, 0x00, ..., 0xa4, 0xe1, 0x2a, 0x45} (32 bytes)
// Pad hex stringhexResult, _ := data.PadHex("0xa4e12a45", data.PadLeft, 32)// "0x00000000000000000000000000000000000000000000000000000000a4e12a45"
// Pad on the rightrightPadded, _ := data.PadBytes([]byte{0x01}, data.PadRight, 4)// []byte{0x01, 0x00, 0x00, 0x00}Returns
- Type:
([]byte, error)forPad/PadBytes,(string, error)forPadHex
The padded value. Returns an error if the input size exceeds the target size.
Parameters
bytes/hex (required)
- Type:
[]byteforPad/PadBytes,stringforPadHex
The byte slice or hex string to pad.
result, _ := data.PadBytes([]byte{0x01, 0x02}, data.PadLeft, 4)opts.dir (optional)
- Type:
data.PadDirection(PadLeftorPadRight) - Default:
PadLeft
The direction in which to pad the zeros – either leading (left) or trailing (right).
// Pad on the rightresult, _ := data.PadBytes( []byte{0xa4, 0xe1, 0x2a, 0x45}, data.PadRight, 8,)// []byte{0xa4, 0xe1, 0x2a, 0x45, 0x00, 0x00, 0x00, 0x00}
// Pad hex on the righthexResult, _ := data.PadHex("0xa4e12a45", data.PadRight, 8)// "0xa4e12a4500000000"opts.size (optional)
- Type:
int - Default:
32
Size (in bytes) of the target value.
// Pad to 16 bytesresult, _ := data.Pad([]byte{0x01}, data.PadOptions{ Size: 16,})// []byte{0x00, ..., 0x01} (16 bytes)
// Pad hex to 4 byteshexResult, _ := data.PadHex("0xa4e12a45", data.PadLeft, 4)// "0x00000000a4e12a45"Convenience Functions
PadLeftBytes / PadRightBytes
Convenience functions for padding bytes in a specific direction:
result, _ := data.PadLeftBytes([]byte{0x01}, 4)
// []byte{0x00, 0x00, 0x00, 0x01}
result, _ := data.PadRightBytes([]byte{0x01}, 4)
// []byte{0x01, 0x00, 0x00, 0x00}
PadLeftHex / PadRightHex
Convenience functions for padding hex strings in a specific direction:
result, _ := data.PadLeftHex("0x01", 4)
// "0x00000001"
result, _ := data.PadRightHex("0x01", 4)
// "0x01000000"