lexicon.go raw

   1  package lattice
   2  
   3  // LexEntry is 32 bytes of surface form data.
   4  // Short forms (≤23 bytes UTF-8) stored inline.
   5  // Longer forms use the string pool via PoolOffset.
   6  type LexEntry struct {
   7  	Form       [24]byte //  24: inline UTF-8 (null-terminated if shorter)
   8  	FormLen    uint8    //   1: byte length of form
   9  	Flags      uint8    //   1: bit 0 = overflow (form in string pool)
  10  	_pad       uint16   //   2
  11  	PoolOffset uint32   //   4: offset into Tree.StringPool if overflow
  12  } // 32 bytes
  13  
  14  const lexFlagOverflow uint8 = 0x01
  15  
  16  // SetForm stores a surface form in the LexEntry.
  17  // If it fits in 24 bytes, stores inline. Otherwise sets overflow flag.
  18  func (e *LexEntry) SetForm(form string, pool *[]byte) {
  19  	b := []byte(form)
  20  	if len(b) <= 24 {
  21  		copy(e.Form[:], b)
  22  		e.FormLen = uint8(len(b))
  23  		e.Flags &^= lexFlagOverflow
  24  	} else {
  25  		// Store first 24 bytes inline as preview, full form in pool.
  26  		copy(e.Form[:], b[:24])
  27  		e.FormLen = uint8(len(b))
  28  		e.Flags |= lexFlagOverflow
  29  		e.PoolOffset = uint32(len(*pool))
  30  		*pool = append(*pool, b...)
  31  	}
  32  }
  33  
  34  // GetForm returns the surface form string.
  35  func (e *LexEntry) GetForm(pool []byte) string {
  36  	if e.Flags&lexFlagOverflow != 0 {
  37  		end := e.PoolOffset + uint32(e.FormLen)
  38  		return string(pool[e.PoolOffset:end])
  39  	}
  40  	return string(e.Form[:e.FormLen])
  41  }
  42