word.go

 1package uniseg
 2
 3import "unicode/utf8"
 4
 5// FirstWord returns the first word found in the given byte slice according to
 6// the rules of [Unicode Standard Annex #29, Word Boundaries]. This function can
 7// be called continuously to extract all words from a byte slice, as illustrated
 8// in the example below.
 9//
10// If you don't know the current state, for example when calling the function
11// for the first time, you must pass -1. For consecutive calls, pass the state
12// and rest slice returned by the previous call.
13//
14// The "rest" slice is the sub-slice of the original byte slice "b" starting
15// after the last byte of the identified word. If the length of the "rest" slice
16// is 0, the entire byte slice "b" has been processed. The "word" byte slice is
17// the sub-slice of the input slice containing the identified word.
18//
19// Given an empty byte slice "b", the function returns nil values.
20//
21// [Unicode Standard Annex #29, Word Boundaries]: http://unicode.org/reports/tr29/#Word_Boundaries
22func FirstWord(b []byte, state int) (word, rest []byte, newState int) {
23	// An empty byte slice returns nothing.
24	if len(b) == 0 {
25		return
26	}
27
28	// Extract the first rune.
29	r, length := utf8.DecodeRune(b)
30	if len(b) <= length { // If we're already past the end, there is nothing else to parse.
31		return b, nil, wbAny
32	}
33
34	// If we don't know the state, determine it now.
35	if state < 0 {
36		state, _ = transitionWordBreakState(state, r, b[length:], "")
37	}
38
39	// Transition until we find a boundary.
40	var boundary bool
41	for {
42		r, l := utf8.DecodeRune(b[length:])
43		state, boundary = transitionWordBreakState(state, r, b[length+l:], "")
44
45		if boundary {
46			return b[:length], b[length:], state
47		}
48
49		length += l
50		if len(b) <= length {
51			return b, nil, wbAny
52		}
53	}
54}
55
56// FirstWordInString is like [FirstWord] but its input and outputs are strings.
57func FirstWordInString(str string, state int) (word, rest string, newState int) {
58	// An empty byte slice returns nothing.
59	if len(str) == 0 {
60		return
61	}
62
63	// Extract the first rune.
64	r, length := utf8.DecodeRuneInString(str)
65	if len(str) <= length { // If we're already past the end, there is nothing else to parse.
66		return str, "", wbAny
67	}
68
69	// If we don't know the state, determine it now.
70	if state < 0 {
71		state, _ = transitionWordBreakState(state, r, nil, str[length:])
72	}
73
74	// Transition until we find a boundary.
75	var boundary bool
76	for {
77		r, l := utf8.DecodeRuneInString(str[length:])
78		state, boundary = transitionWordBreakState(state, r, nil, str[length+l:])
79
80		if boundary {
81			return str[:length], str[length:], state
82		}
83
84		length += l
85		if len(str) <= length {
86			return str, "", wbAny
87		}
88	}
89}