Split Binary Frames With bytes.Split

Slice one buffer into NUL separated records with bytes.Split and rebuild with bytes.Join, then prove the framing lossless with bytes.Equal.

GoData Integrity

Code

gosnippet
21 lines
package main

import (
	"bytes"
	"fmt"
)

func main() {
	// 0x00 分隔的记录帧:一条缓冲里塞了多条消息,空段也是合法记录
	stream := []byte("heartbeat\x00readings\x00\x00checksum-ok\x00")

	records := bytes.Split(stream, []byte{0})
	fmt.Println("records:", len(records))
	for i, r := range records {
		fmt.Printf("%d: %q\n", i, string(r))
	}

	// 重新拼回后逐字节比较:分帧与重组零损耗
	rebuilt := bytes.Join(records, []byte{0})
	fmt.Println("lossless:", bytes.Equal(rebuilt, stream))
}

NUL bytes as record separators

stream := []byte("heartbeat\x00readings\x00\x00checksum-ok\x00") packs four messages into one buffer with 0x00 separators — and the empty segment between the second and third separators is a legitimate record, per the comment. bytes.Split(stream, []byte{0}) returns the segments as independent byte slices without copying the content.

What the split produces

records: 5
0: "heartbeat"
1: "readings"
2: ""
3: "checksum-ok"
4: ""
lossless: true

Five segments come out — the trailing separator contributes the final empty slice, and fmt.Printf("%d: %q\n", i, string(r)) renders each with %q quoting. bytes.Join(records, []byte{0}) reassembles with the same separator, and bytes.Equal(rebuilt, stream) proves the framing is lossless: true byte for byte, empties included.

The line that proves the round trip

rebuilt := bytes.Join(records, []byte{0})
fmt.Println("lossless:", bytes.Equal(rebuilt, stream))

For a framing layer this equality is the contract: a codec that split and rejoined correctly reproduces the stream exactly, including the records that carry no payload at all.

Interactive Tools for This Topic

FAQ

What does Split Binary Frames With bytes.Split print when run?
Run it as a complete program — the output lines carry labels such as `records:`, `lossless:`.