Distinguish RuneError Bytes With DecodeRuneInString

Scan raw strings via utf8.DecodeRuneInString so invalid byte runs (RuneError with width 1) are separated from genuine U+FFFD runes (width 3).

GoData Integrity

Code

snippet
package main

import (
	"fmt"
	"unicode/utf8"
)

func inspectUTF8(s string) {
	fmt.Printf("input valid=%t bytes=%x\n", utf8.ValidString(s), s)
	for i := 0; i < len(s); {
		r, width := utf8.DecodeRuneInString(s[i:])
		if r == utf8.RuneError && width == 1 {
			fmt.Printf("  offset %d: invalid byte 0x%02x (width=1)\n", i, s[i])
		} else {
			fmt.Printf("  offset %d: rune %q U+%04X (width=%d)\n", i, r, r, width)
		}
		i += width
	}
}

func main() {
	// Contains genuine U+FFFD (3 bytes: ef bf bd) plus invalid raw byte 0xff
	sample := "ok-\ufffd-\xff!"
	inspectUTF8(sample)
}

Behavior overview — Distinguish RuneError Bytes With DecodeRuneInString

Start tracing control flow inside functions inspectUTF8 and main, doing all the work.

One loop does the cycling here: for i := 0; i < len(s);.

What to watch for

  • Sole prerequisite is the base runtime itself — no external downloads or packages.

Applying it

The entry-point signature is func inspectUTF8(s string)

The run prints input valid=, offset — each prefix names the step that produced it.

Start the program and main runs inspectUTF8 one after another.

Statements that matter

func main() {
	// Contains genuine U+FFFD (3 bytes: ef bf bd) plus invalid raw byte 0xff
	sample := "ok-\ufffd-\xff!"
	inspectUTF8(sample)
}

Interactive Tools for This Topic

FAQ

What does Distinguish RuneError Bytes With DecodeRuneInString print when run?
Invoke the file as-is — the `input valid=`, `offset` prefixes identify which step printed each line.