Discard Skips Bytes Without Buffering

Skip framed payloads with bufio.Reader.Discard, which drops n bytes without copying them through user buffers and errors on short frames.

GoData Integrity

Code

gosnippet
46 lines
package main

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"strings"
)

// 帧格式:2 字节小端长度 + 载荷;扫描器只关心帧边界,不解码载荷
func scanFrames(wire string) ([]string, error) {
	reader := bufio.NewReader(strings.NewReader(wire))
	var frames []string
	for {
		var header [2]byte
		if _, err := io.ReadFull(reader, header[:]); err != nil {
			if err == io.EOF {
				return frames, nil
			}
			return nil, err
		}
		size := int(header[0]) | int(header[1])<<8
		// Discard 丢弃 n 个字节:不经过用户缓冲区,适合跳过载荷、填充或坏帧
		if _, err := reader.Discard(size); err != nil {
			return nil, err
		}
		frames = append(frames, fmt.Sprintf("frame of %d bytes", size))
	}
}

func main() {
	var wire bytes.Buffer
	wire.Write([]byte{4, 0})
	wire.WriteString("ping")
	wire.Write([]byte{9, 0})
	wire.WriteString("subscribe")

	frames, err := scanFrames(wire.String())
	if err != nil {
		panic(err)
	}
	for _, frame := range frames {
		fmt.Println(frame)
	}
}

How it works

Discard Skips Bytes Without Buffering keeps everything in the functions scanFrames and main.

Repetition is confined to for — the rest of the file is straight-line. Failures are values here: 3 sites check err and decide instead of letting one propagate.

What to watch for

  • No setup phase: the platform supplies every API the file touches.
  • Error values are returned, not thrown — every call site must inspect err before using the other return values.

Putting it to use

The most load-bearing signature is func scanFrames(wire string) ([]string, error)

Running the file executes main, which drives scanFrames in order.

The core lines of the flow

frames = append(frames, fmt.Sprintf("frame of %d bytes", size))
for _, frame := range frames {
	fmt.Println(frame)
}
if err != nil {
	panic(err)
}

Interactive Tools for This Topic

FAQ

How are errors reported?
The Go way: `err` comes back from each call, and 3 checkpoints here test it before proceeding.
How do you run Discard Skips Bytes Without Buffering?
Nothing to install first — run the file and the program does the rest.