Debian Codegraph @

sort.go

raw symbols SCIP
1 package csv
2
3 import (
4 "fmt"
5 "github.com/wildducktheories/go-csv/utils"
6 "sort"
7 )
8
9 // An adapter that converts a slice of CSV records into an instance of sort.Interface using the
10 // specified comparators, in order, to compare records.
11 type Sortable struct {
12 Keys []string
13 Data []Record
14 Comparators []SortComparator
15 }
16
17 // An implementation of sort.Interface.Len()
18 func (b *Sortable) Len() int {
19 return len(b.Data)
20 }
21
22 // An implementation of sort.Interface.Swap()
23 func (b *Sortable) Swap(i, j int) {
24 b.Data[i], b.Data[j] = b.Data[j], b.Data[i]
25 }
26
27 // An implementation of sort.Interface.Less()
28 func (b *Sortable) Less(i, j int) bool {
29 for _, c := range b.Comparators {
30 if c(i, j) {
31 return true
32 } else if c(j, i) {
33 return false
34 }
35 }
36 return false
37 }
38
39 // Derives a SortProcess from the receiver. Note that it isn't safe
40 // to run multiple processes derived from the same Sortable at the same
41 // time.
42 func (b *Sortable) AsSortProcess() *SortProcess {
43 return &SortProcess{
44 Keys: b.Keys,
45 AsSort: func(data []Record) sort.Interface {
46 b.Data = data
47 return b
48 },
49 }
50 }
51
52 // Answer a comparator for the field named k, using the string comparator specified by less.
53 func (b *Sortable) Comparator(k string, less StringComparator) SortComparator {
54 return func(i, j int) bool {
55 return less(b.Data[i].Get(k), b.Data[j].Get(k))
56 }
57 }
58
59 // Answers true if l is less than r, according to a lexical comparison
60 func LessStrings(l, r string) bool {
61 return l < r
62 }
63
64 // Answers true if the numeric value of l is less than r according to a numerical
65 // comparison (if l and r are both parseable as floats) or according to a lexical
66 // comparison otherwise.
67 func LessNumericStrings(l, r string) bool {
68 var lf, rf float64
69 if _, err := fmt.Sscanf(l, "%f", &lf); err != nil {
70 return LessStrings(l, r)
71 } else if _, err := fmt.Sscanf(r, "%f", &rf); err != nil {
72 return LessStrings(l, r)
73 } else {
74 return lf < rf
75 }
76 }
77
78 // Specifies the keys to be used by a CSV sort.
79 type SortKeys struct {
80 Keys []string // list of columns to use for sorting
81 Numeric []string // list of columns for which a numerical string comparison is used
82 Reversed []string // list of columns for which the comparison is reversed
83 }
84
85 // Answer a Sort for the specified slice of CSV records, using the comparators derived from the
86 // keys specified by the receiver.
87 func (p *SortKeys) AsSort(data []Record) sort.Interface {
88 return p.AsSortable(data)
89 }
90
91 // Answer a Sortable whose comparators have been initialized with string or numerical string
92 // comparators according the specification of the receiver.
93 func (p *SortKeys) AsSortable(data []Record) *Sortable {
94 bk := &Sortable{
95 Keys: p.Keys,
96 Data: data,
97 Comparators: make([]SortComparator, len(p.Keys), len(p.Keys)),
98 }
99 for x, c := range p.AsRecordComparators() {
100 c := c
101 bk.Comparators[x] = func(i, j int) bool {
102 return c(bk.Data[i], bk.Data[j])
103 }
104 }
105 return bk
106 }
107
108 // Derive a SortProcess from the receiver.
109 func (p *SortKeys) AsSortProcess() *SortProcess {
110 return &SortProcess{
111 AsSort: p.AsSort,
112 Keys: p.Keys,
113 }
114 }
115
116 // Derive a StringProjection from the sort keys.
117 func (p *SortKeys) AsStringProjection() StringProjection {
118 return func(r Record) []string {
119 result := make([]string, len(p.Keys))
120 for i, k := range p.Keys {
121 result[i] = r.Get(k)
122 }
123 return result
124 }
125 }
126
127 // Answers a comparator that can compare two slices.
128 func (p *SortKeys) AsStringSliceComparator() StringSliceComparator {
129 numeric := utils.NewIndex(p.Numeric)
130 reverseIndex := utils.NewIndex(p.Reversed)
131 comparators := make([]StringComparator, len(p.Keys))
132 for i, k := range p.Keys {
133 if numeric.Contains(k) {
134 comparators[i] = LessNumericStrings
135 } else {
136 comparators[i] = LessStrings
137 }
138 if reverseIndex.Contains(k) {
139 f := comparators[i]
140 comparators[i] = func(l, r string) bool {
141 return !f(l, r)
142 }
143 }
144 }
145 return AsStringSliceComparator(comparators)
146 }
147
148 // Answers a slice of comparators that can compare two records.
149 func (p *SortKeys) AsRecordComparators() []RecordComparator {
150 numeric := utils.NewIndex(p.Numeric)
151 reverseIndex := utils.NewIndex(p.Reversed)
152 comparators := make([]RecordComparator, len(p.Keys))
153 for i, k := range p.Keys {
154 k := k
155 if numeric.Contains(k) {
156 comparators[i] = func(l, r Record) bool {
157 return LessNumericStrings(l.Get(k), r.Get(k))
158 }
159 } else {
160 comparators[i] = func(l, r Record) bool {
161 return LessStrings(l.Get(k), r.Get(k))
162 }
163 }
164 if reverseIndex.Contains(k) {
165 f := comparators[i]
166 comparators[i] = func(l, r Record) bool {
167 return !f(l, r)
168 }
169 }
170 }
171 return comparators
172 }
173
174 // Answers a comparator that can compare two records.
175 func (p *SortKeys) AsRecordComparator() RecordComparator {
176 return AsRecordComparator(p.AsRecordComparators())
177 }
178
179 // A process, which given a CSV reader, sorts a stream of Records using the sort
180 // specified by the result of the AsSort function. The stream is checked to verify
181 // that it has the specified keys.
182 type SortProcess struct {
183 AsSort func(data []Record) sort.Interface
184 Keys []string
185 }
186
187 // Run the sort process specified by the receiver against the specified CSV reader,
188 // writing the results to a Writer constructed from the specified builder.
189 // Termination of the sort process is signalled by writing nil or at most one error
190 // into the specified error channel.
191 // It is an error to apply the receiving process to a reader whose Header is not
192 // a strict superset of the receiver's Keys.
193 func (p *SortProcess) Run(reader Reader, builder WriterBuilder, errCh chan<- error) {
194
195 errCh <- func() (err error) {
196 defer reader.Close()
197
198 keys := p.Keys
199
200 // get the data header
201 dataHeader := reader.Header()
202 writer := builder(dataHeader)
203 defer writer.Close(err)
204
205 _, x, _ := utils.Intersect(keys, dataHeader)
206 if len(x) != 0 {
207 return fmt.Errorf("invalid keys: %v", x)
208 }
209
210 if all, err := ReadAll(reader); err != nil {
211 return err
212 } else {
213
214 sort.Sort(p.AsSort(all))
215
216 for _, e := range all {
217 if err := writer.Write(e); err != nil {
218 return err
219 }
220 }
221 }
222 return nil
223 }()
224 }