forked from johnkerl/miller
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mlrmap_accessors.go
923 lines (824 loc) · 23.1 KB
/
mlrmap_accessors.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
package mlrval
import (
"bytes"
"fmt"
"strconv"
"github.com/johnkerl/miller/internal/pkg/lib"
)
// IsEmpty determines if an map is empty.
func (mlrmap *Mlrmap) IsEmpty() bool {
return mlrmap.Head == nil
}
func (mlrmap *Mlrmap) Has(key string) bool {
return mlrmap.findEntry(key) != nil
}
func (mlrmap *Mlrmap) Get(key string) *Mlrval {
pe := mlrmap.findEntry(key)
if pe == nil {
return nil
} else {
return pe.Value
}
}
// PutReference copies the key but not the value. This is not safe for DSL use,
// where we could create undesired references between different objects. Only
// intended to be used at callsites which allocate a mlrval on the spot, solely
// for the purpose of putting into the map.
func (mlrmap *Mlrmap) PutReference(key string, value *Mlrval) {
pe := mlrmap.findEntry(key)
if pe == nil {
mlrmap.putReferenceNewAux(key, value)
} else {
pe.Value = value
}
}
// putReferenceNewAux is a helper function for code shared between PutReference
// and PutReferenceMaybeDedupe. It should not be invoked from anywhere else --
// it doesn't do its own check if the key already exists in the record or not.
func (mlrmap *Mlrmap) putReferenceNewAux(key string, value *Mlrval) {
pe := newMlrmapEntry(key, value)
if mlrmap.Head == nil {
mlrmap.Head = pe
mlrmap.Tail = pe
} else {
pe.Prev = mlrmap.Tail
pe.Next = nil
mlrmap.Tail.Next = pe
mlrmap.Tail = pe
}
if mlrmap.keysToEntries != nil {
mlrmap.keysToEntries[key] = pe
}
mlrmap.FieldCount++
}
// PutReferenceMaybeDedupe is the default inserter for key-value pairs in input records --
// if the input is 'x=8,x=9` then we make a record with x=8 and x_2=9. This can be suppressed
// via a command-line flag which this method's dedupe flag respects.
func (mlrmap *Mlrmap) PutReferenceMaybeDedupe(key string, value *Mlrval, dedupe bool) (string, error) {
if !dedupe {
mlrmap.PutReference(key, value)
return key, nil
}
pe := mlrmap.findEntry(key)
if pe == nil {
mlrmap.putReferenceNewAux(key, value)
return key, nil
}
for i := 2; i < 1000; i++ {
newKey := key + "_" + strconv.Itoa(i)
pe := mlrmap.findEntry(newKey)
if pe == nil {
mlrmap.putReferenceNewAux(newKey, value)
return newKey, nil
}
}
return key, fmt.Errorf("record has too many input fields named \"%s\"", key)
}
// PutCopy copies the key and value (deep-copying in case the value is array/map).
// This is safe for DSL use. See also PutReference.
func (mlrmap *Mlrmap) PutCopy(key string, value *Mlrval) {
pe := mlrmap.findEntry(key)
if pe == nil {
pe = newMlrmapEntry(key, value.Copy())
if mlrmap.Head == nil {
mlrmap.Head = pe
mlrmap.Tail = pe
} else {
pe.Prev = mlrmap.Tail
pe.Next = nil
mlrmap.Tail.Next = pe
mlrmap.Tail = pe
}
if mlrmap.keysToEntries != nil {
mlrmap.keysToEntries[key] = pe
}
mlrmap.FieldCount++
} else {
pe.Value = value.Copy()
}
}
// PrependReference is the same as PutReference, but puts a new entry first, not last.
func (mlrmap *Mlrmap) PrependReference(key string, value *Mlrval) {
pe := mlrmap.findEntry(key)
if pe == nil {
pe = newMlrmapEntry(key, value)
if mlrmap.Tail == nil {
mlrmap.Head = pe
mlrmap.Tail = pe
} else {
pe.Prev = nil
pe.Next = mlrmap.Head
mlrmap.Head.Prev = pe
mlrmap.Head = pe
}
if mlrmap.keysToEntries != nil {
mlrmap.keysToEntries[key] = pe
}
mlrmap.FieldCount++
} else {
pe.Value = value
}
}
// TODO: COMMENT
func (mlrmap *Mlrmap) PutReferenceAfter(
pe *MlrmapEntry,
key string,
value *Mlrval,
) *MlrmapEntry {
if pe == nil || pe.Next == nil {
// New entry is supposed to go 'after' old, but there is no such old
// entry. Or, the old entry exists and is at the tail. In either case,
// add the new entry at the end of the record (new tail).
// TODO: make a helper method for code-dedupe
pf := newMlrmapEntry(key, value)
if mlrmap.Head == nil { // First entry into empty map
mlrmap.Head = pf
mlrmap.Tail = pf
} else {
// Before: ... pc pd
// After: ... pc pd pf
pf.Prev = mlrmap.Tail
pf.Next = nil
mlrmap.Tail.Next = pf
mlrmap.Tail = pf
}
if mlrmap.keysToEntries != nil {
mlrmap.keysToEntries[key] = pf
}
mlrmap.FieldCount++
return pf
} else {
// Before: ... pe pg ...
// After: ... pe pf pg ...
//
// New entry is neither the new head (pe != nil) nor the new tail
// (pe.Next != nil, otherwise we'd be in the if-branch above).
pf := newMlrmapEntry(key, value)
pg := pe.Next
pe.Next = pf
pf.Next = pg
pf.Prev = pe
if pg != nil {
pg.Prev = pf
}
if mlrmap.keysToEntries != nil {
mlrmap.keysToEntries[key] = pf
}
mlrmap.FieldCount++
return pf
}
}
// findEntry is the basic hash-map accessor for Has, Put, Get, Remove, etc.
// Hashmaps in Go are a built-in type; Mlrmap is (a)
// insertion-order-preserving, and (b) supports either hashed or non-hashed
// access.
func (mlrmap *Mlrmap) findEntry(key string) *MlrmapEntry {
if mlrmap.keysToEntries != nil {
return mlrmap.keysToEntries[key]
} else {
for pe := mlrmap.Head; pe != nil; pe = pe.Next {
if pe.Key == key {
return pe
}
}
return nil
}
}
// findEntryByPositionalIndex is for '$[1]' etc. in the DSL.
//
// Notes:
// * This is a linear search.
// * Indices are 1-up not 0-up
// * Indices -n..-1 are aliases for 1..n. In particular, it will be faster to
// get the -1st field than the nth.
// * Returns 0 on invalid index: 0, or < -n, or > n where n is the number of
// fields.
func (mlrmap *Mlrmap) findEntryByPositionalIndex(position int64) *MlrmapEntry {
if position > mlrmap.FieldCount || position < -mlrmap.FieldCount || position == 0 {
return nil
}
if position > 0 {
var i int64 = 1
for pe := mlrmap.Head; pe != nil; pe = pe.Next {
if i == position {
return pe
}
i++
}
lib.InternalCodingErrorIf(true)
} else {
var i int64 = -1
for pe := mlrmap.Tail; pe != nil; pe = pe.Prev {
if i == position {
return pe
}
i--
}
lib.InternalCodingErrorIf(true)
}
lib.InternalCodingErrorIf(true)
return nil
}
func (mlrmap *Mlrmap) PutCopyWithMlrvalIndex(key *Mlrval, value *Mlrval) error {
if key.IsStringOrInt() {
mlrmap.PutCopy(key.String(), value)
return nil
} else {
return fmt.Errorf(
"mlr: record/map indices must be string, int, or array thereof; got %s", key.GetTypeName(),
)
}
}
// ----------------------------------------------------------------
func (mlrmap *Mlrmap) PrependCopy(key string, value *Mlrval) {
mlrmap.PrependReference(key, value.Copy())
}
// ----------------------------------------------------------------
// Merges that into mlrmap.
func (mlrmap *Mlrmap) Merge(other *Mlrmap) {
for pe := other.Head; pe != nil; pe = pe.Next {
mlrmap.PutCopy(pe.Key, pe.Value)
}
}
// ----------------------------------------------------------------
// Exposed for the 'nest' verb
func (mlrmap *Mlrmap) GetEntry(key string) *MlrmapEntry {
return mlrmap.findEntry(key)
}
func (mlrmap *Mlrmap) GetKeys() []string {
keys := make([]string, mlrmap.FieldCount)
i := 0
for pe := mlrmap.Head; pe != nil; pe = pe.Next {
keys[i] = pe.Key
i++
}
return keys
}
// ----------------------------------------------------------------
// TODO: put error-return into this API
func (mlrmap *Mlrmap) PutNameWithPositionalIndex(position int64, name *Mlrval) {
positionalEntry := mlrmap.findEntryByPositionalIndex(position)
if positionalEntry == nil {
// TODO: handle out-of-bounds accesses
return
}
s := ""
if name.IsString() || name.IsInt() {
s = name.String()
} else {
// TODO: return MlrvalFromError()
return
}
// E.g. there are fields named 'a' and 'b', as positions 1 and 2,
// and the user does '$[[1]] = $[[2]]'. Then there would be two b's.
mapEntry := mlrmap.findEntry(s)
if mapEntry != nil && mapEntry != positionalEntry {
if mlrmap.keysToEntries != nil {
delete(mlrmap.keysToEntries, positionalEntry.Key)
}
mlrmap.Unlink(mapEntry)
}
lib.InternalCodingErrorIf(s == "")
positionalEntry.Key = s
if mlrmap.keysToEntries != nil {
mlrmap.keysToEntries[s] = positionalEntry
}
}
func (mlrmap *Mlrmap) GetWithPositionalIndex(position int64) *Mlrval {
mapEntry := mlrmap.findEntryByPositionalIndex(position)
if mapEntry == nil {
return nil
}
return mapEntry.Value
}
func (mlrmap *Mlrmap) GetWithMlrvalIndex(index *Mlrval) (*Mlrval, error) {
if index.IsArray() {
return mlrmap.getWithMlrvalArrayIndex(index)
} else {
return mlrmap.getWithMlrvalSingleIndex(index)
}
}
// This lets the user do '$y = $x[ ["a", "b", "c"] ]' in lieu of
// '$y = $x["a"]["b"]["c"]'.
func (mlrmap *Mlrmap) getWithMlrvalArrayIndex(index *Mlrval) (*Mlrval, error) {
current := mlrmap
var retval *Mlrval = nil
lib.InternalCodingErrorIf(!index.IsArray())
array := index.arrayval
n := len(array)
for i, piece := range array {
next, err := current.GetWithMlrvalIndex(piece)
if err != nil {
return nil, err
}
if i < n-1 {
if !next.IsMap() {
return nil, fmt.Errorf("mlr: cannot multi-index non-map.")
}
current = next.mapval
} else {
retval = next.Copy()
}
}
lib.InternalCodingErrorIf(retval == nil)
return retval, nil
}
func (mlrmap *Mlrmap) getWithMlrvalSingleIndex(index *Mlrval) (*Mlrval, error) {
if index.IsString() {
return mlrmap.Get(index.printrep), nil
} else if index.IsInt() {
return mlrmap.Get(index.String()), nil
} else {
return nil, fmt.Errorf(
"Record/map indices must be string, int, or array thereof; got %s", index.GetTypeName(),
)
}
}
// For '$[[1]]' etc. in the DSL.
//
// Notes:
// * This is a linear search.
// * Indices are 1-up not 0-up
// * Indices -n..-1 are aliases for 1..n. In particular, it will be faster to
// get the -1st field than the nth.
// * Returns 0 on invalid index: 0, or < -n, or > n where n is the number of
// fields.
func (mlrmap *Mlrmap) GetNameAtPositionalIndex(position int64) (string, bool) {
mapEntry := mlrmap.findEntryByPositionalIndex(position)
if mapEntry == nil {
return "", false
}
return mapEntry.Key, true
}
// ----------------------------------------------------------------
// Copies the key and value (deep-copying in case the value is array/map).
// This is safe for DSL use. See also PutReference.
// TODO: put error-return into this API
func (mlrmap *Mlrmap) PutCopyWithPositionalIndex(position int64, value *Mlrval) {
mapEntry := mlrmap.findEntryByPositionalIndex(position)
if mapEntry != nil {
mapEntry.Value = value.Copy()
} else {
return
}
}
func (mlrmap *Mlrmap) RemoveWithPositionalIndex(position int64) {
mapEntry := mlrmap.findEntryByPositionalIndex(position)
if mapEntry != nil {
mlrmap.Unlink(mapEntry)
}
}
// ----------------------------------------------------------------
func (mlrmap *Mlrmap) Equals(other *Mlrmap) bool {
if mlrmap.FieldCount != other.FieldCount {
return false
}
if !mlrmap.Contains(other) {
return false
}
if !other.Contains(mlrmap) {
return false
}
return true
}
// True if this contains other, i.e. if other is contained by mlrmap.
// * If any key of other is not a key of this, return false.
// * If any key of other has a value unequal to this' value at the same key, return false.
// * Else return true
func (mlrmap *Mlrmap) Contains(other *Mlrmap) bool {
for pe := other.Head; pe != nil; pe = pe.Next {
if !mlrmap.Has(pe.Key) {
return false
}
thisval := mlrmap.Get(pe.Key)
thatval := pe.Value
if !Equals(thisval, thatval) {
return false
}
}
return true
}
func (mlrmap *Mlrmap) Clear() {
mlrmap.FieldCount = 0
// Assuming everything unreferenced is getting GC'ed by the Go runtime
mlrmap.Head = nil
mlrmap.Tail = nil
if mlrmap.keysToEntries != nil {
mlrmap.keysToEntries = make(map[string]*MlrmapEntry)
}
}
// ----------------------------------------------------------------
func (mlrmap *Mlrmap) Copy() *Mlrmap {
other := NewMlrmapMaybeHashed(mlrmap.isHashed())
for pe := mlrmap.Head; pe != nil; pe = pe.Next {
other.PutCopy(pe.Key, pe.Value)
}
return other
}
// Returns true if it was found and removed
func (mlrmap *Mlrmap) Remove(key string) bool {
pe := mlrmap.findEntry(key)
if pe == nil {
return false
} else {
mlrmap.Unlink(pe)
return true
}
}
func (mlrmap *Mlrmap) MoveToHead(key string) {
pe := mlrmap.findEntry(key)
if pe != nil {
mlrmap.Unlink(pe)
mlrmap.linkAtHead(pe)
}
}
func (mlrmap *Mlrmap) MoveToTail(key string) {
pe := mlrmap.findEntry(key)
if pe != nil {
mlrmap.Unlink(pe)
mlrmap.linkAtTail(pe)
}
}
// ----------------------------------------------------------------
// E.g. '$name[1]["foo"] = "bar"' or '$*["foo"][1] = "bar"'
// In the former case the indices are ["name", 1, "foo"] and in the latter case
// the indices are ["foo", 1]. See also indexed-lvalues.md.
//
// This is a Mlrmap (from string to Mlrval) so we handle the first level of
// indexing here, then pass the remaining indices to the Mlrval at the desired
// slot.
func (mlrmap *Mlrmap) PutIndexed(indices []*Mlrval, rvalue *Mlrval) error {
return putIndexedOnMap(mlrmap, indices, rvalue)
}
func (mlrmap *Mlrmap) RemoveIndexed(indices []*Mlrval) error {
return removeIndexedOnMap(mlrmap, indices)
}
// ----------------------------------------------------------------
func (mlrmap *Mlrmap) GetKeysJoined() string {
var buffer bytes.Buffer
i := 0
for pe := mlrmap.Head; pe != nil; pe = pe.Next {
if i > 0 {
buffer.WriteString(",")
}
i++
buffer.WriteString(pe.Key)
}
return buffer.String()
}
// For mlr reshape
func (mlrmap *Mlrmap) GetValuesJoined() string {
var buffer bytes.Buffer
i := 0
for pe := mlrmap.Head; pe != nil; pe = pe.Next {
if i > 0 {
buffer.WriteString(",")
}
i++
buffer.WriteString(pe.Value.String())
}
return buffer.String()
}
// ----------------------------------------------------------------
// For group-by in several transformers. If the record is 'a=x,b=y,c=3,d=4,e=5' and
// selectedFieldNames is 'a,b,c' then values are 'x,y,3'. This is returned as a
// comma-joined string. The boolean ok is false if not all selected field
// names were present in the record.
//
// It's OK for the selected-field-namees list to be empty. This happens for
// transformers which support a -g option but are invoked without it (e.g. 'mlr tail
// -n 1' vs 'mlr tail -n 1 -g a,b,c'). In this case the return value is simply
// the empty string.
func (mlrmap *Mlrmap) GetSelectedValuesJoined(selectedFieldNames []string) (string, bool) {
if len(selectedFieldNames) == 0 {
// The fall-through is functionally correct, but this is quicker with
// skipping setting up an empty bytes-buffer and stringifying it. The
// non-grouped case is quite normal and is worth optimizing for.
return "", true
}
var buffer bytes.Buffer
for i, selectedFieldName := range selectedFieldNames {
entry := mlrmap.findEntry(selectedFieldName)
if entry == nil {
return "", false
}
if i > 0 {
buffer.WriteString(",")
}
// This may be an array or map, or just a string/int/etc. Regardless we
// stringify it.
buffer.WriteString(entry.Value.String())
}
return buffer.String(), true
}
// As with GetSelectedValuesJoined but also returning the array of mlrvals.
// For sort.
// TODO: put 'Copy' into the method name
func (mlrmap *Mlrmap) GetSelectedValuesAndJoined(selectedFieldNames []string) (
string,
[]*Mlrval,
bool,
) {
mlrvals := make([]*Mlrval, 0, len(selectedFieldNames))
if len(selectedFieldNames) == 0 {
// The fall-through is functionally correct, but this is quicker with
// skipping setting up an empty bytes-buffer and stringifying it. The
// non-grouped case is quite normal and is worth optimizing for.
return "", mlrvals, true
}
var buffer bytes.Buffer
for i, selectedFieldName := range selectedFieldNames {
entry := mlrmap.findEntry(selectedFieldName)
if entry == nil {
return "", mlrvals, false
}
if i > 0 {
buffer.WriteString(",")
}
// This may be an array or map, or just a string/int/etc. Regardless we
// stringify it.
buffer.WriteString(entry.Value.String())
mlrvals = append(mlrvals, entry.Value.Copy())
}
return buffer.String(), mlrvals, true
}
// As above but only returns the array. Also, these are references, NOT copies.
// For step and join.
func (mlrmap *Mlrmap) ReferenceSelectedValues(selectedFieldNames []string) ([]*Mlrval, bool) {
allFound := true
mlrvals := make([]*Mlrval, 0, len(selectedFieldNames))
for _, selectedFieldName := range selectedFieldNames {
entry := mlrmap.findEntry(selectedFieldName)
if entry != nil {
mlrvals = append(mlrvals, entry.Value)
} else {
mlrvals = append(mlrvals, nil)
allFound = false
}
}
return mlrvals, allFound
}
// TODO: rename to CopySelectedValues
// As previous but with copying. For stats1.
func (mlrmap *Mlrmap) GetSelectedValues(selectedFieldNames []string) ([]*Mlrval, bool) {
allFound := true
mlrvals := make([]*Mlrval, 0, len(selectedFieldNames))
for _, selectedFieldName := range selectedFieldNames {
entry := mlrmap.findEntry(selectedFieldName)
if entry != nil {
mlrvals = append(mlrvals, entry.Value.Copy())
} else {
mlrvals = append(mlrvals, nil)
allFound = false
}
}
return mlrvals, allFound
}
// Similar to the above but only checks availability. For join.
func (mlrmap *Mlrmap) HasSelectedKeys(selectedFieldNames []string) bool {
for _, selectedFieldName := range selectedFieldNames {
entry := mlrmap.findEntry(selectedFieldName)
if entry == nil {
return false
}
}
return true
}
// ----------------------------------------------------------------
// For mlr nest implode across records.
func (mlrmap *Mlrmap) GetKeysJoinedExcept(px *MlrmapEntry) string {
var buffer bytes.Buffer
i := 0
for pe := mlrmap.Head; pe != nil; pe = pe.Next {
if pe == px {
continue
}
if i > 0 {
buffer.WriteString(",")
}
i++
buffer.WriteString(pe.Key)
}
return buffer.String()
}
// For mlr nest implode across records.
func (mlrmap *Mlrmap) GetValuesJoinedExcept(px *MlrmapEntry) string {
var buffer bytes.Buffer
i := 0
for pe := mlrmap.Head; pe != nil; pe = pe.Next {
if pe == px {
continue
}
if i > 0 {
buffer.WriteString(",")
}
i++
// This may be an array or map, or just a string/int/etc. Regardless we
// stringify it.
buffer.WriteString(pe.Value.String())
}
return buffer.String()
}
// ----------------------------------------------------------------
func (mlrmap *Mlrmap) Rename(oldKey string, newKey string) bool {
entry := mlrmap.findEntry(oldKey)
if entry == nil {
// Rename field from 'a' to 'b' where there is no 'a': no-op
return false
}
existing := mlrmap.findEntry(newKey)
if existing == nil {
// Rename field from 'a' to 'b' where there is no 'b': simple update
entry.Key = newKey
if mlrmap.keysToEntries != nil {
delete(mlrmap.keysToEntries, oldKey)
mlrmap.keysToEntries[newKey] = entry
}
} else {
// Rename field from 'a' to 'b' where there are both 'a' and 'b':
// remove old 'a' and put its value into the slot of 'b'.
existing.Value = entry.Value
if mlrmap.keysToEntries != nil {
delete(mlrmap.keysToEntries, oldKey)
}
mlrmap.Unlink(entry)
}
return true
}
// ----------------------------------------------------------------
func (mlrmap *Mlrmap) Label(newNames []string) {
other := NewMlrmapAsRecord()
i := 0
numNewNames := len(newNames)
for {
if i >= numNewNames {
break
}
pe := mlrmap.pop()
if pe == nil {
break
}
// Old record will be GC'ed: just move pointers
other.PutReference(newNames[i], pe.Value)
i++
}
for {
pe := mlrmap.pop()
if pe == nil {
break
}
// Example:
// * Input record has keys a,b,i,x,y
// * Requested labeling is d,x,f
// * The first three records a,b,i should be renamed to d,x,f
// * The old x needs to disappear (for key-uniqueness)
// * The y field is carried through
if other.Has(pe.Key) {
continue
}
other.PutReference(pe.Key, pe.Value)
}
*mlrmap = *other
}
// ----------------------------------------------------------------
func (mlrmap *Mlrmap) SortByKey() {
keys := mlrmap.GetKeys()
lib.SortStrings(keys)
other := NewMlrmapAsRecord()
for _, key := range keys {
// Old record will be GC'ed: just move pointers
other.PutReference(key, mlrmap.Get(key))
}
*mlrmap = *other
}
// ----------------------------------------------------------------
func (mlrmap *Mlrmap) SortByKeyRecursively() {
keys := mlrmap.GetKeys()
lib.SortStrings(keys)
other := NewMlrmapAsRecord()
for _, key := range keys {
// Old record will be GC'ed: just move pointers
value := mlrmap.Get(key)
if value.IsMap() {
value.mapval.SortByKeyRecursively()
}
other.PutReference(key, value)
}
*mlrmap = *other
}
// ----------------------------------------------------------------
// Only checks to see if the first entry is a map. For emit/emitp.
func (mlrmap *Mlrmap) IsNested() bool {
if mlrmap.Head == nil {
return false
} else if mlrmap.Head.Value.GetMap() == nil {
//TODO: check IsArrayOrMap()
return false
} else {
return true
}
}
// ================================================================
// PRIVATE METHODS
func (mlrmap *Mlrmap) Unlink(pe *MlrmapEntry) {
if pe == mlrmap.Head {
if pe == mlrmap.Tail {
mlrmap.Head = nil
mlrmap.Tail = nil
} else {
mlrmap.Head = pe.Next
pe.Next.Prev = nil
}
} else {
pe.Prev.Next = pe.Next
if pe == mlrmap.Tail {
mlrmap.Tail = pe.Prev
} else {
pe.Next.Prev = pe.Prev
}
}
if mlrmap.keysToEntries != nil {
delete(mlrmap.keysToEntries, pe.Key)
}
mlrmap.FieldCount--
}
// Does not check for duplicate keys
func (mlrmap *Mlrmap) linkAtHead(pe *MlrmapEntry) {
if mlrmap.Head == nil {
pe.Prev = nil
pe.Next = nil
mlrmap.Head = pe
mlrmap.Tail = pe
} else {
pe.Prev = nil
pe.Next = mlrmap.Head
mlrmap.Head.Prev = pe
mlrmap.Head = pe
}
if mlrmap.keysToEntries != nil {
mlrmap.keysToEntries[pe.Key] = pe
}
mlrmap.FieldCount++
}
// Does not check for duplicate keys
func (mlrmap *Mlrmap) linkAtTail(pe *MlrmapEntry) {
if mlrmap.Head == nil {
pe.Prev = nil
pe.Next = nil
mlrmap.Head = pe
mlrmap.Tail = pe
} else {
pe.Prev = mlrmap.Tail
pe.Next = nil
mlrmap.Tail.Next = pe
mlrmap.Tail = pe
}
if mlrmap.keysToEntries != nil {
mlrmap.keysToEntries[pe.Key] = pe
}
mlrmap.FieldCount++
}
// ----------------------------------------------------------------
func (mlrmap *Mlrmap) pop() *MlrmapEntry {
if mlrmap.Head == nil {
return nil
} else {
pe := mlrmap.Head
mlrmap.Unlink(pe)
return pe
}
}
// ----------------------------------------------------------------
// ToPairsArray is used for sorting maps by key/value/etc, e.g. the sortmf DSL function.
func (mlrmap *Mlrmap) ToPairsArray() []MlrmapPair {
pairsArray := make([]MlrmapPair, mlrmap.FieldCount)
i := 0
for pe := mlrmap.Head; pe != nil; pe = pe.Next {
pairsArray[i].Key = pe.Key
pairsArray[i].Value = pe.Value.Copy()
i++
}
return pairsArray
}
// MlrmapFromPairsArray is used for sorting maps by key/value/etc, e.g. the sortmf DSL function.
func MlrmapFromPairsArray(pairsArray []MlrmapPair) *Mlrmap {
mlrmap := NewMlrmap()
for i := range pairsArray {
mlrmap.PutCopy(pairsArray[i].Key, pairsArray[i].Value)
}
return mlrmap
}
// ----------------------------------------------------------------
// GetFirstPair returns the first key-value pair as its own map. If the map is
// empty (i.e. there is no first pair) it returns nil.
func (mlrmap *Mlrmap) GetFirstPair() *Mlrmap {
if mlrmap.Head == nil {
return nil
}
pair := NewMlrmap()
pair.PutCopy(mlrmap.Head.Key, mlrmap.Head.Value)
return pair
}
func (mlrmap *Mlrmap) IsSinglePair() bool {
return mlrmap.FieldCount == 1
}