viem-goviem-go

slice

Returns a section of a byte slice or hex string given start/end byte offsets

slice

Returns a section of a byte slice or hex string given start/end byte offsets.

Import

import "github.com/ChefBingbong/viem-go/utils/data"

Usage

import "github.com/ChefBingbong/viem-go/utils/data"
// Slice bytes
result, _ := data.SliceBytes([]byte{0x01, 0x02, 0x03, 0x04}, 1, 3)
// []byte{0x02, 0x03}
// Slice hex string
hexResult, _ := data.SliceHex("0x01020304", 1, 3)
// "0x0203"
// Slice from start to end
fromStart, _ := data.SliceBytesStart([]byte{0x01, 0x02, 0x03}, 1)
// []byte{0x02, 0x03}

Returns

  • Type: ([]byte, error) for SliceBytes, (string, error) for SliceHex

The sliced section. Returns an error if the start offset is out of bounds.

Parameters

value (required)

  • Type: []byte for SliceBytes, string for SliceHex

The byte slice or hex string to slice.

result, _ := data.SliceBytes([]byte{0x01, 0x02, 0x03, 0x04}, 1, 3)

start (required)

  • Type: int

The start byte offset (inclusive). Use 0 for the beginning. Negative values are treated as 0.

// Start from byte 1
result, _ := data.SliceBytes([]byte{0x01, 0x02, 0x03, 0x04}, 1, 3)
// []byte{0x02, 0x03}
// Start from beginning
result, _ := data.SliceBytes([]byte{0x01, 0x02, 0x03, 0x04}, 0, 2)
// []byte{0x01, 0x02}

end (required)

  • Type: int

The end byte offset (exclusive). Use 0 or a value greater than the length to slice to the end.

// Slice from byte 1 to byte 3 (exclusive)
result, _ := data.SliceBytes([]byte{0x01, 0x02, 0x03, 0x04}, 1, 3)
// []byte{0x02, 0x03}
// Slice to the end
result, _ := data.SliceBytes([]byte{0x01, 0x02, 0x03}, 1, 0)
// []byte{0x02, 0x03}

opts.strict (optional)

  • Type: bool
  • Default: false

If true, validates that the slice produces the expected size.

// Strict mode validates result size
result, err := data.SliceBytes(
[]byte{0x01, 0x02, 0x03},
0,
2,
data.SliceOptions{Strict: true},
)
// []byte{0x01, 0x02}, nil

Convenience Functions

SliceBytesStart

Slices from a start position to the end of the value:

result, _ := data.SliceBytesStart([]byte{0x01, 0x02, 0x03}, 1)
// []byte{0x02, 0x03}

SliceHexStart

Slices a hex string from a start position to the end:

result, _ := data.SliceHexStart("0x01020304", 1)
// "0x020304"