// Week 4 – Character encoding in Go: byte, rune, UTF-8
// Run: go run ./w04/encoding
package main

import (
	"fmt"
	"unicode/utf8"
)

func main() {
	s := "Aé世😀"

	// A Go string is a UTF-8 encoded byte sequence.
	fmt.Println("len(s)                 =", len(s))                    // 10 bytes
	fmt.Println("utf8.RuneCountInString =", utf8.RuneCountInString(s)) // 4 characters

	// range over a string gives RUNES (code points), with the byte index
	for i, r := range s {
		fmt.Printf("  byte index %d: %c  U+%04X  (%d bytes)\n", i, r, r, utf8.RuneLen(r))
	}

	// Indexing gives a byte – we can index into the "middle" of a multi-byte character!
	fmt.Print("byte by byte: ")
	for i := 0; i < len(s); i++ {
		fmt.Printf("%02X ", s[i])
	}
	fmt.Println()

	// Safe character-by-character processing: []rune
	r := []rune(s)
	fmt.Println("length of []rune:", len(r), ", r[2] =", string(r[2]))

	// ASCII arithmetic
	c := 'c'
	fmt.Println("'c' - 'a' =", c-'a', "  '7' - '0' =", '7'-'0')
}
