summaryrefslogtreecommitdiffstats
path: root/akregator/src/mk4storage/metakit/src/custom.cpp
blob: 6ed1d5ab3b81d4539b09d3efa78ea35097de16e5 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
// custom.cpp --
// $Id$
// This is part of Metakit, see http://www.equi4.com/metakit/

/** @file
 * Implementation of many custom viewer classes
 */

#include "header.h"

#include "custom.h"
#include "format.h"

/////////////////////////////////////////////////////////////////////////////

class c4_CustomHandler : public c4_Handler
{
  c4_CustomSeq* _seq;

public:
  c4_CustomHandler (const c4_Property& prop_, c4_CustomSeq* seq_);
  virtual ~c4_CustomHandler ();

  virtual int ItemSize(int index_);
  virtual const void* Get(int index_, int& length_);
  virtual void Set(int index_, const c4_Bytes& buf_);

  virtual void Insert(int index_, const c4_Bytes& buf_, int count_);
  virtual void Remove(int index_, int count_);
};

/////////////////////////////////////////////////////////////////////////////

c4_CustomHandler::c4_CustomHandler (const c4_Property& prop_,
                      c4_CustomSeq* seq_)
  : c4_Handler (prop_), _seq (seq_)
{
  d4_assert(_seq != 0);
}

c4_CustomHandler::~c4_CustomHandler ()
{
}

int c4_CustomHandler::ItemSize(int index_)
{
  c4_Bytes& buf = _seq->Buffer();

  int colnum = _seq->PropIndex(Property().GetId());
  d4_assert(colnum >= 0);
  
  if (!_seq->DoGet(index_, colnum, buf))
    return 0;

  return buf.Size();
}

const void* c4_CustomHandler::Get(int index_, int& length_)
{
  c4_Bytes& buf = _seq->Buffer();

  int colnum = _seq->PropIndex(Property().GetId());
  d4_assert(colnum >= 0);
  
  if (!_seq->DoGet(index_, colnum, buf))
    ClearBytes(buf);

  length_ = buf.Size();
  return buf.Contents();
}

void c4_CustomHandler::Set(int index_, const c4_Bytes& buf_)
{
  int colnum = _seq->PropIndex(Property().GetId());
  d4_assert(colnum >= 0);
  
  _seq->DoSet(index_, colnum, buf_);
}

void c4_CustomHandler::Insert(int, const c4_Bytes&, int)
{
  d4_assert(0); //! not yet
}

void c4_CustomHandler::Remove(int, int)
{
  d4_assert(0); //! not yet
}

c4_Handler* c4_CustomSeq::CreateHandler(const c4_Property& prop_)
{
  return d4_new c4_CustomHandler (prop_, this);
}

/////////////////////////////////////////////////////////////////////////////

c4_CustomSeq::c4_CustomSeq (c4_CustomViewer* viewer_)
  : c4_HandlerSeq (0), _viewer (viewer_), _inited (false)
{
  d4_assert(_viewer != 0);

    // set up handlers to match a template obtained from the viewer
  c4_View v = viewer_->GetTemplate();

  for (int i = 0; i < v.NumProperties(); ++i)
    PropIndex(v.NthProperty(i));

  _inited = true;
}

c4_CustomSeq::~c4_CustomSeq ()
{
  delete _viewer;
}

int c4_CustomSeq::NumRows() const
{
  return _inited ? _viewer->GetSize() : 0;
}

bool c4_CustomSeq::RestrictSearch(c4_Cursor cursor_, int& pos_, int& count_)
{
  if (count_ > 0)
  {
  int n;
  int o = _viewer->Lookup(cursor_, n);
    // a -1 result means: "don't know, please scan all"
  if (o < 0)
    return count_ > 0;

  if (n > 0)
  {
    if (pos_ < o)
    {
    count_ -= o - pos_;
    pos_ = o;
    }

    if (pos_ + count_ > o + n)
    count_ = o + n - pos_;

    if (count_ > 0)
    return true;
  }
  }

  count_ = 0;
  return false;
}

void c4_CustomSeq::InsertAt(int p_, c4_Cursor c_, int n_)
{
  _viewer->InsertRows(p_, c_, n_);
}

void c4_CustomSeq::RemoveAt(int p_, int n_)
{
  _viewer->RemoveRows(p_, n_);
}

void c4_CustomSeq::Move(int, int)
{
  d4_assert(false); //! not yet
}

bool c4_CustomSeq::DoGet(int row_, int col_, c4_Bytes& buf_) const
{
  d4_assert(_inited);

  return _viewer->GetItem(row_, col_, buf_);
}

void c4_CustomSeq::DoSet(int row_, int col_, const c4_Bytes& buf_)
{
  d4_assert(_inited);

  d4_dbgdef(const bool f =)
    _viewer->SetItem(row_, col_, buf_);
  d4_assert(f);
}

/////////////////////////////////////////////////////////////////////////////

/** @class c4_CustomViewer
 *
 *  Abstract base class for definition of custom views.
 *
 *  A custom view is a view which can be accessed like any other view, using
 *  row and property operations, but which is fully managed by a customized
 *  "viewer" class.  The viewer will eventually handle all requests for the
 *  view, such as defining its structure and size, as well as providing the
 *  actual data values when requested.
 *
 *  Custom views cannot propagate changes.
 *
 *  To implement a custom view, you must derive your viewer from this base
 *  class and define each of the virtual members.  Then create a new object
 *  of this type on the heap and pass it to the c4_View constructor.  Your
 *  viewer will automatically be destroyed when the last reference to its
 *  view goes away.  See the DBF2MK sample code for an example of a viewer.
 */

c4_CustomViewer::~c4_CustomViewer ()
{
}

  /// Locate a row in this view, try to use native searches
int c4_CustomViewer::Lookup(c4_Cursor, int& count_)
{
  count_ = GetSize();
  return 0; // not implemented, return entire view range
}

  /// Store one data item, supplied as a generic data value
bool c4_CustomViewer::SetItem(int, int, const c4_Bytes&)
{
  return false; // default is not modifiable
}

  /// Insert one or more copies of a row (if possible)
bool c4_CustomViewer::InsertRows(int, c4_Cursor, int)
{
  return false; // default is not modifiable
}

  /// Remove one or more rows (this is not always possible)
bool c4_CustomViewer::RemoveRows(int, int)
{
  return false; // default is not modifiable
}

/////////////////////////////////////////////////////////////////////////////

class c4_SliceViewer : public c4_CustomViewer
{
  c4_View _tqparent;
  int _first, _limit, _step;

public: 
  c4_SliceViewer (c4_Sequence& seq_, int first_, int limit_, int step_);
  virtual ~c4_SliceViewer ();
  
  virtual c4_View GetTemplate();
  virtual int GetSize();
  virtual bool GetItem(int row_, int col_, c4_Bytes& buf_);
  bool SetItem(int row_, int col_, const c4_Bytes& buf_);
  virtual bool InsertRows(int pos_, c4_Cursor value_, int count_=1);
  virtual bool RemoveRows(int pos_, int count_=1);
};

c4_SliceViewer::c4_SliceViewer (c4_Sequence& seq_, int first_, int limit_, int step_)
  : _tqparent (&seq_), _first (first_), _limit (limit_), _step (step_)
{
  d4_assert(_step != 0);
}

c4_SliceViewer::~c4_SliceViewer ()
{
}

c4_View c4_SliceViewer::GetTemplate()
{
  return _tqparent.Clone(); // could probably return _tqparent just as well
}

int c4_SliceViewer::GetSize()
{
  int n = _limit >= 0 ? _limit : _tqparent.GetSize();
  if (n < _first)
    n = _first;

  int k = _step < 0 ? -_step : _step;
  return (n - _first + k - 1) / k;
}

bool c4_SliceViewer::GetItem(int row_, int col_, c4_Bytes& buf_)
{
  row_ = _first + _step * (_step > 0 ? row_ : row_ - GetSize() + 1);

  return _tqparent.GetItem(row_, col_, buf_);
}

bool c4_SliceViewer::SetItem(int row_, int col_, const c4_Bytes& buf_)
{
  row_ = _first + _step * (_step > 0 ? row_ : row_ - GetSize() + 1);

  _tqparent.SetItem(row_, col_, buf_);
  return true;
}

bool c4_SliceViewer::InsertRows(int pos_, c4_Cursor value_, int count_)
{
  if (_step != 1)
  return false;

  pos_ = _first + _step * (_step > 0 ? pos_ : pos_ - GetSize() + 1);
  if (_limit >= 0)
  _limit += count_;

  _tqparent.InsertAt(pos_, *value_, count_);
  return true;
}

bool c4_SliceViewer::RemoveRows(int pos_, int count_)
{
  if (_step != 1)
  return false;

  pos_ = _first + _step * (_step > 0 ? pos_ : pos_ - GetSize() + 1);
  if (_limit >= 0)
  _limit -= count_;

  _tqparent.RemoveAt(pos_, count_);
  return true;
}

c4_CustomViewer* f4_CustSlice(c4_Sequence& seq_, int first_, int limit_, int step_)
{
  return d4_new c4_SliceViewer (seq_, first_, limit_, step_);
}

/////////////////////////////////////////////////////////////////////////////

class c4_ProductViewer : public c4_CustomViewer
{
  c4_View _tqparent, _argView, _template;

public: 
  c4_ProductViewer (c4_Sequence& seq_, const c4_View& view_);
  virtual ~c4_ProductViewer ();
  
  virtual c4_View GetTemplate();
  virtual int GetSize();
  virtual bool GetItem(int row_, int col_, c4_Bytes& buf_);
};

c4_ProductViewer::c4_ProductViewer (c4_Sequence& seq_, const c4_View& view_)
  : _tqparent (&seq_), _argView (view_), _template (_tqparent.Clone())
{
  for (int i = 0; i < _argView.NumProperties(); ++i)
    _template.AddProperty(_argView.NthProperty(i));
}

c4_ProductViewer::~c4_ProductViewer ()
{
}

c4_View c4_ProductViewer::GetTemplate()
{
  return _template;
}

int c4_ProductViewer::GetSize()
{
  return _tqparent.GetSize() * _argView.GetSize();
}

bool c4_ProductViewer::GetItem(int row_, int col_, c4_Bytes& buf_)
{
  c4_View v = _tqparent;

  if (col_ < v.NumProperties())
  {
    row_ /= _argView.GetSize();
  }
  else
  {
    v = _argView;
    row_ %= _argView.GetSize();
    col_ = v.FindProperty(_template.NthProperty(col_).GetId());
    
    d4_assert(col_ >= 0);
  }

  return v.GetItem(row_, col_, buf_);
}

c4_CustomViewer* f4_CustProduct(c4_Sequence& seq_, const c4_View& view_)
{
  return d4_new c4_ProductViewer (seq_, view_);
}

/////////////////////////////////////////////////////////////////////////////

class c4_RemapWithViewer : public c4_CustomViewer
{
  c4_View _tqparent, _argView;

public: 
  c4_RemapWithViewer (c4_Sequence& seq_, const c4_View& view_);
  virtual ~c4_RemapWithViewer ();
  
  virtual c4_View GetTemplate();
  virtual int GetSize();
  virtual bool GetItem(int row_, int col_, c4_Bytes& buf_);
  bool SetItem(int row_, int col_, const c4_Bytes& buf_);
};

c4_RemapWithViewer::c4_RemapWithViewer (c4_Sequence& seq_, const c4_View& view_)
  : _tqparent (&seq_), _argView (view_)
{
}

c4_RemapWithViewer::~c4_RemapWithViewer ()
{
}

c4_View c4_RemapWithViewer::GetTemplate()
{
  return _tqparent.Clone(); // could probably return _tqparent just as well
}

int c4_RemapWithViewer::GetSize()
{
  return _argView.GetSize();
}

bool c4_RemapWithViewer::GetItem(int row_, int col_, c4_Bytes& buf_)
{
  const c4_Property& map = _argView.NthProperty(0);
  d4_assert(map.Type() == 'I');

  row_ = ((const c4_IntProp&) map) (_argView[row_]);

  return _tqparent.GetItem(row_, col_, buf_);
}

bool c4_RemapWithViewer::SetItem(int row_, int col_, const c4_Bytes& buf_)
{
  const c4_Property& map = _argView.NthProperty(0);
  d4_assert(map.Type() == 'I');

  row_ = ((const c4_IntProp&) map) (_argView[row_]);

  _tqparent.SetItem(row_, col_, buf_);
  return true;
}

c4_CustomViewer* f4_CustRemapWith(c4_Sequence& seq_, const c4_View& view_)
{
  return d4_new c4_RemapWithViewer (seq_, view_);
}

/////////////////////////////////////////////////////////////////////////////

class c4_PairViewer : public c4_CustomViewer
{
  c4_View _tqparent, _argView, _template;

public: 
  c4_PairViewer (c4_Sequence& seq_, const c4_View& view_);
  virtual ~c4_PairViewer ();
  
  virtual c4_View GetTemplate();
  virtual int GetSize();
  virtual bool GetItem(int row_, int col_, c4_Bytes& buf_);
  bool SetItem(int row_, int col_, const c4_Bytes& buf_);
  virtual bool InsertRows(int pos_, c4_Cursor value_, int count_=1);
  virtual bool RemoveRows(int pos_, int count_=1);
};

c4_PairViewer::c4_PairViewer (c4_Sequence& seq_, const c4_View& view_)
  : _tqparent (&seq_), _argView (view_), _template (_tqparent.Clone())
{
  for (int i = 0; i < _argView.NumProperties(); ++i)
    _template.AddProperty(_argView.NthProperty(i));
}

c4_PairViewer::~c4_PairViewer ()
{
}

c4_View c4_PairViewer::GetTemplate()
{
  return _template;
}

int c4_PairViewer::GetSize()
{
  return _tqparent.GetSize();
}

bool c4_PairViewer::GetItem(int row_, int col_, c4_Bytes& buf_)
{
  c4_View v = _tqparent;

  if (col_ >= v.NumProperties())
  {
    v = _argView;
    col_ = v.FindProperty(_template.NthProperty(col_).GetId());
    d4_assert(col_ >= 0);
  }

  return v.GetItem(row_, col_, buf_);
}

bool c4_PairViewer::SetItem(int row_, int col_, const c4_Bytes& buf_)
{
  c4_View v = _tqparent;

  if (col_ >= v.NumProperties())
  {
    v = _argView;
    col_ = v.FindProperty(_template.NthProperty(col_).GetId());
    d4_assert(col_ >= 0);
  }

  v.SetItem(row_, col_, buf_);
  return true;
}

bool c4_PairViewer::InsertRows(int pos_, c4_Cursor value_, int count_)
{
  _tqparent.InsertAt(pos_, *value_, count_);
  _argView.InsertAt(pos_, *value_, count_);
  return true;
}

bool c4_PairViewer::RemoveRows(int pos_, int count_)
{
  _tqparent.RemoveAt(pos_, count_);
  _argView.RemoveAt(pos_, count_);
  return true;
}

c4_CustomViewer* f4_CustPair(c4_Sequence& seq_, const c4_View& view_)
{
  return d4_new c4_PairViewer (seq_, view_);
}

/////////////////////////////////////////////////////////////////////////////

class c4_ConcatViewer : public c4_CustomViewer
{
  c4_View _tqparent, _argView;

public: 
  c4_ConcatViewer (c4_Sequence& seq_, const c4_View& view_);
  virtual ~c4_ConcatViewer ();
  
  virtual c4_View GetTemplate();
  virtual int GetSize();
  virtual bool GetItem(int row_, int col_, c4_Bytes& buf_);
  bool SetItem(int row_, int col_, const c4_Bytes& buf_);
};

c4_ConcatViewer::c4_ConcatViewer (c4_Sequence& seq_, const c4_View& view_)
  : _tqparent (&seq_), _argView (view_)
{
}

c4_ConcatViewer::~c4_ConcatViewer ()
{
}

c4_View c4_ConcatViewer::GetTemplate()
{
  return _tqparent.Clone(); // could probably return _tqparent just as well
}

int c4_ConcatViewer::GetSize()
{
  return _tqparent.GetSize() + _argView.GetSize();
}

bool c4_ConcatViewer::GetItem(int row_, int col_, c4_Bytes& buf_)
{
  c4_View v = _tqparent;

  if (row_ >= _tqparent.GetSize())
  {
    v = _argView;
    row_ -= _tqparent.GetSize();
    col_ = v.FindProperty(_tqparent.NthProperty(col_).GetId());
    
    if (col_ < 0)
      return false;
  }

  return v.GetItem(row_, col_, buf_);
}

bool c4_ConcatViewer::SetItem(int row_, int col_, const c4_Bytes& buf_)
{
  c4_View v = _tqparent;

  if (row_ >= _tqparent.GetSize())
  {
    v = _argView;
    row_ -= _tqparent.GetSize();
    col_ = v.FindProperty(_tqparent.NthProperty(col_).GetId());
    d4_assert(col_ >= 0);
  }

  v.SetItem(row_, col_, buf_);
  return true;
}

c4_CustomViewer* f4_CustConcat(c4_Sequence& seq_, const c4_View& view_)
{
  return d4_new c4_ConcatViewer (seq_, view_);
}

/////////////////////////////////////////////////////////////////////////////

class c4_RenameViewer : public c4_CustomViewer
{
  c4_View _tqparent, _template;

public: 
  c4_RenameViewer (c4_Sequence& seq_, const c4_Property& old_,
                    const c4_Property& new_);
  virtual ~c4_RenameViewer ();
  
  virtual c4_View GetTemplate();
  virtual int GetSize();
  virtual bool GetItem(int row_, int col_, c4_Bytes& buf_);
  virtual bool SetItem(int row_, int col_, const c4_Bytes& buf_);
  //virtual bool InsertRows(int pos_, c4_Cursor value_, int count_=1);
  //virtual bool RemoveRows(int pos_, int count_=1);
};

c4_RenameViewer::c4_RenameViewer (c4_Sequence& seq_, const c4_Property& old_,
                           const c4_Property& new_)
  : _tqparent (&seq_)
{
  for (int i = 0; i < _tqparent.NumProperties(); ++i)
  {
    const c4_Property& prop = _tqparent.NthProperty(i);
    _template.AddProperty(prop.GetId() == old_.GetId() ? new_ : prop);
  }
}

c4_RenameViewer::~c4_RenameViewer ()
{
}

c4_View c4_RenameViewer::GetTemplate()
{
  return _template;
}

int c4_RenameViewer::GetSize()
{
  return _tqparent.GetSize();
}

bool c4_RenameViewer::GetItem(int row_, int col_, c4_Bytes& buf_)
{
  return _tqparent.GetItem(row_, col_, buf_);
}

bool c4_RenameViewer::SetItem(int row_, int col_, const c4_Bytes& buf_)
{
  _tqparent.SetItem(row_, col_, buf_);
  return true;
}

c4_CustomViewer* f4_CustRename(c4_Sequence& seq_, const c4_Property& old_,
                           const c4_Property& new_)
{
  return d4_new c4_RenameViewer (seq_, old_, new_);
}

/////////////////////////////////////////////////////////////////////////////

class c4_GroupByViewer : public c4_CustomViewer
{
  c4_View _tqparent, _keys, _sorted, _temp;
  c4_Property _result;
  c4_DWordArray _map;

  int ScanTransitions(int lo_, int hi_,
              t4_byte* flags_, const c4_View& match_) const;

public: 
  c4_GroupByViewer (c4_Sequence& seq_, const c4_View& keys_,
                      const c4_Property& result_);
  virtual ~c4_GroupByViewer ();
  
  virtual c4_View GetTemplate();
  virtual int GetSize();
  virtual bool GetItem(int row_, int col_, c4_Bytes& buf_);
};

c4_GroupByViewer::c4_GroupByViewer (c4_Sequence& seq_, const c4_View& keys_,
                           const c4_Property& result_)
  : _tqparent (&seq_), _keys (keys_), _result (result_)
{
  _sorted = _tqparent.SortOn(_keys);
  int n = _sorted.GetSize();

  c4_Bytes temp;
  t4_byte* buf = temp.SetBufferClear(n);

  int groups = 0;
  if (n > 0)
  {
    ++buf[0]; // the first entry is always a transition
    groups = 1 + ScanTransitions(1, n, buf, _sorted.Project(_keys));
  }

    // set up a map pointing to each transition
  _map.SetSize(groups + 1);
  int j = 0;

  for (int i = 0; i < n; ++i)
    if (buf[i])
      _map.SetAt(j++, i);

    // also append an entry to point just past the end
  _map.SetAt(j, n);

  d4_assert(_map.GetAt(0) == 0);
  d4_assert(j == groups);
}

c4_GroupByViewer::~c4_GroupByViewer ()
{
}

int c4_GroupByViewer::ScanTransitions(int lo_, int hi_,
                    t4_byte* flags_, const c4_View& match_) const
{
  d4_assert(lo_ > 0);

  int m = hi_ - lo_;
  d4_assert(m >= 0);

    // done if nothing left or if entire range is identical
  if (m == 0 || match_ [lo_-1] == match_ [hi_-1])
    return 0;

    // range has a transition, done if it is exactly of size one
  if (m == 1)
  {
    ++(flags_[lo_]);
    return 1;
  }

    // use binary splitting if the range has enough entries
  if (m >= 5)
    return ScanTransitions(lo_, lo_ + m / 2, flags_, match_) +
        ScanTransitions(lo_ + m / 2, hi_, flags_, match_);

    // else use a normal linear scan
  int n = 0;

  for (int i = lo_; i < hi_; ++i)
    if (match_ [i] != match_ [i-1])
    {
      ++(flags_[i]);
      ++n;
    }

  return n;
}

c4_View c4_GroupByViewer::GetTemplate()
{
  c4_View v = _keys.Clone();
  v.AddProperty(_result);

  return v;
}

int c4_GroupByViewer::GetSize()
{
  d4_assert(_map.GetSize() > 0);

  return _map.GetSize() - 1;
}

bool c4_GroupByViewer::GetItem(int row_, int col_, c4_Bytes& buf_)
{
  if (col_ < _keys.NumProperties())
    return _sorted.GetItem(_map.GetAt(row_), col_, buf_);

  d4_assert(col_ == _keys.NumProperties());
  
  t4_i32 count;
  switch (_result.Type())
  {
    case 'I': count = _map.GetAt(row_ + 1) - _map.GetAt(row_);
          buf_ = c4_Bytes (&count, sizeof count, true);
          break;
    case 'V': _temp = _sorted.Slice(_map.GetAt(row_), _map.GetAt(row_ + 1))
                .ProjectWithout(_keys);
          buf_ = c4_Bytes (&_temp, sizeof _temp, true);
          break;
    default:  d4_assert(0);
  }

  return true;
}

c4_CustomViewer* f4_CustGroupBy(c4_Sequence& seq_, const c4_View& template_,
                           const c4_Property& result_)
{
  return d4_new c4_GroupByViewer (seq_, template_, result_);
}

/////////////////////////////////////////////////////////////////////////////

class c4_JoinPropViewer : public c4_CustomViewer
{
  c4_View _tqparent, _template;
  c4_ViewProp _sub;
  int _subPos, _subWidth;
  c4_DWordArray _base, _offset;

public: 
  c4_JoinPropViewer (c4_Sequence& seq_, const c4_ViewProp& sub_, bool outer_);
  virtual ~c4_JoinPropViewer ();
  
  virtual c4_View GetTemplate();
  virtual int GetSize();
  virtual bool GetItem(int row_, int col_, c4_Bytes& buf_);
};

c4_JoinPropViewer::c4_JoinPropViewer (c4_Sequence& seq_,
                    const c4_ViewProp& sub_, bool outer_)
  : _tqparent (&seq_),
    _sub (sub_), _subPos (_tqparent.FindProperty(sub_.GetId())), _subWidth (0)
{
  d4_assert(_subPos >= 0);

  for (int k = 0; k < _tqparent.NumProperties(); ++k)
  {
    if (k != _subPos)
      _template.AddProperty(_tqparent.NthProperty(k));
    else  // if there are no rows, then this join does very little anyway
        //! OOPS: if this is an unattached view, then the subviews can differ
      if (_tqparent.GetSize() > 0)
      {
        c4_View view = sub_ (_tqparent[0]);
        for (int l = 0; l < view.NumProperties(); ++l)
        {
          _template.AddProperty(view.NthProperty(l));
          ++_subWidth;
        }
      }
  }

  _base.SetSize(0, 5);
  _offset.SetSize(0, 5);

  for (int i = 0; i < _tqparent.GetSize(); ++i)
  {
    c4_View v = _sub (_tqparent[i]);

    int n = v.GetSize();
    if (n == 0 && outer_)
    {
      _base.Add(i);
      _offset.Add(~ (t4_i32) 0);  // special null entry for outer joins
    }
    else
      for (int j = 0; j < n; ++j)
      {
        _base.Add(i);
        _offset.Add(j);
      }
  }
}

c4_JoinPropViewer::~c4_JoinPropViewer ()
{
}

c4_View c4_JoinPropViewer::GetTemplate()
{
  return _template;
}

int c4_JoinPropViewer::GetSize()
{
  return _base.GetSize();
}

bool c4_JoinPropViewer::GetItem(int row_, int col_, c4_Bytes& buf_)
{
  c4_View v = _tqparent;
  int r = _base.GetAt(row_);

  if (col_ >= _subPos)
    if (col_ >= _subPos + _subWidth)
    {
      col_ -= _subWidth - 1;
    }
    else
    {
      v = _sub (_tqparent[r]);
      r = _offset.GetAt(row_);
      if (r < 0)
        return false; // if this is a null row in an outer join

      col_ = v.FindProperty(_template.NthProperty(col_).GetId());
      if (col_ < 0)
        return false; // if subview doesn't have all properties
    }

  return v.GetItem(r, col_, buf_);
}

c4_CustomViewer* f4_CustJoinProp(c4_Sequence& seq_,
                const c4_ViewProp& sub_, bool outer_)
{
  return d4_new c4_JoinPropViewer (seq_, sub_, outer_);
}

/////////////////////////////////////////////////////////////////////////////

class c4_JoinViewer : public c4_CustomViewer
{
  c4_View _tqparent, _argView, _template;
  c4_DWordArray _base, _offset;

public: 
  c4_JoinViewer (c4_Sequence& seq_, const c4_View& keys_,
              const c4_View& view_, bool outer_);
  virtual ~c4_JoinViewer ();
  
  virtual c4_View GetTemplate();
  virtual int GetSize();
  virtual bool GetItem(int row_, int col_, c4_Bytes& buf_);
};

c4_JoinViewer::c4_JoinViewer (c4_Sequence& seq_,const c4_View& keys_,
                const c4_View& view_, bool outer_)
  : _tqparent (&seq_), _argView (view_.SortOn(keys_))
{
    // why not in GetTemplate, since we don't need to know this...
  _template = _tqparent.Clone();
  for (int l = 0; l < _argView.NumProperties(); ++l)
    _template.AddProperty(_argView.NthProperty(l));

  c4_View sorted = _tqparent.SortOn(keys_).Project(keys_);
  c4_View temp = _argView.Project(keys_);

  _base.SetSize(0, 5);
  _offset.SetSize(0, 5);

  int j = 0, n = 0;

  for (int i = 0; i < sorted.GetSize(); ++i)
  {
    int orig = _tqparent.GetIndexOf(sorted[i]);
    d4_assert(orig >= 0);

    if (i > 0 && sorted[i] == sorted[i-1])
    {
        // if last key was same, repeat the same join
      int last = _offset.GetSize() - n;
      for (int k = 0; k < n; ++k)
      {
        _base.Add(orig);
        _offset.Add(_offset.GetAt(last + k));
      }
    }
    else  // no, this is a new combination
    {
      bool match = false;

        // advance until the temp view entry is >= this sorted entry
      while (j < temp.GetSize())
        if (sorted[i] <= temp[j])
        {
          match = sorted[i] == temp[j];
          break;
        }
        else
          ++j;

      n = 0;

      if (match)
      {
        do {
          _base.Add(orig);
          _offset.Add(j);
          ++n;
        } while (++j < temp.GetSize() && temp[j] == temp[j-1]);
      }
      else if (outer_)
      {
          // no match, add an entry anyway if this is an outer join
        _base.Add(orig);
        _offset.Add(~ (t4_i32) 0);  // special null entry
        ++n;
      }
    }
  }
}

c4_JoinViewer::~c4_JoinViewer ()
{
}

c4_View c4_JoinViewer::GetTemplate()
{
  return _template;
}

int c4_JoinViewer::GetSize()
{
  return _base.GetSize();
}

bool c4_JoinViewer::GetItem(int row_, int col_, c4_Bytes& buf_)
{
  c4_View v = _tqparent;
  int r = _base.GetAt(row_);

  if (col_ >= v.NumProperties())
  {
    v = _argView;
    r = _offset.GetAt(row_);
    if (r < 0)
      return false; // if this is a null row in an outer join

    col_ = v.FindProperty(_template.NthProperty(col_).GetId());
    if (col_ < 0)
      return false; // if second view doesn't have all properties
  }

  return v.GetItem(r, col_, buf_);
}

#if 0
bool c4_JoinViewer::GetItem(int row_, int col_, c4_Bytes& buf_)
{
  c4_View v = _tqparent;

  int o = 0;
  int r = _offset.GetAt(row_);

  if (r < 0)
  {
    o = ~r;
    if (o == 0)
      return false; // if this is a null row in an outer join
    r -= o;
  }

  if (col_ >= v.NumProperties())
  {
    v = _argView;
    r = _o;

    col_ = v.FindProperty(_template.NthProperty(col_));
    if (col_ < 0)
      return false; // if second view doesn't have all properties
  }

  return v.GetItem(r, col_, buf_);
}
#endif

c4_CustomViewer* f4_CustJoin(c4_Sequence& seq_, const c4_View& keys_,
               const c4_View& view_, bool outer_)
{
  return d4_new c4_JoinViewer (seq_, keys_, view_, outer_);
}

/////////////////////////////////////////////////////////////////////////////