UTF-8 ValidString Rejects Bad Bytes

Screen text with utf8.ValidString, then walk runes with DecodeRuneInString to locate the first invalid byte and report its offset.

GoData Integrity

Code

gosnippet
26 lines
package main

import (
	"fmt"
	"unicode/utf8"
)

func main() {
	good := "héllo, 世界"
	fmt.Println("valid:", utf8.ValidString(good))
	fmt.Println("runes:", utf8.RuneCountInString(good), "bytes:", len(good))

	// 0xff never forms a valid UTF-8 sequence
	bad := string([]byte{'o', 'k', 0xff, '!'})
	fmt.Println("valid bad:", utf8.ValidString(bad))

	// decode runes until RuneError with width 1 marks the bad byte
	for i := 0; i < len(bad); {
		r, size := utf8.DecodeRuneInString(bad[i:])
		if r == utf8.RuneError && size == 1 {
			fmt.Printf("invalid byte at %d: %#x\n", i, bad[i])
		}
		i += size
	}
	fmt.Println("rune count:", utf8.RuneCountInString(bad))
}

What the code does

UTF-8 ValidString Rejects Bad Bytes keeps everything in the function main.

Repetition is confined to for i := 0; i < len(bad); — the rest of the file is straight-line.

What to watch for

  • The runtime is the only requirement — no packages, no install.

Applying it

The file announces its steps in the output: valid:, runes:, valid bad:.

Statements that matter

r, size := utf8.DecodeRuneInString(bad[i:])

Interactive Tools for This Topic

FAQ

What does UTF-8 ValidString Rejects Bad Bytes print when run?
Running the file directly is enough — expect labeled output lines such as `valid:`, `runes:`, `valid bad:`.