forked from jbowens/codenames
-
Notifications
You must be signed in to change notification settings - Fork 1
/
wordset.go
64 lines (54 loc) · 1.12 KB
/
wordset.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package codenames
import (
"crypto/sha1"
"errors"
"fmt"
"io"
"sort"
"strings"
"sync"
)
type wordSetID [sha1.Size]byte
func (i wordSetID) String() string {
return fmt.Sprintf("%x", i[:])
}
type WordSets struct {
mu sync.Mutex
byID map[wordSetID][]string
}
func (ws *WordSets) init() {
if ws.byID == nil {
ws.byID = make(map[wordSetID][]string)
}
}
func (ws *WordSets) Canonicalize(words []string) (wordSetID, []string, error) {
ws.mu.Lock()
defer ws.mu.Unlock()
ws.init()
set := map[string]bool{}
for _, w := range words {
set[strings.TrimSpace(strings.ToUpper(w))] = true
}
if len(set) > 0 && len(set) < 25 {
return wordSetID{}, nil, errors.New("need at least 25 words")
}
words = words[:0]
for w := range set {
words = append(words, w)
}
sort.Strings(words)
// Calculate the word set ID, a hash of the canonicalized word set.
h := sha1.New()
for _, w := range words {
io.WriteString(h, w)
h.Write([]byte{0x00})
}
idBytes := h.Sum(nil)
var id wordSetID
copy(id[:], idBytes)
if interned, ok := ws.byID[id]; ok {
return id, interned, nil
}
ws.byID[id] = words
return id, words, nil
}