package lattice import ( "strings" "unicode" "golang.org/x/text/unicode/norm" ) // Normalize lowercases and NFC-normalizes a word. // Strips surrounding whitespace, quotes, and combining diacritical marks // (accents like ́ that appear in Bulgarian dictionary entries). // Bulgarian stays Cyrillic. No transliteration. func Normalize(word string) []byte { w := strings.TrimSpace(word) w = strings.Trim(w, "\"'`") w = strings.ToLower(w) // NFC first, then strip combining marks (category Mn). b := norm.NFC.Bytes([]byte(w)) clean := make([]byte, 0, len(b)) for i := 0; i < len(b); { r, size := decodeRune(b[i:]) if !unicode.Is(unicode.Mn, r) { clean = append(clean, b[i:i+size]...) } i += size } return clean } // decodeRune decodes one UTF-8 rune from b. func decodeRune(b []byte) (rune, int) { if len(b) == 0 { return 0, 0 } c := b[0] if c < 0x80 { return rune(c), 1 } var r rune var size int switch { case c&0xE0 == 0xC0: r, size = rune(c&0x1F), 2 case c&0xF0 == 0xE0: r, size = rune(c&0x0F), 3 case c&0xF8 == 0xF0: r, size = rune(c&0x07), 4 default: return 0xFFFD, 1 } if len(b) < size { return 0xFFFD, 1 } for i := 1; i < size; i++ { r = r<<6 | rune(b[i]&0x3F) } return r, size }