-
Notifications
You must be signed in to change notification settings - Fork 2
/
query.go
713 lines (598 loc) · 16.7 KB
/
query.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
package collection
import (
"context"
"errors"
"runtime"
"sync"
)
// Enumerable offers a means of easily converting into a channel. It is most
// useful for types where mutability is not in question.
type Enumerable[T any] interface {
Enumerate(ctx context.Context) Enumerator[T]
}
// Enumerator exposes a new syntax for querying familiar data structures.
type Enumerator[T any] <-chan T
// Predicate defines an interface for funcs that make some logical test.
type Predicate[T any] func(T) bool
// Transform defines a function which takes a value, and returns some value based on the original.
type Transform[T any, E any] func(T) E
// Unfolder defines a function which takes a single value, and exposes many of them as an Enumerator
type Unfolder[T any, E any] func(T) Enumerator[E]
type emptyEnumerable[T any] struct{}
var (
errNoElements = errors.New("enumerator encountered no elements")
errMultipleElements = errors.New("enumerator encountered multiple elements")
)
// IsErrorNoElements determines whethr or not the given error is the result of no values being
// returned when one or more were expected.
func IsErrorNoElements(err error) bool {
return err == errNoElements
}
// IsErrorMultipleElements determines whether or not the given error is the result of multiple values
// being returned when one or zero were expected.
func IsErrorMultipleElements(err error) bool {
return err == errMultipleElements
}
// Identity returns a trivial Transform which applies no operation on the value.
func Identity[T any]() Transform[T, T] {
return func(value T) T {
return value
}
}
func Empty[T any]() Enumerable[T] {
return &emptyEnumerable[T]{}
}
func (e emptyEnumerable[T]) Enumerate(ctx context.Context) Enumerator[T] {
results := make(chan T)
close(results)
return results
}
// All tests whether or not all items present in an Enumerable meet a criteria.
func All[T any](subject Enumerable[T], p Predicate[T]) bool {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
return subject.Enumerate(ctx).All(p)
}
// All tests whether or not all items present meet a criteria.
func (iter Enumerator[T]) All(p Predicate[T]) bool {
for entry := range iter {
if !p(entry) {
return false
}
}
return true
}
// Any tests an Enumerable to see if there are any elements present.
func Any[T any](iterator Enumerable[T]) bool {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
for range iterator.Enumerate(ctx) {
return true
}
return false
}
// Anyp tests an Enumerable to see if there are any elements present that meet a criteria.
func Anyp[T any](iterator Enumerable[T], p Predicate[T]) bool {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
for element := range iterator.Enumerate(ctx) {
if p(element) {
return true
}
}
return false
}
type EnumerableSlice[T any] []T
func (f EnumerableSlice[T]) Enumerate(ctx context.Context) Enumerator[T] {
results := make(chan T)
go func() {
defer close(results)
for _, entry := range f {
select {
case results <- entry:
break
case <-ctx.Done():
return
}
}
}()
return results
}
// AsEnumerable allows for easy conversion of a slice to a re-usable Enumerable object.
func AsEnumerable[T any](entries ...T) Enumerable[T] {
return EnumerableSlice[T](entries)
}
// AsEnumerable stores the results of an Enumerator so the results can be enumerated over repeatedly.
func (iter Enumerator[T]) AsEnumerable() Enumerable[T] {
return EnumerableSlice[T](iter.ToSlice())
}
// Count iterates over a list and keeps a running tally of the number of elements which satisfy a predicate.
func Count[T any](iter Enumerable[T], p Predicate[T]) int {
return iter.Enumerate(context.Background()).Count(p)
}
// Count iterates over a list and keeps a running tally of the number of elements
// satisfy a predicate.
func (iter Enumerator[T]) Count(p Predicate[T]) int {
tally := 0
for entry := range iter {
if p(entry) {
tally++
}
}
return tally
}
// CountAll iterates over a list and keeps a running tally of how many it's seen.
func CountAll[T any](iter Enumerable[T]) int {
return iter.Enumerate(context.Background()).CountAll()
}
// CountAll iterates over a list and keeps a running tally of how many it's seen.
func (iter Enumerator[T]) CountAll() int {
tally := 0
for range iter {
tally++
}
return tally
}
// Discard reads an enumerator to the end but does nothing with it.
// This method should be used in circumstances when it doesn't make sense to explicitly cancel the Enumeration.
func (iter Enumerator[T]) Discard() {
for range iter {
// Intentionally Left Blank
}
}
// ElementAt retreives an item at a particular position in an Enumerator.
func ElementAt[T any](iter Enumerable[T], n uint) T {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
return iter.Enumerate(ctx).ElementAt(n)
}
// ElementAt retreives an item at a particular position in an Enumerator.
func (iter Enumerator[T]) ElementAt(n uint) T {
for i := uint(0); i < n; i++ {
<-iter
}
return <-iter
}
// First retrieves just the first item in the list, or returns an error if there are no elements in the array.
func First[T any](subject Enumerable[T]) (retval T, err error) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
err = errNoElements
var isOpen bool
if retval, isOpen = <-subject.Enumerate(ctx); isOpen {
err = nil
}
return
}
// Last retreives the item logically behind all other elements in the list.
func Last[T any](iter Enumerable[T]) T {
return iter.Enumerate(context.Background()).Last()
}
// Last retreives the item logically behind all other elements in the list.
func (iter Enumerator[T]) Last() (retval T) {
for retval = range iter {
// Intentionally Left Blank
}
return
}
type merger[T any] struct {
originals []Enumerable[T]
}
func (m merger[T]) Enumerate(ctx context.Context) Enumerator[T] {
retval := make(chan T)
var wg sync.WaitGroup
wg.Add(len(m.originals))
for _, item := range m.originals {
go func(input Enumerable[T]) {
defer wg.Done()
for value := range input.Enumerate(ctx) {
retval <- value
}
}(item)
}
go func() {
wg.Wait()
close(retval)
}()
return retval
}
// Merge takes the results as it receives them from several channels and directs
// them into a single channel.
func Merge[T any](channels ...Enumerable[T]) Enumerable[T] {
return merger[T]{
originals: channels,
}
}
// Merge takes the results of this Enumerator and others, and funnels them into
// a single Enumerator. The order of in which they will be combined is non-deterministic.
func (iter Enumerator[T]) Merge(others ...Enumerator[T]) Enumerator[T] {
retval := make(chan T)
var wg sync.WaitGroup
wg.Add(len(others) + 1)
funnel := func(prevResult Enumerator[T]) {
for entry := range prevResult {
retval <- entry
}
wg.Done()
}
go funnel(iter)
for _, item := range others {
go funnel(item)
}
go func() {
wg.Wait()
close(retval)
}()
return retval
}
type parallelSelecter[T any, E any] struct {
original Enumerable[T]
operation Transform[T, E]
}
func (ps parallelSelecter[T, E]) Enumerate(ctx context.Context) Enumerator[E] {
iter := ps.original.Enumerate(ctx)
if cpus := runtime.NumCPU(); cpus != 1 {
intermediate := splitN(iter, ps.operation, uint(cpus))
return intermediate[0].Merge(intermediate[1:]...)
}
return Select(ps.original, ps.operation).Enumerate(ctx)
}
// ParallelSelect creates an Enumerable which will use all logically available CPUs to
// execute a Transform.
func ParallelSelect[T any, E any](original Enumerable[T], operation Transform[T, E]) Enumerable[E] {
return parallelSelecter[T, E]{
original: original,
operation: operation,
}
}
// ParallelSelect will execute a Transform across all logical CPUs available to the current process.
//
// This is commented out, because Go 1.18 adds support for generics, but disallows methods from having type parameters
// not declared by their receivers.
//
//func (iter Enumerator[T]) ParallelSelect[E any](operation Transform[T, E]) Enumerator[E] {
// if cpus := runtime.NumCPU(); cpus != 1 {
// intermediate := iter.splitN(operation, uint(cpus))
// return intermediate[0].Merge(intermediate[1:]...)
// }
// return iter
//}
type reverser[T any] struct {
original Enumerable[T]
}
// Reverse will enumerate all values of an enumerable, store them in a Stack, then replay them all.
func Reverse[T any](original Enumerable[T]) Enumerable[T] {
return reverser[T]{
original: original,
}
}
func (r reverser[T]) Enumerate(ctx context.Context) Enumerator[T] {
return r.original.Enumerate(ctx).Reverse()
}
// Reverse returns items in the opposite order it encountered them in.
func (iter Enumerator[T]) Reverse() Enumerator[T] {
cache := NewStack[T]()
for entry := range iter {
cache.Push(entry)
}
retval := make(chan T)
go func() {
for !cache.IsEmpty() {
val, _ := cache.Pop()
retval <- val
}
close(retval)
}()
return retval
}
type selecter[T any, E any] struct {
original Enumerable[T]
transform Transform[T, E]
}
func (s selecter[T, E]) Enumerate(ctx context.Context) Enumerator[E] {
retval := make(chan E)
go func() {
defer close(retval)
for item := range s.original.Enumerate(ctx) {
select {
case retval <- s.transform(item):
// Intentionally Left Blank
case <-ctx.Done():
return
}
}
}()
return retval
}
// Select creates a reusable stream of transformed values.
func Select[T any, E any](subject Enumerable[T], transform Transform[T, E]) Enumerable[E] {
return selecter[T, E]{
original: subject,
transform: transform,
}
}
// Select iterates over a list and returns a transformed item.
//
// This is commented out because Go 1.18 added support for
//
//func (iter Enumerator[T]) Select[E any](transform Transform[T, E]) Enumerator[E] {
// retval := make(chan interface{})
//
// go func() {
// for item := range iter {
// retval <- transform(item)
// }
// close(retval)
// }()
//
// return retval
//}
type selectManyer[T any, E any] struct {
original Enumerable[T]
toMany Unfolder[T, E]
}
func (s selectManyer[T, E]) Enumerate(ctx context.Context) Enumerator[E] {
retval := make(chan E)
go func() {
for parent := range s.original.Enumerate(ctx) {
for child := range s.toMany(parent) {
retval <- child
}
}
close(retval)
}()
return retval
}
// SelectMany allows for unfolding of values.
func SelectMany[T any, E any](subject Enumerable[T], toMany Unfolder[T, E]) Enumerable[E] {
return selectManyer[T, E]{
original: subject,
toMany: toMany,
}
}
//// SelectMany allows for flattening of data structures.
//func (iter Enumerator[T]) SelectMany[E any](lister Unfolder[T, E]) Enumerator[E] {
// retval := make(chan E)
//
// go func() {
// for parent := range iter {
// for child := range lister(parent) {
// retval <- child
// }
// }
// close(retval)
// }()
//
// return retval
//}
// Single retreives the only element from a list, or returns nil and an error.
func Single[T any](iter Enumerable[T]) (retval T, err error) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
err = errNoElements
firstPass := true
for entry := range iter.Enumerate(ctx) {
if firstPass {
retval = entry
err = nil
} else {
retval = *new(T)
err = errMultipleElements
break
}
firstPass = false
}
return
}
// Singlep retrieces the only element from a list that matches a criteria. If
// no match is found, or two or more are found, `Singlep` returns nil and an
// error.
func Singlep[T any](iter Enumerable[T], pred Predicate[T]) (retval T, err error) {
iter = Where(iter, pred)
return Single(iter)
}
type skipper[T any] struct {
original Enumerable[T]
skipCount uint
}
func (s skipper[T]) Enumerate(ctx context.Context) Enumerator[T] {
return s.original.Enumerate(ctx).Skip(s.skipCount)
}
// Skip creates a reusable stream which will skip the first `n` elements before iterating
// over the rest of the elements in an Enumerable.
func Skip[T any](subject Enumerable[T], n uint) Enumerable[T] {
return skipper[T]{
original: subject,
skipCount: n,
}
}
// Skip retreives all elements after the first 'n' elements.
func (iter Enumerator[T]) Skip(n uint) Enumerator[T] {
results := make(chan T)
go func() {
defer close(results)
i := uint(0)
for entry := range iter {
if i < n {
i++
continue
}
results <- entry
}
}()
return results
}
// splitN creates N Enumerators, each will be a subset of the original Enumerator and will have
// distinct populations from one another.
func splitN[T any, E any](iter Enumerator[T], operation Transform[T, E], n uint) []Enumerator[E] {
results, cast := make([]chan E, n, n), make([]Enumerator[E], n, n)
for i := uint(0); i < n; i++ {
results[i] = make(chan E)
cast[i] = results[i]
}
go func() {
for i := uint(0); i < n; i++ {
go func(addr uint) {
defer close(results[addr])
for {
read, ok := <-iter
if !ok {
return
}
results[addr] <- operation(read)
}
}(i)
}
}()
return cast
}
type taker[T any] struct {
original Enumerable[T]
n uint
}
func (t taker[T]) Enumerate(ctx context.Context) Enumerator[T] {
return t.original.Enumerate(ctx).Take(t.n)
}
// Take retreives just the first `n` elements from an Enumerable.
func Take[T any](subject Enumerable[T], n uint) Enumerable[T] {
return taker[T]{
original: subject,
n: n,
}
}
// Take retreives just the first 'n' elements from an Enumerator.
func (iter Enumerator[T]) Take(n uint) Enumerator[T] {
results := make(chan T)
go func() {
defer close(results)
i := uint(0)
for entry := range iter {
if i >= n {
return
}
i++
results <- entry
}
}()
return results
}
type takeWhiler[T any] struct {
original Enumerable[T]
criteria func(T, uint) bool
}
func (tw takeWhiler[T]) Enumerate(ctx context.Context) Enumerator[T] {
return tw.original.Enumerate(ctx).TakeWhile(tw.criteria)
}
// TakeWhile creates a reusable stream which will halt once some criteria is no longer met.
func TakeWhile[T any](subject Enumerable[T], criteria func(T, uint) bool) Enumerable[T] {
return takeWhiler[T]{
original: subject,
criteria: criteria,
}
}
// TakeWhile continues returning items as long as 'criteria' holds true.
func (iter Enumerator[T]) TakeWhile(criteria func(T, uint) bool) Enumerator[T] {
results := make(chan T)
go func() {
defer close(results)
i := uint(0)
for entry := range iter {
if !criteria(entry, i) {
return
}
i++
results <- entry
}
}()
return results
}
// Tee creates two Enumerators which will have identical contents as one another.
func (iter Enumerator[T]) Tee() (Enumerator[T], Enumerator[T]) {
left, right := make(chan T), make(chan T)
go func() {
for entry := range iter {
left <- entry
right <- entry
}
close(left)
close(right)
}()
return left, right
}
// ToSlice places all iterated over values in a Slice for easy consumption.
func ToSlice[T any](iter Enumerable[T]) []T {
return iter.Enumerate(context.Background()).ToSlice()
}
// ToSlice places all iterated over values in a Slice for easy consumption.
func (iter Enumerator[T]) ToSlice() []T {
retval := make([]T, 0)
for entry := range iter {
retval = append(retval, entry)
}
return retval
}
type wherer[T any] struct {
original Enumerable[T]
filter Predicate[T]
}
func (w wherer[T]) Enumerate(ctx context.Context) Enumerator[T] {
retval := make(chan T)
go func() {
defer close(retval)
for entry := range w.original.Enumerate(ctx) {
if w.filter(entry) {
retval <- entry
}
}
}()
return retval
}
// Where creates a reusable means of filtering a stream.
func Where[T any](original Enumerable[T], p Predicate[T]) Enumerable[T] {
return wherer[T]{
original: original,
filter: p,
}
}
// Where iterates over a list and returns only the elements that satisfy a
// predicate.
func (iter Enumerator[T]) Where(predicate Predicate[T]) Enumerator[T] {
retval := make(chan T)
go func() {
for item := range iter {
if predicate(item) {
retval <- item
}
}
close(retval)
}()
return retval
}
// UCount iterates over a list and keeps a running tally of the number of elements
// satisfy a predicate.
func UCount[T any](iter Enumerable[T], p Predicate[T]) uint {
return iter.Enumerate(context.Background()).UCount(p)
}
// UCount iterates over a list and keeps a running tally of the number of elements
// satisfy a predicate.
func (iter Enumerator[T]) UCount(p Predicate[T]) uint {
tally := uint(0)
for entry := range iter {
if p(entry) {
tally++
}
}
return tally
}
// UCountAll iterates over a list and keeps a running tally of how many it's seen.
func UCountAll[T any](iter Enumerable[T]) uint {
return iter.Enumerate(context.Background()).UCountAll()
}
// UCountAll iterates over a list and keeps a running tally of how many it's seen.
func (iter Enumerator[T]) UCountAll() uint {
tally := uint(0)
for range iter {
tally++
}
return tally
}