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).
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.