normalize.go raw

   1  package lattice
   2  
   3  import (
   4  	"strings"
   5  	"unicode"
   6  
   7  	"golang.org/x/text/unicode/norm"
   8  )
   9  
  10  // Normalize lowercases and NFC-normalizes a word.
  11  // Strips surrounding whitespace, quotes, and combining diacritical marks
  12  // (accents like ́ that appear in Bulgarian dictionary entries).
  13  // Bulgarian stays Cyrillic. No transliteration.
  14  func Normalize(word string) []byte {
  15  	w := strings.TrimSpace(word)
  16  	w = strings.Trim(w, "\"'`")
  17  	w = strings.ToLower(w)
  18  
  19  	// NFC first, then strip combining marks (category Mn).
  20  	b := norm.NFC.Bytes([]byte(w))
  21  	clean := make([]byte, 0, len(b))
  22  	for i := 0; i < len(b); {
  23  		r, size := decodeRune(b[i:])
  24  		if !unicode.Is(unicode.Mn, r) {
  25  			clean = append(clean, b[i:i+size]...)
  26  		}
  27  		i += size
  28  	}
  29  	return clean
  30  }
  31  
  32  // decodeRune decodes one UTF-8 rune from b.
  33  func decodeRune(b []byte) (rune, int) {
  34  	if len(b) == 0 {
  35  		return 0, 0
  36  	}
  37  	c := b[0]
  38  	if c < 0x80 {
  39  		return rune(c), 1
  40  	}
  41  	var r rune
  42  	var size int
  43  	switch {
  44  	case c&0xE0 == 0xC0:
  45  		r, size = rune(c&0x1F), 2
  46  	case c&0xF0 == 0xE0:
  47  		r, size = rune(c&0x0F), 3
  48  	case c&0xF8 == 0xF0:
  49  		r, size = rune(c&0x07), 4
  50  	default:
  51  		return 0xFFFD, 1
  52  	}
  53  	if len(b) < size {
  54  		return 0xFFFD, 1
  55  	}
  56  	for i := 1; i < size; i++ {
  57  		r = r<<6 | rune(b[i]&0x3F)
  58  	}
  59  	return r, size
  60  }
  61