-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathoperations.go
2299 lines (2055 loc) · 71.2 KB
/
operations.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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package plinq
import (
"errors"
"fmt"
"github.com/fanliao/go-promise"
)
var _ = fmt.Println //for debugger
//the struct and functions of each operation-------------------------------------------------------------------------\
const (
ACT_SELECT int = iota
ACT_SELECTMANY
ACT_WHERE
ACT_GROUPBY
ACT_HGROUPBY
ACT_ORDERBY
ACT_DISTINCT
ACT_JOIN
ACT_GROUPJOIN
ACT_UNION
ACT_CONCAT
ACT_INTERSECT
ACT_REVERSE
ACT_EXCEPT
ACT_AGGREGATE
ACT_SKIP
ACT_SKIPWHILE
ACT_TAKE
ACT_TAKEWHILE
ACT_ELEMENTAT
ACT_SINGLEVALUE
)
// stepAction presents a action related to a linq operation
// Arguments:
// DataSource: the data source of the linq operation
// *ParallelOption: the option of the paralleliam algorithm
// bool: true if it is first step
// Returns:
// DataSource: the operation result
// *promise.Future: if the operation returns the channel,
// the Future value will be used to get the error if the error appears after the stepAction returns
// bool: true if the after operation need keep the order of data
// error: if the operation returns the list mode, it present if the error appears
type stepAction func(dataSource, *ParallelOption, bool) (dataSource, bool, error) //, *promise.Future, bool, error)
//step present a linq operation
type step interface {
Action() stepAction
Typ() int
ChunkSize() int
POption(option ParallelOption) *ParallelOption
}
type commonStep struct {
typ int
act interface{}
chunkSize int
}
type joinStep struct {
commonStep
outerKeySelector OneArgsFunc
innerKeySelector OneArgsFunc
resultSelector interface{}
isLeftJoin bool
}
func (this commonStep) Typ() int { return this.typ }
func (this commonStep) ChunkSize() int { return this.chunkSize }
func (this commonStep) POption(option ParallelOption) *ParallelOption {
if this.typ == ACT_REVERSE || this.Typ() == ACT_UNION || this.Typ() == ACT_INTERSECT || this.Typ() == ACT_EXCEPT {
option.ChunkSize = defaultLargeChunkSize
}
if this.chunkSize != 0 {
option.ChunkSize = this.chunkSize
}
return &option
}
func (this commonStep) Action() (act stepAction) {
switch this.typ {
case ACT_SELECT:
act = getSelect(this.act.(OneArgsFunc))
case ACT_WHERE:
act = getWhere(this.act.(PredicateFunc))
case ACT_SELECTMANY:
act = getSelectMany(this.act.(func(interface{}) []interface{}))
case ACT_DISTINCT:
act = getDistinct(this.act.(OneArgsFunc))
case ACT_ORDERBY:
act = getOrder(this.act.(CompareFunc))
case ACT_GROUPBY:
act = getGroupBy(this.act.(OneArgsFunc), false)
case ACT_HGROUPBY:
act = getGroupBy(this.act.(OneArgsFunc), true)
case ACT_UNION:
act = getUnion(this.act)
case ACT_CONCAT:
act = getConcat(this.act)
case ACT_INTERSECT:
act = getIntersect(this.act)
case ACT_EXCEPT:
act = getExcept(this.act)
case ACT_REVERSE:
act = getReverse()
case ACT_SKIP:
act = getSkipTakeCount(this.act.(int), false)
case ACT_SKIPWHILE:
act = getSkipTakeWhile(this.act.(PredicateFunc), false)
case ACT_TAKE:
act = getSkipTakeCount(this.act.(int), true)
case ACT_TAKEWHILE:
act = getSkipTakeWhile(this.act.(PredicateFunc), true)
}
return
}
func (this joinStep) Action() (act stepAction) {
switch this.typ {
case ACT_JOIN:
act = getJoin(this.act, this.outerKeySelector, this.innerKeySelector,
this.resultSelector.(TwoArgsFunc), this.isLeftJoin)
case ACT_GROUPJOIN:
act = getGroupJoin(this.act, this.outerKeySelector, this.innerKeySelector,
this.resultSelector.(func(interface{}, []interface{}) interface{}), this.isLeftJoin)
}
return
}
// The functions get linq operation------------------------------------
// Get the action function for select operation
func getSelect(selector OneArgsFunc) stepAction {
return stepAction(func(src dataSource, option *ParallelOption, first bool) (dest dataSource, keep bool, e error) {
keep = option.KeepOrder
mapChunk := getChunkOprFunc(mapSliceToSelf, selector)
if first {
mapChunk = getChunkOprFunc(mapSlice, selector)
}
dest, e = parallelMap(src, nil, mapChunk, option)
return
})
}
// Get the action function for select operation
func getSelectMany(manySelector func(interface{}) []interface{}) stepAction {
return stepAction(func(src dataSource, option *ParallelOption, first bool) (dest dataSource, keep bool, e error) {
keep = option.KeepOrder
mapChunk := func(c *chunk) *chunk {
results := mapSliceToMany(c.Data, manySelector)
return &chunk{NewSlicer(results), c.Order, c.StartIndex}
}
dest, e = parallelMap(src, nil, mapChunk, option)
return
})
}
// Get the action function for where operation
func getWhere(predicate PredicateFunc) stepAction {
return stepAction(func(src dataSource, option *ParallelOption, first bool) (dest dataSource, keep bool, e error) {
keep = option.KeepOrder
mapChunk := getChunkOprFunc(filterSlice, predicate)
dest, e = parallelMap(src, nil, mapChunk, option)
return
})
}
// Get the action function for OrderBy operation
func getOrder(comparator CompareFunc) stepAction {
return stepAction(func(src dataSource, option *ParallelOption, first bool) (dest dataSource, keep bool, e error) {
defer func() {
if err := recover(); err != nil {
e = newErrorWithStacks(err)
}
}()
//order operation be sequentail
option.Degree = 1
switch s := src.(type) {
case *listSource:
//quick sort
//TODO:How to avoid the reflect?
sorteds := sortSlice(s.data.ToInterfaces(), func(this, that interface{}) bool {
return comparator(this, that) == -1
})
return newDataSource(sorteds), true, nil
case *chanSource:
//AVL tree sort
avl := newAvlTree(comparator)
cs := parallelMapChanToChan(s, nil,
getChunkOprFunc(forEachSlicer, func(i int, v interface{}) {
avl.Insert(v)
}), option)
dest, e = getFutureResult(cs.Future(), func(r []interface{}) dataSource {
return newDataSource(avl.ToSlice())
})
keep = true
return
}
panic(ErrUnsupportSource)
})
}
// Get the action function for DistinctBy operation
func getDistinct(selector OneArgsFunc) stepAction {
return stepAction(func(src dataSource, option *ParallelOption, first bool) (dest dataSource, keep bool, e error) {
keep = option.KeepOrder
var useDefHash uint32 = 0
mapChunk := getMapChunkToKVChunkFunc(&useDefHash, selector)
//map the element to a keyValue that key is hash value and value is element
mapOut, e := parallelMap(src, nil, mapChunk, option)
if e != nil {
return
}
dest, e = reduceDistValues(mapOut, option)
return
})
}
// Get the action function for GroupBy operation
// note the groupby cannot keep order because the map cannot keep order
func getGroupBy(selector OneArgsFunc, returnMap bool) stepAction {
return stepAction(func(src dataSource, option *ParallelOption, first bool) (dest dataSource, keep bool, e error) {
var useDefHash uint32 = 0
mapChunk := getMapChunkToKVChunkFunc(&useDefHash, selector)
//map the element to a keyValue that key is group key and value is element
mapOut, e := parallelMap(src, nil, mapChunk, option)
if e != nil {
return
}
groups := make(map[interface{}]interface{})
group := func(v interface{}) {
kv := v.(*hKeyValue)
k := kv.keyHash
if v, ok := groups[k]; !ok {
groups[k] = []interface{}{kv.value}
} else {
list := v.([]interface{})
groups[k] = appendToSlice1(list, kv.value)
}
}
//reduce the keyValue map to get grouped slice
//get key with group values values
errs := reduceChan(mapOut, getChunkOprFunc(forEachSlicer, func(i int, v interface{}) {
group(v)
}))
if errs == nil {
if returnMap {
return newDataSource(groups), option.KeepOrder, nil
} else {
kvs := make([]interface{}, len(groups))
i := 0
for k, v := range groups {
kvs[i] = &KeyValue{k, v}
i++
}
return newDataSource(kvs), option.KeepOrder, nil
}
} else {
return nil, option.KeepOrder, NewAggregateError("Group error", errs)
}
})
}
// Get the action function for Join operation
// note the Join cannot keep order because the map cannot keep order
func getJoin(inner interface{},
outerKeySelector OneArgsFunc,
innerKeySelector OneArgsFunc,
resultSelector TwoArgsFunc, isLeftJoin bool) stepAction {
return getJoinImpl(inner, outerKeySelector, innerKeySelector,
func(outerkv *hKeyValue, innerList []interface{}, results *[]interface{}) {
for _, iv := range innerList {
*results = appendToSlice1(*results, resultSelector(outerkv.value, iv))
}
}, func(outerkv *hKeyValue, results *[]interface{}) {
*results = appendToSlice1(*results, resultSelector(outerkv.value, nil))
}, isLeftJoin)
}
// Get the action function for GroupJoin operation
func getGroupJoin(inner interface{},
outerKeySelector OneArgsFunc,
innerKeySelector OneArgsFunc,
resultSelector func(interface{}, []interface{}) interface{}, isLeftJoin bool) stepAction {
return getJoinImpl(inner, outerKeySelector, innerKeySelector,
func(outerkv *hKeyValue, innerList []interface{}, results *[]interface{}) {
*results = appendToSlice1(*results, resultSelector(outerkv.value, innerList))
}, func(outerkv *hKeyValue, results *[]interface{}) {
*results = appendToSlice1(*results, resultSelector(outerkv.value, []interface{}{}))
}, isLeftJoin)
}
// The common Join function
func getJoinImpl(inner interface{},
outerKeySelector OneArgsFunc,
innerKeySelector OneArgsFunc,
matchSelector func(*hKeyValue, []interface{}, *[]interface{}),
unmatchSelector func(*hKeyValue, *[]interface{}), isLeftJoin bool) stepAction {
return stepAction(func(src dataSource, option *ParallelOption, first bool) (dest dataSource, keep bool, e error) {
keep = option.KeepOrder
innerKVtask := promise.Start(func() (interface{}, error) {
if innerKVsDs, err, _ := From(inner).hGroupBy(innerKeySelector).execute(); err == nil {
r := innerKVsDs.(*listSource).data.(*mapSlicer).data
return r, nil
} else {
return nil, err
}
})
var useDefHash uint32 = 0
mapChunk := func(c *chunk) (r *chunk) {
outerKVs := getMapChunkToKVs(&useDefHash, outerKeySelector)(c).ToInterfaces()
results := make([]interface{}, 0, 10)
if r, err := innerKVtask.Get(); err != nil {
panic(err)
} else {
innerKVs := r.(map[interface{}]interface{})
for _, o := range outerKVs {
outerkv := o.(*hKeyValue)
if innerList, ok := innerKVs[outerkv.keyHash]; ok {
matchSelector(outerkv, innerList.([]interface{}), &results)
} else if isLeftJoin {
unmatchSelector(outerkv, &results)
}
}
}
return &chunk{NewSlicer(results), c.Order, c.StartIndex}
}
dest, e = parallelMap(src, nil, mapChunk, option)
return
})
}
func canSequentialSet(src dataSource, src2 dataSource) bool {
if src.Typ() == SOURCE_LIST && src2.Typ() == SOURCE_LIST {
if src.ToSlice(false).Len() <= defaultLargeChunkSize && src2.ToSlice(false).Len() <= defaultLargeChunkSize {
return true
}
}
return false
}
// Get the action function for Union operation
// note the union cannot keep order because the map cannot keep order
func getUnion(source2 interface{}) stepAction {
return stepAction(func(src dataSource, option *ParallelOption, first bool) (dest dataSource, keep bool, e error) {
keep = option.KeepOrder
src2 := From(source2).data
if canSequentialSet(src, src2) {
return sequentialUnion(src, src2, option, first)
}
reduceSrcChan := make(chan *chunk, 2)
var useDefHash uint32
mapChunk := getMapChunkToKVChunkFunc(&useDefHash, nil)
//map the elements of source and source2 to the a KeyValue slice
//includes the hash value and the original element
mapOut1 := parallelMapToChan(src, reduceSrcChan, mapChunk, option)
mapOut2 := parallelMapToChan(src2, reduceSrcChan, mapChunk, option)
mapFuture := promise.WhenAll(mapOut1.Future(), mapOut2.Future())
mapOut := &chanSource{chunkChan: reduceSrcChan, future: mapFuture}
mapOut.addCallbackToCloseChan()
option.ReIndex = true
dest, e = reduceDistValues(mapOut, option)
return
})
}
// Get the action function for Union operation
// note the union cannot keep order because the map cannot keep order
func sequentialUnion(src dataSource, src2 dataSource, option *ParallelOption, first bool) (ds dataSource, keep bool, e error) {
defer func() {
if err := recover(); err != nil {
e = newErrorWithStacks(err)
}
}()
s2 := src2.ToSlice(false)
s1 := src.ToSlice(false)
var useDefHash uint32 = 0
mapChunk := getMapChunkToKVChunkFunc(&useDefHash, nil)
c1 := mapChunk(&chunk{s1, 0, 1})
c2 := mapChunk(&chunk{s2, 0, 1})
result := make([]interface{}, 0, s1.Len()+s2.Len())
distKVs := make(map[interface{}]int)
distChunkValues(c1, distKVs, &result)
distChunkValues(c2, distKVs, &result)
return &listSource{NewSlicer(result)}, option.KeepOrder, nil
}
// Get the action function for Concat operation
func getConcat(source2 interface{}) stepAction {
return stepAction(func(src dataSource, option *ParallelOption, first bool) (dest dataSource, keep bool, e error) {
//TODO: if the source is channel source, should use channel mode
slice1 := src.ToSlice(option.KeepOrder).ToInterfaces()
if slice2, err2 := From(source2).SetKeepOrder(option.KeepOrder).Results(); err2 == nil {
result := make([]interface{}, len(slice1)+len(slice2))
_ = copy(result[0:len(slice1)], slice1)
_ = copy(result[len(slice1):len(slice1)+len(slice2)], slice2)
return newDataSource(result), option.KeepOrder, nil
} else {
return nil, option.KeepOrder, err2
}
})
}
// Get the action function for intersect operation
// note the intersect cannot keep order because the map cannot keep order
func getIntersect(source2 interface{}) stepAction {
return stepAction(func(src dataSource, option *ParallelOption, first bool) (dest dataSource, keep bool, e error) {
keep = option.KeepOrder
dest, e = filterSet(src, source2, false, option)
return
})
}
// Get the action function for Except operation
// note the except cannot keep order because the map cannot keep order
func getExcept(source2 interface{}) stepAction {
return stepAction(func(src dataSource, option *ParallelOption, first bool) (dest dataSource, keep bool, e error) {
keep = option.KeepOrder
dest, e = filterSet(src, source2, true, option)
return
})
}
// Get the action function for Reverse operation
func getReverse() stepAction {
return stepAction(func(src dataSource, option *ParallelOption, first bool) (dest dataSource, keep bool, e error) {
keep = option.KeepOrder
var (
dstSlicer []interface{}
srcSlicer Slicer
)
if listSrc, ok := src.(*listSource); ok && first {
dstSlicer = make([]interface{}, listSrc.data.Len())
srcSlicer = listSrc.data
} else {
dstSlicer = src.ToSlice(true).ToInterfaces()
srcSlicer = NewSlicer(dstSlicer)
}
size := srcSlicer.Len()
srcSlice := srcSlicer.Slice(0, size/2) //wholeSlice[0 : size/2]
mapChunk := func(c *chunk) *chunk {
forEachSlicer(c.Data, func(i int, v interface{}) {
j := c.StartIndex + i
dstSlicer[size-1-j], dstSlicer[j] = c.Data.Index(i), srcSlicer.Index(size-1-j)
})
return c
}
reverseSrc := &listSource{NewSlicer(srcSlice)} //newDataSource(srcSlice)
if size <= 1000 {
mapChunk(&chunk{Data: srcSlice})
dest = newDataSource(dstSlicer)
return
}
f := parallelMapListToList(reverseSrc, func(c *chunk) *chunk {
return mapChunk(c)
}, option)
_, e = f.Get()
dest = newDataSource(dstSlicer)
return
})
}
// Get the action function for Skip/Take operation
func getSkipTakeCount(count int, isTake bool) stepAction {
if count < 0 {
count = 0
}
return getSkipTake(func(c *chunk, canceller promise.Canceller) (i int, found bool) {
if c.StartIndex > count {
i, found = 0, true
} else if c.StartIndex+c.Data.Len() >= count {
i, found = count-c.StartIndex, true
} else {
i, found = c.StartIndex+c.Data.Len(), false
}
return
}, isTake, true)
}
// Get the action function for SkipWhile/TakeWhile operation
func getSkipTakeWhile(predicate PredicateFunc, isTake bool) stepAction {
return getSkipTake(foundMatchFunc(invFunc(predicate), true), isTake, false)
}
// note the elementAt cannot keep order because the map cannot keep order
// 根据索引查找单个元素
func getElementAt(src dataSource, i int, option *ParallelOption) (element interface{}, found bool, e error) {
return getFirstElement(src, func(c *chunk, canceller promise.Canceller) (int, bool) {
size := c.Data.Len()
if c.StartIndex <= i && c.StartIndex+size-1 >= i {
return i - c.StartIndex, true
} else {
return size, false
}
}, true, option)
}
// Get the action function for FirstBy operation
// 根据条件查找第一个符合的元素
func getFirstBy(src dataSource, predicate PredicateFunc, option *ParallelOption) (element interface{}, found bool, e error) {
return getFirstElement(src, foundMatchFunc(predicate, true), false, option)
}
// Get the action function for LastBy operation
// 根据条件查找最后一个符合的元素
func getLastBy(src dataSource, predicate PredicateFunc, option *ParallelOption) (element interface{}, found bool, e error) {
return getLastElement(src, foundMatchFunc(predicate, false), option)
}
// Get the action function for Aggregate operation
func getAggregate(src dataSource, aggregateFuncs []*AggregateOperation, option *ParallelOption) (result []interface{}, e error) {
if isNil(aggregateFuncs) || len(aggregateFuncs) == 0 {
return nil, newErrorWithStacks(errors.New("Aggregation function cannot be nil"))
}
keep := option.KeepOrder
//try to use sequentail if the size of the data is less than size of chunk
if rs, err, handled := trySequentialAggregate(src, option, aggregateFuncs); handled {
return rs, err
}
rs := make([]interface{}, len(aggregateFuncs))
mapChunk := func(c *chunk) (r *chunk) {
r = &chunk{aggregateSlice(c.Data, aggregateFuncs, false, true), c.Order, c.StartIndex}
return
}
//NOTE: must use channel as map output,
//because the logic of chunk is different with other operation,
//these chunks cannot be merged to a slice
mapOut := parallelMapToChan(src, nil, mapChunk, option)
//reduce the keyValue map to get grouped slice
//get key with group values values
first := true
reduce := func(c *chunk) {
if first {
for i := 0; i < len(rs); i++ {
rs[i] = aggregateFuncs[i].Seed
}
}
first = false
for i := 0; i < len(rs); i++ {
rs[i] = aggregateFuncs[i].ReduceAction(c.Data.Index(i), rs[i])
}
}
avl := newChunkAvlTree()
if errs := reduceChan(mapOut, func(c *chunk) (r *chunk) {
if !keep {
reduce(c)
} else {
avl.Insert(c)
}
return
}); errs != nil {
e = getError(errs)
}
if keep {
cs := avl.ToSlice()
for _, v := range cs {
c := v.(*chunk)
reduce(c)
}
}
if first {
return rs, newErrorWithStacks(errors.New("cannot aggregate an empty slice"))
} else {
return rs, e
}
}
func getSkipTake(findMatch func(*chunk, promise.Canceller) (int, bool), isTake bool, useIndex bool) stepAction {
return stepAction(func(src dataSource, option *ParallelOption, first bool) (dest dataSource, keep bool, e error) {
switch s := src.(type) {
case *listSource:
var (
i int
found bool
)
//如果是根据索引查询列表,可以直接计算,否则要一个个判断
if useIndex {
i, _ = findMatch(&chunk{s.data, 0, 0}, nil)
} else {
if i, found, e = getFirstOrLastIndex(s, findMatch, option, true); !found {
i = s.data.Len()
}
}
//根据Take还是Skip返回结果
if isTake {
return newDataSource(s.data.Slice(0, i)), option.KeepOrder, e
} else {
return newDataSource(s.data.Slice(i, s.data.Len())), option.KeepOrder, e
}
case *chanSource:
out := make(chan *chunk, option.Degree)
sendMatchChunk := func(c *chunk, idx int) {
if isTake {
sendChunk(out, &chunk{c.Data.Slice(0, idx), c.Order, c.StartIndex})
} else {
sendChunk(out, &chunk{c.Data.Slice(idx, c.Data.Len()), c.Order, c.StartIndex})
}
}
//如果一个块的前置块都已经判断完成时,调用beforeMatchAct
beforeMatchAct := func(c *chunkMatchResult) (while bool) {
//如果useIndex,则只有等到前置块都判断完成时才能得出正确的起始索引号,所以在这里才判断是否匹配
if useIndex {
if i, found := findMatch(c.chunk, nil); found {
c.matched = true
c.matchIndex = i
}
}
if c.matched {
//如果发现满足条件的item,则必然是第一个满足条件的块
sendMatchChunk(c.chunk, c.matchIndex)
return true
} else if isTake {
//如果不满足条件,那可以take
sendChunk(out, c.chunk)
} else {
//send a empty slicer is better, because the after operations may include Skip, it need the whole chunk list
sendChunk(out, &chunk{NewSlicer([]interface{}{}), c.chunk.Order, c.chunk.StartIndex})
}
return false
}
//如果一个块在某个匹配块的后面,将调用afterMatchAct,意味着可以作为Skip的输出
afterMatchAct := func(c *chunkMatchResult) {
if !isTake {
sendChunk(out, c.chunk)
}
}
//如果一个块是第一个匹配的块,将调用beMatchAct
beMatchAct := func(c *chunkMatchResult) {
sendMatchChunk(c.chunk, c.matchIndex)
}
//开始处理channel中的块
srcChan := s.ChunkChan(option.ChunkSize)
f := promise.Start(func() (interface{}, error) {
matchedList := newChunkMatchResultList(beforeMatchAct, afterMatchAct, beMatchAct, useIndex)
return forEachChanByOrder(s, srcChan, func(c *chunk, foundFirstMatch *bool) bool {
//fmt.Println("forEachChanByOrder", c, c.Data.Len(), "------------------", *foundFirstMatch)
if !*foundFirstMatch {
//检查块是否存在匹配的数据,按Index计算的总是返回false,因为必须要等前面所有的块已经排好序后才能得到正确的索引
chunkResult := getChunkMatchResult(c, findMatch, useIndex)
//判断是否找到了第一个匹配的块
if *foundFirstMatch = matchedList.handleChunk(chunkResult); *foundFirstMatch {
if isTake {
s.Close()
return true
}
}
} else {
//如果已经找到了第一个匹配的块,则此后的块直接处理即可
if !isTake {
sendChunk(out, c)
} else {
return true
}
}
return false
})
}).Fail(func(err interface{}) {
s.Close()
})
outCs := &chanSource{chunkChan: out, future: f}
outCs.addCallbackToCloseChan()
return outCs, option.KeepOrder, nil
}
panic(ErrUnsupportSource)
})
}
// Get the action function for ElementAt operation
func getFirstElement(src dataSource,
findMatch func(c *chunk, canceller promise.Canceller) (r int, found bool),
useIndex bool, option *ParallelOption) (element interface{}, found bool, err error) {
switch s := src.(type) {
case *listSource:
rs, i := s.data, -1
if useIndex {
//使用索引查找列表非常简单,无需并行
if i, found = findMatch(&chunk{rs, 0, 0}, nil); found {
return rs.Index(i), true, nil
} else {
return nil, false, nil
}
} else if s.data.Len() <= option.Degree*option.ChunkSize {
//根据数据量大小进行并行或串行查找
i, found, err = getFirstOrLastIndex(newListSource(rs), findMatch, option, true)
if found && err == nil {
element = rs.Index(i)
}
return
} else {
i, found, err = getFirstOrLastIndex(newListSource(rs), findMatch, option, true)
if found && err == nil {
element = rs.Index(i)
}
return
//chunkChan := splitToChunkChan(src, option)
//return getFirstElement(&chanSource{chunkChan: chunkChan},
// findMatch, useIndex, option)
}
case *chanSource:
beforeMatchAct := func(c *chunkMatchResult) (while bool) {
if useIndex {
//判断是否满足条件
if idx, found := findMatch(c.chunk, nil); found {
element = c.chunk.Data.Index(idx)
return true
}
}
if c.matched {
element = c.chunk.Data.Index(c.matchIndex)
return true
}
return false
}
afterMatchAct, beMatchAct := func(c *chunkMatchResult) {}, func(c *chunkMatchResult) {
//处理第一个匹配块
element = c.chunk.Data.Index(c.matchIndex)
}
reduceChan := make(chan *chunkMatchResult, option.Degree)
fu := parallelHandleChan(s, func(c *chunk) {
chunkResult := getChunkMatchResult(c, findMatch, useIndex)
func(){
defer func() {
if e := recover(); e != nil{
s.Close()
}
}()
reduceChan <- chunkResult
}()
}, option).Done(func(r interface{}) {
defer func() {
_ = recover()
}()
reduceChan <- nil
})
rf := promise.Start(func() (interface{}, error) {
defer func() {
_ = recover()
}()
matchedList := newChunkMatchResultList(beforeMatchAct, afterMatchAct, beMatchAct, useIndex)
for result := range reduceChan {
if matchedList.handleChunk(result) {
//element = c.chunk.Data[idx]
found = true
close(reduceChan)
break
}
}
return nil, nil
})
if _, err := fu.Get(); err != nil {
s.Close()
return nil, false, err
}
if _, err := rf.Get(); err != nil {
close(reduceChan)
return nil, false, err
}
return
}
panic(ErrUnsupportSource)
}
func getLastElement(src dataSource,
findMatch func(c *chunk, canceller promise.Canceller) (r int, found bool),
option *ParallelOption) (element interface{}, found bool, err error) {
switch s := src.(type) {
case *listSource:
rs, i := s.data, -1
//根据数据量大小进行并行或串行查找
i, found, err = getFirstOrLastIndex(newListSource(rs), findMatch, option, false)
if found && err == nil {
element = rs.Index(i)
}
return
case *chanSource:
srcChan := s.ChunkChan(option.ChunkSize)
f := promise.Start(func() (interface{}, error) {
var r interface{}
maxOrder := -1
_, _ = forEachChanByOrder(s, srcChan, func(c *chunk, foundFirstMatch *bool) bool {
index, matched := findMatch(c, nil)
if matched {
if c.Order > maxOrder {
maxOrder = c.Order
r = c.Data.Index(index)
}
}
return false
})
if maxOrder >= 0 {
element = r
found = true
}
return nil, nil
})
if _, err := f.Get(); err != nil {
s.Close()
return nil, false, err
}
return
}
panic(ErrUnsupportSource)
}
// Get the action function for Any operation
func getAny(src dataSource, predicate PredicateFunc, option *ParallelOption) (result interface{}, allMatched bool, err error) {
getMapChunk := func(c *chunk) func(promise.Canceller) (interface{}, error) {
return func(canceller promise.Canceller) (foundNoMatched interface{}, e error) {
size := c.Data.Len()
for i := 0; i < size; i++ {
if canceller.IsCancellationRequested() {
break
}
if predicate(c.Data.Index(i)) {
return true, nil
}
}
return false, nil
}
}
predicateResult := func(v interface{}) bool {
if r, ok := v.(bool); r && ok {
return true
} else {
return false
}
}
var f *promise.Future
switch s := src.(type) {
case *listSource:
f = parallelMapListForAnyTrue(s, getMapChunk, predicateResult, option)
case *chanSource:
f = parallelMapChanForAnyTrue(s, getMapChunk, predicateResult, option)
}
r, e := f.Get()
if val, ok := r.(bool); ok {
return val, val, e
} else {
return false, false, e
}
return
}
func getChunkMatchResult(c *chunk,
findMatch func(c *chunk, canceller promise.Canceller) (r int, found bool),
useIndex bool) (r *chunkMatchResult) {
r = &chunkMatchResult{chunk: c}
if !useIndex {
r.matchIndex, r.matched = findMatch(c, nil)
}
return
}
// Get the action function for ElementAt operation
func forEachChanByOrder(src *chanSource, srcChan chan *chunk, action func(*chunk, *bool) bool) (interface{}, error) {
foundFirstMatch := false
shouldBreak := false
//Noted the order of sent from source chan maybe confused
for c := range srcChan {
if isNil(c) {
if cap(srcChan) > 0 {
src.Close()
break
} else {
continue
}
}
if shouldBreak = action(c, &foundFirstMatch); shouldBreak {
src.Close()
break
}
}
if src.future != nil {
if _, err := src.future.Get(); err != nil {
return nil, err
}
}
return nil, nil
}
func filterSet(src dataSource, source2 interface{}, isExcept bool, option *ParallelOption) (dataSource, error) {
src2 := newDataSource(source2)
if canSequentialSet(src, src2) {
return filterSetWithSeq(src, src2, isExcept, option)
}
switch ds2 := src2.(type) {
case *listSource:
return filterSetByList(src, ds2, isExcept, option)
case *chanSource:
return filterSetByChan(src, ds2, isExcept, option)
default:
panic(ErrUnsupportSource)
}
}
func toKeyValue(o interface{}) (k interface{}, val interface{}) {
if kv, ok := o.(*hKeyValue); ok {
k, val = kv.keyHash, kv.value
} else {
k, val = o, o
}
return
}
func addDistVal(k interface{}, val interface{},
distKVs map[interface{}]bool,
resultKVs map[interface{}]interface{}, isExcept bool) (added bool) {
_, ok := distKVs[k]
if (isExcept && !ok) || (!isExcept && ok) {
if _, ok := resultKVs[k]; !ok {
resultKVs[k] = val
added = true
}
}
return
}
func getFilterSetMapFuncs() (mapFunc1, mapFunc2 func(*chunk) *chunk) {
var useDefHash uint32 = 0
mapFunc1 = getMapChunkToKVChunkFunc(&useDefHash, nil)
mapFunc2 = func(c *chunk) (r *chunk) {
getResult := func(c *chunk, useValAsKey bool) Slicer {
return mapSlice(c.Data, hash64)
}
slicer := getMapChunkToKeyList(&useDefHash, nil, getResult)(c)
return &chunk{slicer, c.Order, c.StartIndex}
}
return
}
func filterSetByChan(src dataSource, src2 dataSource, isExcept bool, option *ParallelOption) (dataSource, error) {
checkChunkBeEnd := func(c *chunk, ok bool, ended *bool, anotherEnded bool, ch chan *chunk) (end, broken bool) {
if isNil(c) || !ok {