This repository has been archived by the owner on Dec 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_test.go
1974 lines (1709 loc) · 46.3 KB
/
stack_test.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 stackage
import (
"bytes"
"fmt"
// uncomment for TestStackagePerf runs
//"log"
//"net/http"
//_ "net/http/pprof"
"sort"
"strconv"
"strings"
"testing"
_ "time"
)
// Uncomment this test func (and the http+log imports above)
// to allow continuous pprof access via HTTP. Replace actions
// within the 'for loop' below with whatever expensive calls
// or activities you want to debug.
//
// You can run this test directly via the following command
// (which assumes your cwd is this package):
//
// $ go test -run TestStackagePerf .
//
// While this test is running, in a separate terminal run
// the following command to acquire samples:
//
// $ go tool pprof http://localhost:1234/debug/pprof/profile?seconds=60
//
// Alter this URL as needed (e.g.: use a different sampling
// duration, such as seconds=300).
//
// After N seconds (whatever duration you've used), you will
// be dropped into a pprof shell. I like to enter 'svg' and
// obtain a profileNNN.svg file, but there are other options
// for use.
//
// Once you've been dropped into the pprof shell, this means
// the sample data has been acquired. At this point, you may
// kill the running test in the other terminal via CTRL+C,
// unless you plan on acquiring more samples.
//
// Don't forget to re-comment this function before running
// other tests else you'll hang at some point! Definitely
// don't repackage/redistribute this package while this test
// function is UNcommented.
//func TestStackagePerf(t *testing.T) {
// ch := make(chan bool)
// go func() {
// // edit this listener (e.g.: use TCP/8080) as
// // seen fit.
// log.Println(http.ListenAndServe(":1234", nil))
// }()
//
// for {
// custom := Cond(`outer`, Ne, customStack(And().Push(Cond(`keyword`, Eq, "somevalue"))))
// custom2 := Cond(`inner`, Eq, customStack(And().Push(Cond(`keyword`, Eq, "somevalue"))))
// a1 := And().Push(
// `this4`,
// Not().Mutex().Push(
// Or().Push(
// custom2,
// Cond(`dayofweek`, Ne, "Wednesday"),
// Cond(`ssf`, Ge, "128"),
// Cond(`greeting`, Ne, List().Push(List().Push(List().Push(``)))),
// ),
// ),
// )
// a2 := And().Push(
// `this4`,
// Not().Mutex().Push(
// Or().Push(
// custom2,
// Cond(`dayofweek`, Ne, "Wednesday"),
// Cond(`ssf`, Gt, "128"),
// Cond(`greeting`, Ne, List().Push(List().Push(List().Push(``)))),
// ),
// ),
// )
//
// //thisIsMyNightmare := And().Push(
// _ = And().Push(
// `this1`,
// Or().Mutex().Push(
// custom,
// a1,
// And().Push(
// Or().Push(
// Cond(`keyword2`, Lt, "someothervalue"),
// ),
// ),
// Cond(`keyword`, Gt, Or().Push(`...`)),
// ),
// `this2`,
// )
//
// custom.IsEqual(custom2)
// a1.IsEqual(a2)
//
// //os.Stdout.Write([]byte(thisIsMyNightmare.String()))
// }
// <-ch
//}
/*
This example demonstrates basic support for stack sorting via the
[sort.Stable] method using basic string values.
*/
func ExampleStack_String_withSort() {
var names Stack = List().SetDelimiter(' ')
names.Push(`Frank`, `Anna`, `Xavier`, `Betty`, `aly`, `Jim`, `fargus`)
sort.Stable(names)
fmt.Println(names)
// Output: Anna Betty Frank Jim Xavier aly fargus
}
/*
This example demonstrates the means of converting a custom [Stack]-alias
instance into a native [Stack] that contains the same values. Optionally,
users may shadow the first return value, and use the second (bool) value
to ascertain whether the instance was converted successfully.
*/
func ExampleConvertStack() {
var native Stack = List().Push(`this`, `is`, `a`, `native`, `stack`)
type YourStack Stack
// A custom instance could have been
// assembled in a variety of ways.
//
// For this example, we'll just use a
// basic cast just for brevity.
custom := YourStack(native)
back, ok := ConvertStack(custom)
if !ok {
fmt.Printf("Failed to convert %T", custom)
return
}
slice, found := back.Index(0) // any index would do
if !found {
fmt.Printf("Content not found")
return
}
fmt.Printf("Value: %v", slice)
// Output: Value: this
}
/*
This example demonstrates the means for assigning a custom marshaler
function or method to a [Stack] instance.
*/
func ExampleStack_SetMarshaler() {
var r Stack = List()
// Lets write a marshaler that converts
// string numbers to ints, each of which
// are added to Stack r.
r.SetMarshaler(func(in ...any) (err error) {
if len(in) == 0 {
err = fmt.Errorf("No input content")
return
}
for i := 0; i < len(in); i++ {
if assert, ok := in[i].(string); ok {
var num int
if num, err = strconv.Atoi(assert); err != nil {
break
} else {
r.Push(num)
}
} else {
err = fmt.Errorf("Cannot assert %T as a string", in[i])
break
}
}
return
})
if err := r.Marshal(`1`, `2`, `3`, `4`); err != nil {
fmt.Println(err)
return
}
slice, _ := r.Index(1)
fmt.Printf("Slice is %T", slice)
// Output: Slice is int
}
/*
This example demonstrates the means for assigning a custom unmarshaler
function or method to a [Stack] instance.
*/
func ExampleStack_SetUnmarshaler() {
var r Stack = List().Push(`1`, `2`, `3`, `4`)
// Write an unmarshaler that extracts just the
// values, depositing them within the []any
// output instance.
r.SetUnmarshaler(func(_ ...any) (out []any, err error) {
for i := 0; i < r.Len(); i++ {
slice, _ := r.Index(i)
assert, ok := slice.(string)
// We only want string types
if ok {
out = append(out, assert)
} else {
err = fmt.Errorf("Unsupported slice type: %T", slice)
break
}
}
return
})
out, err := r.Unmarshal()
if err != nil {
fmt.Println(err)
return
}
lout := len(out)
fmt.Printf("Output has %d strings: %t", lout, lout == 4)
// Output: Output has 4 strings: true
}
/*
This example demonstrates a simple "swapping" of indexed values by way
of the [Stack.Swap] method.
*/
func ExampleStack_Swap() {
var names Stack = List().SetDelimiter(' ')
names.Push(`Frank`, `Anna`, `Xavier`, `Betty`, `aly`, `Jim`, `fargus`)
names.Swap(0, 5)
slice, _ := names.Index(0)
fmt.Println(slice)
// Output: Jim
}
func ExampleStack_Free() {
var names Stack = List() // initialize
names.Push(`Frank`, `Anna`, `Xavier`, `Betty`, `aly`, `Jim`, `fargus`)
names.Free()
fmt.Printf("%T is zero: %t", names, names.IsZero())
// Output: stackage.Stack is zero: true
}
/*
This example demonstrates a simple order-based comparison using two
string values by way of the [Stack.Less] method. In this scenario,
a value of false is returned because "Frank" does not alphabetically
precede "Anna".
Note that the semantics of [Stack.Less] apply, in that certain conditions
with regards to the values must be satified, else a custom Less closure
needs to be devised by the end-user. See the [Stack.SetLessFunc] method.
*/
func ExampleStack_Less() {
var names Stack = List().SetDelimiter(' ')
names.Push(`Frank`, `Anna`, `Xavier`, `Betty`, `aly`, `Jim`, `fargus`)
fmt.Println(names.Less(0, 1)) // is Frank before Anna?
// Output: false
}
/*
This example demonstrates custom stack sorting by way of a user-defined
closure set within the stack via the [Stack.SetLessFunc] value, thereby
allowing support with the [sort.Stable] method, et al.
*/
func ExampleStack_SetLessFunc() {
var names Stack = List().SetDelimiter(' ')
names.Push(`Frank`, `Anna`, `Xavier`, `Betty`, `aly`, `Jim`, `fargus`)
// Submit our custom closure
names.SetLessFunc(func(i, j int) bool {
// Note we are just presuming the values are
// strings merely for simplicity. Index and
// type checks should always be done in real
// life scenarios, else you risk panics, etc.
slice1, _ := names.Index(i)
slice2, _ := names.Index(j)
s1 := strings.ToLower(slice1.(string))
s2 := strings.ToLower(slice2.(string))
switch strings.Compare(s1, s2) {
case -1:
return true
}
return false
})
sort.Stable(names)
fmt.Println(names)
// Output: aly Anna Betty fargus Frank Jim Xavier
}
func ExampleComparisonOperator_Context() {
var cop ComparisonOperator = Ge
fmt.Printf("Context: %s", cop.Context())
// Output: Context: comparison
}
func ExampleComparisonOperator_String() {
var cop ComparisonOperator = Ge
fmt.Printf("Operator: %s", cop)
// Output: Operator: >=
}
func ExampleStack_Addr() {
var c Stack = List().Push(`this`, `and`, `that`)
fmt.Printf("Address ID has '0x' prefix: %t", c.Addr()[:2] == `0x`)
// Output: Address ID has '0x' prefix: true
}
func ExampleStack_Reverse() {
var c Stack = List().Push(0, 1, 2, 3, 4)
fmt.Printf("%s", c.Reverse())
// Output: 4 3 2 1 0
}
func ExampleStack_Auxiliary() {
// make a stack ... any type would do
l := List().Push(`this`, `that`, `other`)
// one can put anything they wish into this map,
// so we'll do a bytes.Buffer since it is simple
// and commonplace.
var buf *bytes.Buffer = &bytes.Buffer{}
_, _ = buf.WriteString(`some .... data .....`)
// Create our map (one could also use make
// and populate it piecemeal as opposed to
// in-line, as we do below).
l.SetAuxiliary(map[string]any{
`buffer`: buf,
})
// Call our map and call its 'Get' method in one-shot
if val, ok := l.Auxiliary().Get(`buffer`); ok {
fmt.Printf("%s", val)
}
// Output: some .... data .....
}
func ExampleAuxiliary_Get() {
var aux Auxiliary = make(Auxiliary, 0)
aux.Set(`value`, 18)
val, ok := aux.Get(`value`)
if ok {
fmt.Printf("%d", val)
}
// Output: 18
}
func ExampleAuxiliary_Set() {
var aux Auxiliary = make(Auxiliary, 0)
aux.Set(`value`, 18)
aux.Set(`color`, `red`)
aux.Set(`max`, 200)
fmt.Printf("Len: %d", aux.Len())
// Output: Len: 3
}
func ExampleAuxiliary_Unset() {
var aux Auxiliary = make(Auxiliary, 0)
aux.Set(`value`, 18)
aux.Set(`color`, `red`)
aux.Set(`max`, 200)
aux.Unset(`max`)
fmt.Printf("Len: %d", aux.Len())
// Output: Len: 2
}
func ExampleAuxiliary_Len() {
aux := Auxiliary{
`value`: 18,
}
fmt.Printf("Len: %d", aux.Len())
// Output: Len: 1
}
func ExampleSetDefaultStackLogLevel() {
SetDefaultStackLogLevel(
LogLevel1 + // 1
LogLevel4 + // 8
UserLogLevel2 + // 128
UserLogLevel5, // 1024
)
custom := DefaultStackLogLevel()
// turn loglevel to none
SetDefaultStackLogLevel(NoLogLevels)
off := DefaultStackLogLevel()
fmt.Printf("%d (custom), %d (off)", custom, off)
// Output: 1161 (custom), 0 (off)
}
func ExampleDefaultStackLogLevel() {
fmt.Printf("%d", DefaultStackLogLevel())
// Output: 0
}
var testParens []string = []string{`(`, `)`}
type customStack Stack // simulates a user-defined type that aliases a Stack
func (r customStack) String() string {
return Stack(r).String()
}
type customStruct struct {
Type string
Value any
}
func (r customStruct) String() string {
return `struct_value`
}
func ExampleStack_SetAuxiliary() {
// Always alloc stack somehow, in this
// case just use List because its simple
// and (unlike Basic) it is feature-rich.
var list Stack = List()
// alloc map
aux := make(Auxiliary, 0)
// populate map
aux.Set(`somethingWeNeed`, struct {
Type string
Value []string
}{
Type: `L`,
Value: []string{
`abc`,
`def`,
},
})
// assign map to stack rcvr
list.SetAuxiliary(aux)
// verify presence
call := list.Auxiliary()
fmt.Printf("%T found, length:%d", call, call.Len())
// Output: stackage.Auxiliary found, length:1
}
func ExampleStack_Kind() {
var myStack Stack = And()
fmt.Printf("Kind: '%s'", myStack.Kind())
// Output: Kind: 'AND'
}
/*
This example demonstrates the call and (failed) set of an
uninitialized Auxiliary instance. While no panic ensues,
the map instance is not writable.
The user must instead follow the procedures in the WithInit,
UserInit or ByTypeCast examples.
*/
func ExampleStack_Auxiliary_noInit() {
var list Stack = List()
aux := list.Auxiliary()
fmt.Printf("%T found, length:%d",
aux, aux.Set(`testing`, `123`).Len())
// Output: stackage.Auxiliary found, length:0
}
/*
This example continues the concepts within the NoInit example,
except in this case proper initialization occurs and a desirable
outcome is achieved.
*/
func ExampleStack_Auxiliary_withInit() {
var list Stack = List().SetAuxiliary() // no args triggers auto-init
aux := list.Auxiliary()
fmt.Printf("%T found, length was:%d, is now:%d",
aux,
aux.Len(), // check initial (pre-set) length
aux.Set(`testing`, `123`).Len()) // fluent Set/Len in one shot
// Output: stackage.Auxiliary found, length was:0, is now:1
}
/*
This example demonstrates a scenario similar to that of the WithInit
example, except in this case the map instance is entirely created and
populated by the user in a traditional fashion.
*/
func ExampleStack_Auxiliary_userInit() {
var list Stack = List()
aux := make(Auxiliary, 0)
// user opts to just use standard map
// key/val set procedure, and avoids
// use of the convenience methods.
// This is totally fine.
aux[`value1`] = []int{1, 2, 3, 4, 5}
aux[`value2`] = [2]any{float64(7.014), rune('#')}
list.SetAuxiliary(aux)
fmt.Printf("%T length:%d", aux, len(aux))
// Output: stackage.Auxiliary length:2
}
/*
This example demonstrates building of the Auxiliary map in its generic
form (map[string]any) before being type cast to Auxiliary.
*/
func ExampleStack_Auxiliary_byTypeCast() {
var list Stack = List()
proto := make(map[string]any, 0)
proto[`value1`] = []int{1, 2, 3, 4, 5}
proto[`value2`] = [2]any{float64(7.014), rune('#')}
list.SetAuxiliary(Auxiliary(proto)) // cast proto and assign to stack
aux := list.Auxiliary() // call map to variable
fmt.Printf("%T length:%d", aux, aux.Len())
// Output: stackage.Auxiliary length:2
}
func TestStack_SetAuxiliary(t *testing.T) {
var list Stack = List()
// alloc map
aux := make(Auxiliary, 0)
// populate map
aux.Set(`somethingWeNeed`, struct {
Type string
Value []string
}{
Type: `L`,
Value: []string{
`abc`,
`def`,
},
})
// assign map to stack rcvr
list.SetAuxiliary(aux)
// test that it was assigned properly
var call Auxiliary = list.Auxiliary()
if call == nil {
t.Errorf("%s failed: %T nil", t.Name(), call)
return
}
// make sure the contents are present
want := 1
if length := call.Len(); length != want {
t.Errorf("%s failed: unexpected length; want %d, got %d",
t.Name(), want, length)
return
}
}
func TestStack_noInit(t *testing.T) {
var x Stack
x.Push(`well?`) // first off, this should not panic
// next, make sure it really
// did not work ...
if length := x.Len(); length != 0 {
t.Errorf("%s failed [noInit]: want '%d' elements, got '%d'", t.Name(), 0, length)
return
}
// lastly, we should definitely see an indication
// of this issue during validity checks ...
if err := x.Valid(); err == nil {
t.Errorf("%s failed [noInit]: want 'error', got '%T'", t.Name(), nil)
return
}
}
func TestStack_And001(t *testing.T) {
got := And().Paren().Fold().Push(
`testing1`,
`testing2`,
`testing3`,
)
want := `( testing1 and testing2 and testing3 )`
if got.String() != want {
t.Errorf("%s failed: want '%s', got '%s'", t.Name(), want, got)
return
}
_, _ = got.Traverse(0, 2, 6, 19)
}
func TestStack_Insert(t *testing.T) {
got := And().Paren().Fold().Push(
`testing1`,
`testing2`,
`testing3`,
)
got.Insert(`testing0`, 0)
want := `( testing0 and testing1 and testing2 and testing3 )`
if got.String() != want {
t.Errorf("%s.1 failed: want '%s', got '%s'", t.Name(), want, got)
return
}
got.Insert(`testing2.5`, 3)
want = `( testing0 and testing1 and testing2 and testing2.5 and testing3 )`
if got.String() != want {
t.Errorf("%s.2 failed: want '%s', got '%s'", t.Name(), want, got)
return
}
got.Insert(`testing4`, 15)
want = `( testing0 and testing1 and testing2 and testing2.5 and testing3 and testing4 )`
if got.String() != want {
t.Errorf("%s.3 failed: want '%s', got '%s'", t.Name(), want, got)
return
}
}
func TestStack_Replace(t *testing.T) {
s := List().SetDelimiter(rune(44)).NoPadding(true).Push(
`testing1`,
`testing2`,
`testing3`,
)
want := `testing0,testing2,testing3`
s.Replace(`testing0`, 0)
got := s.String()
if want != got {
t.Errorf("%s.1 failed: want '%s', got '%s'", t.Name(), want, got)
return
}
if ok := s.Replace(`testingX`, 6); ok {
t.Errorf("%s.2 failed: want '%t', got '%t'", t.Name(), false, ok)
return
}
}
func TestStack_IsParen(t *testing.T) {
stk := And().Paren().Fold().Push(
`testing1`,
`testing2`,
`testing3`,
)
if got := stk.IsParen(); !got {
t.Errorf("%s failed: want 'true', got '%t'", t.Name(), got)
return
}
}
func TestStack_Transfer(t *testing.T) {
stk := And().Push(
`testing1`,
`testing2`,
`testing3`,
)
or := Or()
if ok := stk.Transfer(or); or.Len() != 3 || !ok {
t.Errorf("%s failed [post-transfer len comparisons]: want len:%d, got len:%d", t.Name(), stk.Len(), or.Len())
return
}
stk.Reset() // reset source, removing all slices
if or.Len() != 3 && stk.Len() != 0 {
t.Errorf("%s failed [post-transfer src reset]: want slen:%d; dlen:%d, got slen:%d; dlen:%d",
t.Name(), 0, 3, stk.Len(), or.Len())
return
}
}
func TestStack_Traverse(t *testing.T) {
stk := Basic().Push(
1,
Basic().Push(2),
Cond(`keyword`, Eq, Basic().Push(3)),
)
slice, _ := stk.Traverse(0)
if _, ok := slice.(int); !ok {
t.Errorf("%s failed: unexpected type %T", t.Name(), slice)
return
}
slice, _ = stk.Traverse(1)
if _, ok := slice.(Stack); !ok {
t.Errorf("%s failed: unexpected type %T at depth 2", t.Name(), slice)
return
}
slice, _ = stk.Traverse(1, 0)
if _, ok := slice.(int); !ok {
t.Errorf("%s failed: unexpected type %T at depth 2", t.Name(), slice)
return
}
slice, _ = stk.Traverse(2, 0)
if _, ok := slice.(int); !ok {
t.Errorf("%s failed: unexpected type %T at depth 3", t.Name(), slice)
return
}
}
func TestStack_IsPadded(t *testing.T) {
stk := And().Paren().Fold().Push(
`testing1`,
`testing2`,
`testing3`,
)
if got := stk.IsPadded(); !got {
t.Errorf("%s failed: want 'true', got '%t'", t.Name(), got)
return
}
}
func TestStackAnd_001(t *testing.T) {
A := And().Paren().Push(
`top_element_number_0`,
Or().Paren().Push(
`sub_element_number_0`,
`sub_element_number_1`,
),
)
want := `( top_element_number_0 AND ( sub_element_number_0 OR sub_element_number_1 ) )`
if got := A; got.String() != want {
t.Errorf("%s failed: want '%s', got '%s'", t.Name(), want, got)
return
}
}
func TestStack_IsEqual(t *testing.T) {
channel := make(chan error, 2)
var str1 *string = new(string)
*str1 = `this is crazy`
var str2 *string = new(string)
*str2 = `this is crazy`
var iface1 any = struct{}{}
var iface2 any = struct{}{}
A := And().Paren().Push(
Cond(`Test`, Eq, List().Push(
`sub_nested_number_0`,
`sub_nested_number_1`,
)),
[]string{`1`, `2`, `3`, `4`},
iface1,
map[int]any{
0: map[any]any{
uint8(0): `hehe`,
uint16(1): `omg`,
true: false,
`runes`: []rune{'H', 'E', 'L', 'P', ' ', 'M', 'E'},
},
1: nil,
2: []uint{1, 2, 3, 4},
},
Or().Paren().Push(
And().Push(`deep_string`),
`sub_element_number_0`,
`sub_element_number_1`,
),
//TestStack_IsEqual,
&str1, // **string
channel,
struct{}{},
&struct{}{},
rune(76),
nil,
)
B := And().Paren().Push(
Cond(`Test`, Eq, List().Push(
`sub_nested_number_0`,
`sub_nested_number_1`,
)),
[4]string{`1`, `2`, `3`, `4`},
iface2,
map[int]any{
0: map[any]any{
uint8(0): `hehe`,
uint16(1): `omg`,
true: false,
`runes`: []rune{'H', 'E', 'L', 'P', ' ', 'M', 'E'},
},
1: nil,
2: []uint{1, 2, 3, 4},
},
Or().Paren().Push(
And().Push(`deep_string`),
`sub_element_number_0`,
`sub_element_number_1`,
),
//TestStack_Unmarshal_default,
&str2, // **string
channel,
struct{}{},
&struct{}{},
rune(76),
nil,
)
if err := A.IsEqual(B); err != nil {
t.Errorf("%s failed: %v", t.Name(), err)
return
}
}
func TestStack_Unmarshal_default(t *testing.T) {
// Make a stack with senseless garbage
A := And().Paren().Push(
// Condition with Stack expr
Cond(`Test`, Eq, List().Push(
`sub_nested_number_0`,
`sub_nested_number_1`,
)),
// just a string
`top_element_number_0`,
// Stack
Or().Paren().Push(
And().Push(`deep_string`),
`sub_element_number_0`,
`sub_element_number_1`,
),
// A random rune
rune(76),
// A byte -- 0x2B (ASCII #43, "+")
byte(43),
)
slices, err := A.Unmarshal()
if err != nil {
t.Errorf("%s failed: %v", t.Name(), err)
return
}
want := 6
if got := len(slices); got != want {
t.Errorf("%s failed: want %d, got %d", t.Name(), want, got)
return
}
var n Stack
if err = n.Marshal(slices); err != nil {
t.Errorf("%s failed: %v", t.Name(), err)
return
}
//printf("Top-Stack: %s(%d)\n", n.Kind(), n.Len())
//n.debugStack(0)
//printf("End-of-Stack\n")
}
/*
func (r Stack) debugStack(lvl int) {
for i := 0; i < r.Len(); i++ {
slice, _ := r.Index(i)
switch tv := slice.(type) {
case Condition:
expr := tv.Expression()
if tv.IsNesting() {
if sub, ok := stackTypeAliasConverter(expr); ok {
printf("%d:%d - Condition-Nested-Stack::[KW]%s [OP]%s [%s(%d)]\n",
i, lvl, tv.Keyword(), tv.Operator(), sub.Kind(), sub.Len())
sub.debugStack(lvl+1)
printf("%d:%d - End-of-Condition-Nested-Stack\n", i, lvl)
}
} else {
printf("%d:%d - Condition::[%s]\n", lvl, i, tv)
if isKnownPrimitive(tv) {
printf("%d:%d - Primitive-Condition-Expr: %s\n",
i, lvl, primitiveStringer(tv))
} else if meth := getStringer(expr); meth != nil {
printf("%d:%d - Stringer-Condition-Expr: %s\n", i, lvl, meth())
}
}
case Stack:
printf("%d:%d - Nested-Stack(%s)[%d]::\n",
i, lvl, tv.Kind(), tv.Len())
tv.debugStack(lvl+1)
printf("%d:%d - End-of-Nested-Stack\n", i, lvl)
default:
if isKnownPrimitive(tv) {
printf("-:%d - Primitive-Stack-Value: (%T) %s\n",
i, tv, primitiveStringer(tv))
} else if meth := getStringer(tv); meth != nil {
printf("-:%d - Stringer-Stack-Value: %s\n", i, meth())
} else {
printf("-:%d - NoStringer-Stack-Value: %T\n", i, tv)
}
}
}
}
*/
func TestStack_IsNesting(t *testing.T) {
A := And().Paren().Push(
`top_element_number_0`,
Or().Paren().Push(
`sub_element_number_0`,
`sub_element_number_1`,
),
)
want := true
got := A.IsNesting()
if want != got {
t.Errorf("%s failed [isNesting]: want '%t', got '%t'", t.Name(), want, got)
return
}
}
func TestAnd_002(t *testing.T) {
// make each OR condition look like "<...>" (including quotes)
O := Or().Paren().Encap(`"`, []string{`<`, `>`}).Push(
`sub_element_number_0`,
`sub_element_number_1`,
)
A := And().Paren().Push(
`top_element_number_0`,
O,
)
want := `( top_element_number_0 AND ( "<sub_element_number_0>" OR "<sub_element_number_1>" ) )`
if got := A; got.String() != want {
t.Errorf("%s failed: want '%s', got '%s'", t.Name(), want, got)
return
}
if !O.IsEncap() {
t.Errorf("%s failed [IsEncap]: want '%t', got '%t'", t.Name(), true, false)
return
}
}
func TestAnd_003(t *testing.T) {
A := And().Symbol('&').Paren().LeadOnce().Encap(testParens).NoPadding().Push(
`top_element_number_0`,
Or().Symbol('|').Paren().LeadOnce().Encap(testParens).NoPadding().Push(
`sub_element_number_0`,
`sub_element_number_1`,
),
)
want := `(&(top_element_number_0)(|(sub_element_number_0)(sub_element_number_1)))`
if got := A; got.String() != want {
t.Errorf("%s failed: want '%s', got '%s'", t.Name(), want, got)
return
}
}
func TestAnd_004(t *testing.T) {
// make a helper function that incorporates
// the same options into each of the three
// stacks we're going to make. it just looks
// cleaner.
enabler := func(r Stack) Stack {
return r.Paren().LeadOnce().Encap(testParens).NoPadding()
}
A := enabler(And().Symbol('&')).Push(
`top_element_number_0`,
enabler(Or().Symbol('|')).Push(
`sub_element_number_0`,
`sub_element_number_1`,
),