/
options.go
112 lines (93 loc) · 2.47 KB
/
options.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package kidwords
import (
"errors"
"fmt"
"github.com/dkotik/kidwords/dictionary"
)
// type SplitFunc func()
type SeparatorFunc func() []byte
type writerOptions struct {
separator SeparatorFunc
dictionary *dictionary.Dictionary
}
type WriterOption interface {
applyWriterOption(*writerOptions) error
}
type readerOptions struct {
// split SplitFunc
dictionary map[string]byte
}
type ReaderOption interface {
applyReaderOption(*readerOptions) error
}
type Option interface {
ReaderOption
WriterOption
}
type dictionaryOption struct {
dictionary *dictionary.Dictionary
}
func (d *dictionaryOption) validate() error {
if d == nil || d.dictionary == nil {
return errors.New("cannot use a <nil> dictionary")
}
return d.dictionary.Validate()
}
func (d *dictionaryOption) applyWriterOption(o *writerOptions) error {
if err := d.validate(); err != nil {
return err
}
if o.dictionary != nil {
return errors.New("dictionary is already set")
}
o.dictionary = d.dictionary
return nil
}
func (d *dictionaryOption) applyReaderOption(o *readerOptions) error {
if err := d.validate(); err != nil {
return err
}
if o.dictionary != nil {
return errors.New("dictionary is already set")
}
o.dictionary = d.dictionary.Reverse()
return nil
}
func WithDictionary(d *dictionary.Dictionary) Option {
return &dictionaryOption{dictionary: d}
}
type dictionaryFileOption string
func (d dictionaryFileOption) applyWriterOption(o *writerOptions) error {
if d == "" {
return errors.New("cannot use an empty dictionary file path")
}
dictionary, err := dictionary.LoadFile(string(d))
if err != nil {
return fmt.Errorf("cannot load dictionary %q: %w", d, err)
}
return (&dictionaryOption{dictionary: &dictionary}).applyWriterOption(o)
}
func (d dictionaryFileOption) applyReaderOption(o *readerOptions) error {
if d == "" {
return errors.New("cannot use an empty dictionary file path")
}
dictionary, err := dictionary.LoadFile(string(d))
if err != nil {
return fmt.Errorf("cannot load dictionary %q: %w", d, err)
}
return (&dictionaryOption{dictionary: &dictionary}).applyReaderOption(o)
}
type separatorOption SeparatorFunc
func (s separatorOption) applyWriterOption(o *writerOptions) error {
if s == nil {
return errors.New("cannot us a <nil> separator function")
}
if o.separator != nil {
return errors.New("separator function is already set")
}
o.separator = SeparatorFunc(s)
return nil
}
func WithSeparator(f SeparatorFunc) WriterOption {
return separatorOption(f)
}