-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstack.go
2095 lines (1688 loc) · 55.6 KB
/
stack.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 boardgame
import (
"encoding/json"
"math"
"sort"
"strconv"
"github.com/jkomoros/boardgame/errors"
)
const emptyIndexSentinel = -1
//ImmutableStack is a flavor of Stack, but minus any methods that can be used
//to mutate anything. See the documentation for Stack for more about the
//hierarchy of Stack-based types. ImmutableStack is the lowest-common-
//denominator that all Stack types implement.
type ImmutableStack interface {
//Deck returns the Deck associated with this stack.
Deck() *Deck
//Len returns the number of slots in the Stack. For a normal Stack this is
//the number of items in the stack. For SizedStacks, this is the number of
//slots--even if some are unfilled.
Len() int
//NumComponents returns the number of components that are in this stack.
//For default Stacks this is the same as Len(); for SizedStacks, this is
//the number of non-nil slots.
NumComponents() int
//SlotsRemaining returns how many slots there are left in this stack to
//add items. For default stacks this will be the number of slots until
//maxSize is reached (or MaxInt64 if there is no maxSize). For SizedStacks
//this will be the number of empty slots.
SlotsRemaining() int
//MaxSize returns the Maxium Size, if set, for default stacks. For sized
//stacks it will return the number of total current slots (filled and
//unfilled), which is equivalent to Len().
MaxSize() int
//ImmutableComponentAt retrieves the component at the given index in the
//stack. See also Stack.ComponentAt.
ImmutableComponentAt(index int) ImmutableComponentInstance
//ImmutableComponents returns all of the components. Equivalent to calling
//ImmutableComponentAt from 0 to Len(). See also Stack.Components().
ImmutableComponents() []ImmutableComponentInstance
//ImmutableFirst returns a reference to the first non-nil component from
//the left, or nil if empty. For default stacks, this is simply a
//convenience wrapper around stack.ImmutableComponentAt(0). SizedStacks
//however will use the result of FirstComponentIndex().
ImmutableFirst() ImmutableComponentInstance
//ImmutableLast returns a reference to the first non-nil component from
//the right, or nil if empty. For default stacks, this is simply a
//convenience wrapper around stack.ComponentAt(stack.Len() - 1).
//SizedStacks however will use the result of LastComponentIndex().
ImmutableLast() ImmutableComponentInstance
//IDs returns a slice of strings representing the IDs of each component at
//each index. Under normal circumstances this will be the results of
//calling c.ID() on each component in order. This information will be
//elided or modified if the state has been sanitized. See documentation
//for Policy for more on when and how these might be changed.
IDs() []string
//LastSeen represents an unordered list of the last version number at
//which the given ID was seen in this stack. A component is "seen" at
//three moments: 1) when it is moved to this stack, 2) immediately before
//its ID is scrambled, and 3) immediately after its ID is scrambled.
//LastSeen thus represents the last time that we knew for sure it was in
//this stack --although it may have been in this stack after that, and may
//no longer be in this stack. This information may be elided if the stack
//has been sanitized. See the documentation for Policy for more about when
//this might be elided.
IDsLastSeen() map[string]int
//ShuffleCount is the number of times during this game that Shuffle (or
//PublicShuffle) have been called on this stack. Not visible in some
//sanitization policies, see Policy for more.
ShuffleCount() int
//ImmutableSizedStack will return a version of this stack that implements
//the ImmutableSizedStack interface, if that's possible, or nil otherwise.
ImmutableSizedStack() ImmutableSizedStack
//MergedStack will return a version of this stack that implements the
//MergedStack interface, if that's possible, or nil otherwise.
MergedStack() MergedStack
//ImmutableBoard will return the Board that this Stack is part of, or nil
//if it is not part of a board.
ImmutableBoard() ImmutableBoard
//If Board returns a non-nil Board, this will return the index within the
//Board that this stack is.
BoardIndex() int
//Returns the state that this Stack is currently part of. Mainly a
//convenience method when you have a Stack but don't know its underlying
//type.
state() *state
//setState sets the state ptr that will be returned by state().
setState(state *state)
//All stacks have these, even though they aren't exported, because within
//this library we iterate trhough a lot of Stacks via readers and it's
//convenient to be able to treat them all the same.
firstComponentIndex() int
lastComponentIndex() int
}
//ImmutableSizedStack is a specific type of Stack that has a specific number
//of slots, any of which may be nil. Although very few methods are added, the
//basic behavior of the Stack methods is quite different for these kinds of
//stacks. See also SizedStack, which adds mutator methods to this definition.
//See the documentation for Stack for more about the hierarchy of Stack
//objects.
type ImmutableSizedStack interface {
//An ImmutableSizedStack can be used everywhere a normal ImmutableStack
//can. Note the behavior of an ImmutableSizedStack's base ImmutableStack
//methods will often be different than a default stack.
ImmutableStack
//FirstComponentIndex returns the index of the first non-nil component
//from the left.
FirstComponentIndex() int
//LastComponentIndex returns the index of the first non-nil component from
//the right.
LastComponentIndex() int
}
//MergedStack is a special variant of ImmutableStack that is actually formed
//from multiple underlying stacks combined. MergedStacks can never be mutated
//directly; instead, mutate the underlying stacks. See the documentation for
//Stack for more about the hierarchy of Stack types.
type MergedStack interface {
//A MergedStack can be used anywhere an ImmutableStack can be.
ImmutableStack
//Valid will return a non-nil error if the stack isn't valid currently
//for example if the two stacks being merged are different sizes for an
//overlapped stack. Valid is checked just before state is saved. If any
//stack returns any non-nil for this then the state will not be saved.
Valid() error
//ImmutableStacks returns the stacks that this MergedStack is based on.1
ImmutableStacks() []ImmutableStack
//Overlapped will return true if the MergedStack is an overlapped stack
//(in contrast to a concatenated stack).
Overlapped() bool
}
/*
Stack is one of the fundamental types in the engine. Stacks model things like
a stack of cards, a collection of resource tokens, etc. Each component in each
deck must reside in precisely one stack in each state, the so called
"component invariant". This captures the notion that each ComponentInstance is
a physical object that resides in one spot at any given time. See also the
documentation for Deck.
Stacks fundamentally keep track of a list of ComponentInstances in specific
slots within the stack, and can return those components via ComponentAt().
ComponentInstances can be moved into a Stack via one of their Move* methods;
those methods will fail if the ComponentInstance cannot be moved to that slot
for any reason. The only exception is Stack.MoveAllTo(), which operates on
Stacks, not ComponentInstances.
Stacks are known as an interface type whose initial value contains important
information about their type (e.g. which Deck they're affiliated with),
meaning that your GameDelegate.GameStateConstructor() and others are supposed
to initalize them to a non-nil value before returning the struct they're in.
You generally retrieve them from Deck.NewStack() or Deck.NewSizedStack(). In
practice you often use tags on your struct to instruct the StructInflaters on
how to initialize them for you. See StructInflater for more.
There are a hierarchy of different types for Stacks, with diferent behavior
for these methods.
* ImmutableStack
* Stack
* SizedStack
* ImmutableSizedStack
* MergedStack
The default Stack is known as a "growable" stack. The number of slots it has
is precisely the number of ComponentInstaces it contains, and when a new
ComponentInstance is moved in, a new slot is simply spliced into the right
place, growing the length of the stack. (That is, unless the stack is already
at MaxSize(), in which case the move will fail.) Growable stacks can never
have an empty slot, meaning that ComponentAt() (as long as the index is
between 0 and stack.Len()) will always return a non-nil ComponentInstance.
Stacks can have an optional MaxSize, which sets the maximum limit for the size
of the stack. That can be set via Stack.SetSize() and related methods.
Stack has a sub-class with slightly different behavior, called the SizedStack.
The SizedStack implements the same methods that a normal Stack does, but with
a few extra methods and with different behavior for some of the core methods.
A SizedStack has a fixed, defined number of slots. Those slots may be empty.
Moving a ComponentInstance in to an occupied slot will fail, unlike in a
growable stack where a new slot will be created automatically. SizedStacks add
methods for fetching the first index from the left where a ComponentInstance
resides, and the first index from the right where one resides. SizedStacks can
have their number of slots modified via SetSize() and friends. Unlike a normal
growable Stack, SizedStacks must always have a size set.
The core engine primarily reasons about Stack, not the sub-types.
PropertyReadSetConfigurers, for example, will return the Stack for a given
stack object, not the SizedStack. The way you access the extra methods is via
the SizedStack() getter on the default Stack() interface. If the underlying
Stack is a SizedStack, that method will return a non-nil object that
implements the SizedStack interface. In general you rarely need to do this, as
the default Stack methods are almost always sufficient, and this check for
non-nil is mainly a way to determine if the Stack you have will operate like a
growable or sized stack. See SizedStack for more.
Stack contains mutator methods, but in some cases, like in an
ImmutableSubState, the stack shouldn't be modified. That's why the non-
mutating methods are encapsulated in the ImmutableStack interface, which Stack
embeds. There's also an ImmutableSizedStack interface defined, so you can test
if an ImmutableStack will operate like a growable or sized Stack.
There is one extra type of Stack: the MergedStack. These specisl stacks are
actually combinations of underlying normal stacks, with their output merged
together. Because these merged stacks are just wrappers around other stacks,
they don't have any mutators, so they extend the ImmutableStack interface, and
don't implement the Stack interface. ImmutableStack is thus the lowest common
denominator: the interface that all Stack objects implement. See MergedStack
for more.
*/
type Stack interface {
//A Stack can be used anywhere an ImmutableStack can be.
ImmutableStack
//ComponentAt fetches the ComponentInstance that exists at the given
//index. For default stacks, this will never be nil as long as the index
//is between 0 and Stack.Len(). For SizedStacks, however, this might be
//nil if the given slot is empty. See also ImmutableComponentAt, which has
//the same behavior but returns an ImmutableComponentInstance.
ComponentAt(componentIndex int) ComponentInstance
//Components returns all of the ComponentInstances. Equivalent to calling
//ComponentAt from 0 to Len(). The index of each ComponentInstance will
//correspond to the index you could fetch that item at via
//Stack.ComponentAt. SizedStacks will return a slice that may have nils if
//that slot is empty. See also Stack.Components().
Components() []ComponentInstance
//First returns a reference to the first non-nil component from the left,
//or nil if empty. For default stacks, ths is simply a convenience for
//ComponentAt(0). For SizedStacks, this returns the component at
//SizedStack.FirstComponentIndex. See also ImmutableFirst.
First() ComponentInstance
//Last() returns a reference to the first non-nil component from the
//right, or nil if empty. For defaults stacks, this is simply a
//convenience for ComponentAt(stack.Len() - 1). For SizedStacks this
//returns the component at LastComponentIndex(). See also ImmutableLast.
Last() ComponentInstance
//MoveAllTo is a convenience method that moves all of the components in
//this stack to the other stack, by repeatedly calling
//stack.First().MoveToNextSlot(other). All other Move* methods can be
//found on ComponentInstance. This will fail if the SlotsRemaining in
//other Stack are less than the NumComponents of this stack. In pracitce
//this is rarely moved, because it chunks all of the component moves up
//into one notional Move, meaning that animations will show all of the
//components moving at once. Instead, often moves.MoveAllComponents is
//used to chunk up the move into a series of distinct Moves.
MoveAllTo(other Stack) error
//Shuffle shuffles the order of the stack, so that it has the same items,
//but in a different order. In a SizedStack, the empty slots will move
//around as part of a shuffle. Shuffling will scramble all of the ids in
//the stack, such that the Ids of all items in the stack change. See the
//documenation for Policy for more on Id scrambling. Shuffle uses
//state.Rand() as a source of randomness, allowing it to be deterministic
//if other things also use state.Rand().
Shuffle() error
//PublicShuffle is the same as Shuffle, but the Ids are not scrambled
//after the shuffle. PublicShuffle makes sense in cases where only a small
//number of cards are shuffled and a preternaturally savvy observer should
//be able to keep track of them. The normal Shuffle() is almost always
//what you want. PublicShuffle uses state.Rand() as a source of
//randomness, allowing it to be deterministic if other things also use
//state.Rand().
PublicShuffle() error
//SwapComponents swaps the position of two components within this stack
//without changing the size of the stack (in SizedStacks, it is legal to
//swap empty slots). i,j must be between [0, stack.Len()). This is like a
//ComponentInstance.MoveTo, except within the same stack.
SwapComponents(i, j int) error
//SortComponents sorts the stack's components in the order implied by less
//by repeatedly calling SwapComponents. Errors if any SwapComponents
//errors. If error is non-nil, the stack may be left in an arbitrary order.
SortComponents(less func(i, j ImmutableComponentInstance) bool) error
//Resizable returns true if calls to any of the methods that change the
//Size of the stack are legal to call in general. Currently only stacks
//within a Board return Resizable false. If this returns false, any of
//those size mutating methods will fail with an error.
Resizable() bool
//ContractSize changes the size of the stack. For default stacks it
//contracts the MaxSize, if non-zero. For SizedStack it will reduce the
//size by removing the given number of slots, starting from the right.
//This method will fail if there are more components in the stack
//currently than would fit in newSize.
ContractSize(newSize int) error
//ExpandSize changes the size of the stack. For default stacks it
//increases MaxSize (unless it is zero). For SizedStack it does it by
//adding the given number of newSlots to the end.
ExpandSize(newSlots int) error
//SetSize is a convenience method that will call ContractSize or
//ExpandSize depending on the current Len() and the target len. Calling
//SetSize on a stack that is already that size is a no-op. For default
//stacks, this is the only sway to switch from a zero MaxSize (no limit)
//to a non-zero MaxSize().
SetSize(newSize int) error
//SizeToFit is a simple convenience wrapper around ContractSize. It
//automatically sizes the stack down so that there are no empty slots.
SizeToFit() error
//Board will return a mutable reference to the Board we're part of,
//if we're part of a board.
Board() Board
//SizedStack will return a version of this stack that implements
//the MutableSizedStack interface, if that's possible, or nil otherwise.
SizedStack() SizedStack
moveComponent(componentIndex int, destination Stack, slotIndex int) error
secretMoveComponent(componentIndex int, destination Stack, slotIndex int) error
moveComponentToEnd(componentIndex int) error
moveComponentToStart(componentIndex int) error
//removeComponentAt returns the component at componentIndex, and removes
//it from the stack. For GrowableStacks, this will splice `out the
//component. For SizedStacks it will simply vacate that slot. This should
//only be called by MoveComponent. Performs minimal error checking because
//it is only used inside of MoveComponent.
removeComponentAt(componentIndex int) ImmutableComponentInstance
//insertComponentAt inserts the given component at the given slot index,
//such that calling ComponentAt with slotIndex would return that
//component. For GrowableStacks, this splices in the component. For
//SizedStacks, this just inserts the component in the slot. This should
//only be called by MoveComponent. Performs minimal error checking because
//it is only used inside of Movecomponent and game.SetUp.
insertComponentAt(slotIndex int, component ImmutableComponentInstance)
//insertNext is a convenience wrapper around insertComponentAt.
insertNext(c ImmutableComponentInstance)
//Whether or not the stack is set up to be modified right now.
modificationsAllowed() error
//applySanitizationPolicy applies the given policy to ourselves. This
//should only be called by methods in sanitization.go.
applySanitizationPolicy(policy Policy)
//idSeen is called when an Id is seen (that is, either when added to the
//item or right before being scrambled)
idSeen(id string)
//scrambleIds copies all component ids to persistentPossibleIds, then
//increments all components secretMoveCount.
scrambleIds()
//legalSlot will return true if the provided index points to a valid slot
//to insert a component at. For growableStacks, this is simply a check to
//ensure it's in the range [0, stack.Len()]. For SizedStacks, it is a
//check that the slot is valid and is currently empty. Does not expand the
//special index constants.
legalSlot(index int) bool
//used to import the state from another stack into this one. This allows
//stacks to be phsyically the same within a state as what was returned
//from the constructor.
importFrom(other Stack) error
//All stacks have these, even though they aren't exported, because within
//this library we iterate trhough a lot of Stacks via readers and it's
//convenient to be able to treat them all the same.
firstSlot() int
nextSlot() int
lastSlot() int
}
//SizedStack is Stack, but with SizedStack related methods. See the
//documentation for Stack for more about how SizedStacks are different than
//Stacks. Note that although a SizedStack has only a few more methods than a
//normal Stack, its Stack methods will also have different methods than a
//"normal" stack.
type SizedStack interface {
//SizedStack can be used anywhere a Stack can be.
Stack
//Recreate the methods in ImmutableSizedStack.
//FirstComponentIndex returns the index of the first non-nil component
//from the left.
FirstComponentIndex() int
//LastComponentIndex returns the index of the first non-nil component from
//the right.
LastComponentIndex() int
//FirstSlot returns the index of the first empty slot from the left.
FirstSlot() int
//NextSlot returns the index of the next valid slot in the slot, which is
//equivalent to FirstSlot() for sized stacks.
NextSlot() int
//LastSlot returns the index of the first empty component slot from the
//right.
LastSlot() int
}
//growableStack is a Stack that has a variable number of slots, none of which
//may be empty. It can optionally have a max size. Create a new one with
//deck.NewGrowableStack.
type growableStack struct {
//Deck is the deck that we're a part of. This will be nil if we aren't
//inflated.
deckPtr *Deck
//We need to maintain the name of deck because sometimes we aren't
//inflated yet (like after being deserialized from disk)
deckName string
//The indexes from the given deck that this stack contains, in order.
indexes []int
//If overrideIds is nil, we'll just fetch them from all of component's Id.
overrideIds []string
idsLastSeen map[string]int
shuffleCount int
//size, if set, says the maxmimum number of items allowed in the Stack. 0
//means that the Stack may grow without bound.
maxSize int
//Each stack is associated with precisely one state. This is consulted to
//verify that components being transfered between stacks are part of a
//single state. Set in empty{Game,Player}State.
statePtr *state
board Board
boardIndex int
}
//sizedStack is a Stack that has a fixed number of slots, any of which may be
//empty. Create a new one with deck.NewSizedStack.
type sizedStack struct {
//Deck is the deck we're a part of. This will be nil if we aren't inflated.
deckPtr *Deck
//We need to maintain the name of deck because sometimes we aren't
//inflated yet (like after being deserialized from disk)
deckName string
//Indexes will always have a len of size. Slots that are "empty" will have
//index of -1.
indexes []int
//If overrideIds is nil, we'll just fetch them from all of component's Id.
overrideIds []string
idsLastSeen map[string]int
shuffleCount int
//Size is the number of slots.
size int
//Each stack is associated with precisely one state. This is consulted to
//verify that components being transfered between stacks are part of a
//single state. Set in empty{Game,Player}State.
statePtr *state
}
//mergedStack is a derived stack that is made of two stacks, either in
//concatenate mode (default) or overlap mode.
type mergedStack struct {
stacks []ImmutableStack
overlap bool
}
//stackJSONObj is an internal struct that we populate and use to implement
//MarshalJSON so stacks can be saved in output JSON with minimum fuss.
type stackJSONObj struct {
Deck string
Indexes []int
IDs []string
IDsLastSeen map[string]int
ShuffleCount int
Size int `json:",omitempty"`
MaxSize int `json:",omitempty"`
}
//NewConcatenatedStack returns a new merged stack where all of the components
//in the first stack will show up, then all of the components in the second
//stack, and on down the list of stacks. In practice this is useful as a
//computed property when you have a logical stack made up of components that
//are santiized followed by components that are not sanitized, like in a
//blackjack hand. All stacks must be from the same deck, or Valid() will
//error.
func NewConcatenatedStack(stack ...ImmutableStack) MergedStack {
return &mergedStack{
stacks: stack,
overlap: false,
}
}
//NewOverlappedStack returns a new merged stack where any gaps in the first
//stack will be filled with whatever is in the same position in the second
//stack, and so on down the line. In practice this is useful as a computed
//property when you have a logical stack made up of components where some are
//sanitized and some are not, like the grid of cards in Memory. All stacks
//must be from the same deck, and return non-nil objects from
//ImmutableSizedStack() for all, otherwise Valid() will error.
func NewOverlappedStack(stack ...ImmutableStack) MergedStack {
return &mergedStack{
stacks: stack,
overlap: true,
}
}
//NewGrowableStack creates a new growable stack with the given Deck and Cap.
func newGrowableStack(deck *Deck, maxSize int) *growableStack {
if maxSize < 0 {
maxSize = 0
}
return &growableStack{
deckPtr: deck,
deckName: deck.Name(),
indexes: make([]int, 0),
idsLastSeen: make(map[string]int),
maxSize: maxSize,
}
}
//NewSizedStack creates a new SizedStack for the given deck, with the
//specified size.
func newSizedStack(deck *Deck, size int) *sizedStack {
if size < 0 {
size = 0
}
indexes := make([]int, size)
for i := 0; i < size; i++ {
indexes[i] = emptyIndexSentinel
}
return &sizedStack{
deckPtr: deck,
deckName: deck.Name(),
indexes: indexes,
idsLastSeen: make(map[string]int),
size: size,
}
}
func (g *growableStack) importFrom(other Stack) error {
otherGrowable, ok := other.(*growableStack)
if !ok {
return errors.New("the other stack provided was not a growable")
}
myState := g.statePtr
g.copyFrom(otherGrowable)
g.statePtr = myState
return nil
}
func (g *growableStack) copyFrom(other *growableStack) {
(*g) = *other
g.indexes = make([]int, len(other.indexes))
copy(g.indexes, other.indexes)
g.idsLastSeen = make(map[string]int, len(other.idsLastSeen))
for key, val := range other.idsLastSeen {
g.idsLastSeen[key] = val
}
}
func (s *sizedStack) importFrom(other Stack) error {
otherSized, ok := other.(*sizedStack)
if !ok {
return errors.New("the other stack provided was not a sized")
}
myState := s.statePtr
s.copyFrom(otherSized)
s.statePtr = myState
return nil
}
func (s *sizedStack) copyFrom(other *sizedStack) {
*s = *other
s.indexes = make([]int, len(other.indexes))
copy(s.indexes, other.indexes)
s.idsLastSeen = make(map[string]int, len(other.idsLastSeen))
for key, val := range other.idsLastSeen {
s.idsLastSeen[key] = val
}
}
func (g *growableStack) ImmutableSizedStack() ImmutableSizedStack {
return nil
}
func (s *sizedStack) ImmutableSizedStack() ImmutableSizedStack {
return s
}
//SizedStack returns a SizedStack if all of the sub-stacks are themselves
//sized.
func (m *mergedStack) ImmutableSizedStack() ImmutableSizedStack {
for _, stack := range m.stacks {
if stack.ImmutableSizedStack() == nil {
return nil
}
}
return m
}
func (g *growableStack) MergedStack() MergedStack {
return nil
}
func (s *sizedStack) MergedStack() MergedStack {
return nil
}
func (m *mergedStack) MergedStack() MergedStack {
return m
}
func (g *growableStack) SizedStack() SizedStack {
return nil
}
func (s *sizedStack) SizedStack() SizedStack {
return s
}
func (m *mergedStack) SizedStack() SizedStack {
return nil
}
func (m *mergedStack) ImmutableStacks() []ImmutableStack {
return m.stacks
}
func (m *mergedStack) Overlapped() bool {
return m.overlap
}
func (g *growableStack) firstComponentIndex() int {
return 0
}
func (g *growableStack) lastComponentIndex() int {
return g.Len() - 1
}
func (g *growableStack) firstSlot() int {
return 0
}
func (g *growableStack) lastSlot() int {
return g.Len()
}
func (g *growableStack) nextSlot() int {
return g.lastSlot()
}
func (s *sizedStack) firstComponentIndex() int {
return s.FirstComponentIndex()
}
func (s *sizedStack) FirstComponentIndex() int {
for i, componentIndex := range s.indexes {
if componentIndex != emptyIndexSentinel {
return i
}
}
return -1
}
func (s *sizedStack) lastComponentIndex() int {
return s.LastComponentIndex()
}
func (s *sizedStack) LastComponentIndex() int {
for i := len(s.indexes) - 1; i >= 0; i-- {
if s.indexes[i] != emptyIndexSentinel {
return i
}
}
return -1
}
func (s *sizedStack) firstSlot() int {
return s.FirstSlot()
}
func (s *sizedStack) FirstSlot() int {
for i, componentIndex := range s.indexes {
if componentIndex == emptyIndexSentinel {
return i
}
}
return -1
}
func (s *sizedStack) lastSlot() int {
return s.LastSlot()
}
func (s *sizedStack) LastSlot() int {
for i := len(s.indexes) - 1; i >= 0; i-- {
if s.indexes[i] == emptyIndexSentinel {
return i
}
}
return -1
}
func (s *sizedStack) nextSlot() int {
return s.NextSlot()
}
func (s *sizedStack) NextSlot() int {
return s.FirstSlot()
}
func (m *mergedStack) FirstComponentIndex() int {
return m.firstComponentIndex()
}
func (m *mergedStack) firstComponentIndex() int {
for i, c := range m.ImmutableComponents() {
if c != nil {
return i
}
}
return -1
}
func (m *mergedStack) LastComponentIndex() int {
return m.lastComponentIndex()
}
func (m *mergedStack) lastComponentIndex() int {
components := m.ImmutableComponents()
for i := len(components) - 1; i >= 0; i-- {
if components[i] != nil {
return i
}
}
return -1
}
//Len returns the number of items in the stack.
func (g *growableStack) Len() int {
return len(g.indexes)
}
//Len returns the number of slots in the stack. It will always equal Size.
func (s *sizedStack) Len() int {
return len(s.indexes)
}
func (m *mergedStack) Len() int {
if len(m.stacks) == 0 {
return 0
}
if m.overlap {
return m.stacks[0].Len()
}
result := 0
for _, stack := range m.stacks {
result += stack.Len()
}
return result
}
func (g *growableStack) ShuffleCount() int {
return g.shuffleCount
}
func (s *sizedStack) ShuffleCount() int {
return s.shuffleCount
}
func (m *mergedStack) ShuffleCount() int {
if len(m.stacks) == 0 {
return 0
}
count := 0
for _, stack := range m.stacks {
count += stack.ShuffleCount()
}
return count
}
func (g *growableStack) NumComponents() int {
return len(g.indexes)
}
func (s *sizedStack) NumComponents() int {
count := 0
for _, index := range s.indexes {
if index != emptyIndexSentinel {
count++
}
}
return count
}
func (m *mergedStack) NumComponents() int {
if len(m.stacks) == 0 {
return 0
}
if m.overlap {
count := 0
for i, c := range m.stacks[0].ImmutableComponents() {
if c != nil {
count++
continue
}
for depth := 1; depth < len(m.stacks); depth++ {
if c := m.stacks[depth].ImmutableComponentAt(i); c != nil {
count++
break
}
}
}
return count
}
result := 0
for _, stack := range m.stacks {
result += stack.NumComponents()
}
return result
}
func (m *mergedStack) Valid() error {
if len(m.stacks) == 0 {
return errors.New("no sub-stacks provided")
}
for i, stack := range m.stacks {
if stack == nil {
return errors.New("stack " + strconv.Itoa(i) + " is nil")
}
}
deck := m.stacks[0].Deck()
for i, stack := range m.stacks {
if stack.Deck() != deck {
return errors.New("stack " + strconv.Itoa(i) + " had a different deck than other sub-stacks")
}
}
if !m.overlap {
return nil
}
for i, stack := range m.stacks {
if stack.ImmutableSizedStack() == nil {
return errors.New("stack " + strconv.Itoa(i) + " was not fixed size, but overlap stacks require them all to be fixed size")
}
}
stackLen := m.stacks[0].Len()
for i, stack := range m.stacks {
if stack.Len() != stackLen {
return errors.New("stack " + strconv.Itoa(i) + " was not the same length as the others")
}
}
return nil
}
func (g *growableStack) ImmutableComponents() []ImmutableComponentInstance {
result := make([]ImmutableComponentInstance, len(g.indexes))
for i := 0; i < len(result); i++ {
result[i] = g.ImmutableComponentAt(i)
}
return result
}
func (g *growableStack) Components() []ComponentInstance {
result := make([]ComponentInstance, len(g.indexes))
for i := 0; i < len(result); i++ {
result[i] = g.ComponentAt(i)
}
return result
}
func (s *sizedStack) ImmutableComponents() []ImmutableComponentInstance {
result := make([]ImmutableComponentInstance, len(s.indexes))
for i := 0; i < len(result); i++ {
result[i] = s.ImmutableComponentAt(i)
}
return result
}
func (s *sizedStack) Components() []ComponentInstance {
result := make([]ComponentInstance, len(s.indexes))
for i := 0; i < len(result); i++ {
result[i] = s.ComponentAt(i)
}
return result
}
func (m *mergedStack) ImmutableComponents() []ImmutableComponentInstance {
if len(m.stacks) == 0 {
return []ImmutableComponentInstance{}
}
if m.overlap {
result := make([]ImmutableComponentInstance, len(m.stacks[0].ImmutableComponents()))
for i := range m.stacks[0].ImmutableComponents() {
result[i] = m.ImmutableComponentAt(i)
}
return result
}
var result []ImmutableComponentInstance
for _, stack := range m.stacks {
result = append(result, stack.ImmutableComponents()...)
}
return result
}
func (g *growableStack) ImmutableFirst() ImmutableComponentInstance {
return g.First()
}
func (g *growableStack) First() ComponentInstance {
return g.ComponentAt(g.firstComponentIndex())
}
func (g *growableStack) ImmutableLast() ImmutableComponentInstance {
return g.Last()
}
func (g *growableStack) Last() ComponentInstance {
return g.ComponentAt(g.lastComponentIndex())
}
func (s *sizedStack) ImmutableFirst() ImmutableComponentInstance {
return s.First()
}
func (s *sizedStack) First() ComponentInstance {
return s.ComponentAt(s.firstComponentIndex())
}
func (s *sizedStack) ImmutableLast() ImmutableComponentInstance {