This repository has been archived by the owner on Feb 1, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathstrings.go
873 lines (779 loc) · 22.8 KB
/
strings.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
// this was modified after generation to work with the normal string type, do not regenerate
// Generated by: gen
// TypeWriter: gen
// Directive: +gen on *dm.String
// See http://clipperhouse.github.io/gen for documentation
// Sort implementation is a modification of http://golang.org/pkg/sort/#Sort
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found at http://golang.org/LICENSE.
package rex
import (
"errors"
)
// Strings is a slice of type string. Use it where you would use []string.
type Strings []string
// All verifies that all elements of Strings return true for the passed func. See: http://clipperhouse.github.io/gen/#All
func (rcv Strings) All(fn func(string) bool) bool {
for _, v := range rcv {
if !fn(v) {
return false
}
}
return true
}
// Any verifies that one or more elements of Strings return true for the passed func. See: http://clipperhouse.github.io/gen/#Any
func (rcv Strings) Any(fn func(string) bool) bool {
for _, v := range rcv {
if fn(v) {
return true
}
}
return false
}
// Count gives the number elements of Strings that return true for the passed func. See: http://clipperhouse.github.io/gen/#Count
func (rcv Strings) Count(fn func(string) bool) (result int) {
for _, v := range rcv {
if fn(v) {
result++
}
}
return
}
// Distinct returns a new Strings slice whose elements are unique. See: http://clipperhouse.github.io/gen/#Distinct
func (rcv Strings) Distinct() (result Strings) {
appended := make(map[string]bool)
for _, v := range rcv {
if !appended[v] {
result = append(result, v)
appended[v] = true
}
}
return result
}
// DistinctBy returns a new Strings slice whose elements are unique, where equality is defined by a passed func. See: http://clipperhouse.github.io/gen/#DistinctBy
func (rcv Strings) DistinctBy(equal func(string, string) bool) (result Strings) {
for _, v := range rcv {
eq := func(_app string) bool {
return equal(v, _app)
}
if !result.Any(eq) {
result = append(result, v)
}
}
return result
}
// Each iterates over Strings and executes the passed func against each element. See: http://clipperhouse.github.io/gen/#Each
func (rcv Strings) Each(fn func(string)) {
for _, v := range rcv {
fn(v)
}
}
// First returns the first element that returns true for the passed func. Returns error if no elements return true. See: http://clipperhouse.github.io/gen/#First
func (rcv Strings) First(fn func(string) bool) (result string, err error) {
for _, v := range rcv {
if fn(v) {
result = v
return
}
}
err = errors.New("no Strings elements return true for passed func")
return
}
// IsSortedBy reports whether an instance of Strings is sorted, using the pass func to define ‘less’. See: http://clipperhouse.github.io/gen/#SortBy
func (rcv Strings) IsSortedBy(less func(string, string) bool) bool {
n := len(rcv)
for i := n - 1; i > 0; i-- {
if less(rcv[i], rcv[i-1]) {
return false
}
}
return true
}
// IsSortedDesc reports whether an instance of Strings is sorted in descending order, using the pass func to define ‘less’. See: http://clipperhouse.github.io/gen/#SortBy
func (rcv Strings) IsSortedByDesc(less func(string, string) bool) bool {
greater := func(a, b string) bool {
return a != b && !less(a, b)
}
return rcv.IsSortedBy(greater)
}
// MaxBy returns an element of Strings containing the maximum value, when compared to other elements using a passed func defining ‘less’. In the case of multiple items being equally maximal, the last such element is returned. Returns error if no elements. See: http://clipperhouse.github.io/gen/#MaxBy
func (rcv Strings) MaxBy(less func(string, string) bool) (result string, err error) {
l := len(rcv)
if l == 0 {
err = errors.New("cannot determine the MaxBy of an empty slice")
return
}
m := 0
for i := 1; i < l; i++ {
if rcv[i] != rcv[m] && !less(rcv[i], rcv[m]) {
m = i
}
}
result = rcv[m]
return
}
// MinBy returns an element of Strings containing the minimum value, when compared to other elements using a passed func defining ‘less’. In the case of multiple items being equally minimal, the first such element is returned. Returns error if no elements. See: http://clipperhouse.github.io/gen/#MinBy
func (rcv Strings) MinBy(less func(string, string) bool) (result string, err error) {
l := len(rcv)
if l == 0 {
err = errors.New("cannot determine the Min of an empty slice")
return
}
m := 0
for i := 1; i < l; i++ {
if less(rcv[i], rcv[m]) {
m = i
}
}
result = rcv[m]
return
}
// Single returns exactly one element of Strings that returns true for the passed func. Returns error if no or multiple elements return true. See: http://clipperhouse.github.io/gen/#Single
func (rcv Strings) Single(fn func(string) bool) (result string, err error) {
var candidate string
found := false
for _, v := range rcv {
if fn(v) {
if found {
err = errors.New("multiple Strings elements return true for passed func")
return
}
candidate = v
found = true
}
}
if found {
result = candidate
} else {
err = errors.New("no Strings elements return true for passed func")
}
return
}
// SortBy returns a new ordered Strings slice, determined by a func defining ‘less’. See: http://clipperhouse.github.io/gen/#SortBy
func (rcv Strings) SortBy(less func(string, string) bool) Strings {
result := make(Strings, len(rcv))
copy(result, rcv)
// Switch to heapsort if depth of 2*ceil(lg(n+1)) is reached.
n := len(result)
maxDepth := 0
for i := n; i > 0; i >>= 1 {
maxDepth++
}
maxDepth *= 2
quickSortStrings(result, less, 0, n, maxDepth)
return result
}
// SortByDesc returns a new, descending-ordered Strings slice, determined by a func defining ‘less’. See: http://clipperhouse.github.io/gen/#SortBy
func (rcv Strings) SortByDesc(less func(string, string) bool) Strings {
greater := func(a, b string) bool {
return a != b && !less(a, b)
}
return rcv.SortBy(greater)
}
// Where returns a new Strings slice whose elements return true for func. See: http://clipperhouse.github.io/gen/#Where
func (rcv Strings) Where(fn func(string) bool) (result Strings) {
for _, v := range rcv {
if fn(v) {
result = append(result, v)
}
}
return result
}
// Sort implementation based on http://golang.org/pkg/sort/#Sort, see top of this file
func swapStrings(rcv Strings, a, b int) {
rcv[a], rcv[b] = rcv[b], rcv[a]
}
// Insertion sort
func insertionSortStrings(rcv Strings, less func(string, string) bool, a, b int) {
for i := a + 1; i < b; i++ {
for j := i; j > a && less(rcv[j], rcv[j-1]); j-- {
swapStrings(rcv, j, j-1)
}
}
}
// siftDown implements the heap property on rcv[lo, hi).
// first is an offset into the array where the root of the heap lies.
func siftDownStrings(rcv Strings, less func(string, string) bool, lo, hi, first int) {
root := lo
for {
child := 2*root + 1
if child >= hi {
break
}
if child+1 < hi && less(rcv[first+child], rcv[first+child+1]) {
child++
}
if !less(rcv[first+root], rcv[first+child]) {
return
}
swapStrings(rcv, first+root, first+child)
root = child
}
}
func heapSortStrings(rcv Strings, less func(string, string) bool, a, b int) {
first := a
lo := 0
hi := b - a
// Build heap with greatest element at top.
for i := (hi - 1) / 2; i >= 0; i-- {
siftDownStrings(rcv, less, i, hi, first)
}
// Pop elements, largest first, into end of rcv.
for i := hi - 1; i >= 0; i-- {
swapStrings(rcv, first, first+i)
siftDownStrings(rcv, less, lo, i, first)
}
}
// Quicksort, following Bentley and McIlroy,
// Engineering a Sort Function, SP&E November 1993.
// medianOfThree moves the median of the three values rcv[a], rcv[b], rcv[c] into rcv[a].
func medianOfThreeStrings(rcv Strings, less func(string, string) bool, a, b, c int) {
m0 := b
m1 := a
m2 := c
// bubble sort on 3 elements
if less(rcv[m1], rcv[m0]) {
swapStrings(rcv, m1, m0)
}
if less(rcv[m2], rcv[m1]) {
swapStrings(rcv, m2, m1)
}
if less(rcv[m1], rcv[m0]) {
swapStrings(rcv, m1, m0)
}
// now rcv[m0] <= rcv[m1] <= rcv[m2]
}
func swapRangeStrings(rcv Strings, a, b, n int) {
for i := 0; i < n; i++ {
swapStrings(rcv, a+i, b+i)
}
}
func doPivotStrings(rcv Strings, less func(string, string) bool, lo, hi int) (midlo, midhi int) {
m := lo + (hi-lo)/2 // Written like this to avoid integer overflow.
if hi-lo > 40 {
// Tukey's Ninther, median of three medians of three.
s := (hi - lo) / 8
medianOfThreeStrings(rcv, less, lo, lo+s, lo+2*s)
medianOfThreeStrings(rcv, less, m, m-s, m+s)
medianOfThreeStrings(rcv, less, hi-1, hi-1-s, hi-1-2*s)
}
medianOfThreeStrings(rcv, less, lo, m, hi-1)
// Invariants are:
// rcv[lo] = pivot (set up by ChoosePivot)
// rcv[lo <= i < a] = pivot
// rcv[a <= i < b] < pivot
// rcv[b <= i < c] is unexamined
// rcv[c <= i < d] > pivot
// rcv[d <= i < hi] = pivot
//
// Once b meets c, can swap the "= pivot" sections
// into the middle of the slice.
pivot := lo
a, b, c, d := lo+1, lo+1, hi, hi
for {
for b < c {
if less(rcv[b], rcv[pivot]) { // rcv[b] < pivot
b++
} else if !less(rcv[pivot], rcv[b]) { // rcv[b] = pivot
swapStrings(rcv, a, b)
a++
b++
} else {
break
}
}
for b < c {
if less(rcv[pivot], rcv[c-1]) { // rcv[c-1] > pivot
c--
} else if !less(rcv[c-1], rcv[pivot]) { // rcv[c-1] = pivot
swapStrings(rcv, c-1, d-1)
c--
d--
} else {
break
}
}
if b >= c {
break
}
// rcv[b] > pivot; rcv[c-1] < pivot
swapStrings(rcv, b, c-1)
b++
c--
}
min := func(a, b int) int {
if a < b {
return a
}
return b
}
n := min(b-a, a-lo)
swapRangeStrings(rcv, lo, b-n, n)
n = min(hi-d, d-c)
swapRangeStrings(rcv, c, hi-n, n)
return lo + b - a, hi - (d - c)
}
func quickSortStrings(rcv Strings, less func(string, string) bool, a, b, maxDepth int) {
for b-a > 7 {
if maxDepth == 0 {
heapSortStrings(rcv, less, a, b)
return
}
maxDepth--
mlo, mhi := doPivotStrings(rcv, less, a, b)
// Avoiding recursion on the larger subproblem guarantees
// a stack depth of at most lg(b-a).
if mlo-a < b-mhi {
quickSortStrings(rcv, less, a, mlo, maxDepth)
a = mhi // i.e., quickSortStrings(rcv, mhi, b)
} else {
quickSortStrings(rcv, less, mhi, b, maxDepth)
b = mlo // i.e., quickSortStrings(rcv, a, mlo)
}
}
if b-a > 1 {
insertionSortStrings(rcv, less, a, b)
}
}
// The primary type that represents a set
type StringSet map[string]struct{}
// Creates and returns a reference to an empty set.
func NewStringSet() StringSet {
return make(StringSet)
}
// Creates and returns a reference to a set from an existing slice
func NewStringSetFromSlice(s []string) StringSet {
a := NewStringSet()
for _, item := range s {
a.Add(item)
}
return a
}
// Adds an item to the current set if it doesn't already exist in the set.
func (set StringSet) Add(i string) bool {
_, found := set[i]
set[i] = struct{}{}
return !found //False if it existed already
}
// Determines if a given item is already in the set.
func (set StringSet) Contains(i string) bool {
_, found := set[i]
return found
}
// Determines if the given items are all in the set
func (set StringSet) ContainsAll(i ...string) bool {
allSet := NewStringSetFromSlice(i)
if allSet.IsSubset(set) {
return true
}
return false
}
// Determines if every item in the other set is in this set.
func (set StringSet) IsSubset(other StringSet) bool {
for elem := range set {
if !other.Contains(elem) {
return false
}
}
return true
}
// Determines if every item of this set is in the other set.
func (set StringSet) IsSuperset(other StringSet) bool {
return other.IsSubset(set)
}
// Returns a new set with all items in both sets.
func (set StringSet) Union(other StringSet) StringSet {
unionedSet := NewStringSet()
for elem := range set {
unionedSet.Add(elem)
}
for elem := range other {
unionedSet.Add(elem)
}
return unionedSet
}
// Returns a new set with items that exist only in both sets.
func (set StringSet) Intersect(other StringSet) StringSet {
intersection := NewStringSet()
// loop over smaller set
if set.Cardinality() < other.Cardinality() {
for elem := range set {
if other.Contains(elem) {
intersection.Add(elem)
}
}
} else {
for elem := range other {
if set.Contains(elem) {
intersection.Add(elem)
}
}
}
return intersection
}
// Returns a new set with items in the current set but not in the other set
func (set StringSet) Difference(other StringSet) StringSet {
differencedSet := NewStringSet()
for elem := range set {
if !other.Contains(elem) {
differencedSet.Add(elem)
}
}
return differencedSet
}
// Returns a new set with items in the current set or the other set but not in both.
func (set StringSet) SymmetricDifference(other StringSet) StringSet {
aDiff := set.Difference(other)
bDiff := other.Difference(set)
return aDiff.Union(bDiff)
}
// Clears the entire set to be the empty set.
func (set *StringSet) Clear() {
*set = make(StringSet)
}
// Allows the removal of a single item in the set.
func (set StringSet) Remove(i string) {
delete(set, i)
}
// Cardinality returns how many items are currently in the set.
func (set StringSet) Cardinality() int {
return len(set)
}
// Iter() returns a channel of type string that you can range over.
func (set StringSet) Iter() <-chan string {
ch := make(chan string)
go func() {
for elem := range set {
ch <- elem
}
close(ch)
}()
return ch
}
// Equal determines if two sets are equal to each other.
// If they both are the same size and have the same items they are considered equal.
// Order of items is not relevent for sets to be equal.
func (set StringSet) Equal(other StringSet) bool {
if set.Cardinality() != other.Cardinality() {
return false
}
for elem := range set {
if !other.Contains(elem) {
return false
}
}
return true
}
// Returns a clone of the set.
// Does NOT clone the underlying elements.
func (set StringSet) Clone() StringSet {
clonedSet := NewStringSet()
for elem := range set {
clonedSet.Add(elem)
}
return clonedSet
}
// StringElement is an element of a linked list.
type StringElement struct {
// Next and previous pointers in the doubly-linked list of elements.
// To simplify the implementation, internally a list l is implemented
// as a ring, such that &l.root is both the next element of the last
// list element (l.Back()) and the previous element of the first list
// element (l.Front()).
next, prev *StringElement
// The list to which this element belongs.
list *StringList
// The value stored with this element.
Value string
}
// Next returns the next list element or nil.
func (e *StringElement) Next() *StringElement {
if p := e.next; e.list != nil && p != &e.list.root {
return p
}
return nil
}
// Prev returns the previous list element or nil.
func (e *StringElement) Prev() *StringElement {
if p := e.prev; e.list != nil && p != &e.list.root {
return p
}
return nil
}
// StringList represents a doubly linked list.
// The zero value for StringList is an empty list ready to use.
type StringList struct {
root StringElement // sentinel list element, only &root, root.prev, and root.next are used
len int // current list length excluding (this) sentinel element
}
// Init initializes or clears list l.
func (l *StringList) Init() *StringList {
l.root.next = &l.root
l.root.prev = &l.root
l.len = 0
return l
}
// New returns an initialized list.
func NewStringList() *StringList { return new(StringList).Init() }
// Len returns the number of elements of list l.
// The complexity is O(1).
func (l *StringList) Len() int { return l.len }
// Front returns the first element of list l or nil.
func (l *StringList) Front() *StringElement {
if l.len == 0 {
return nil
}
return l.root.next
}
// Back returns the last element of list l or nil.
func (l *StringList) Back() *StringElement {
if l.len == 0 {
return nil
}
return l.root.prev
}
// lazyInit lazily initializes a zero StringList value.
func (l *StringList) lazyInit() {
if l.root.next == nil {
l.Init()
}
}
// insert inserts e after at, increments l.len, and returns e.
func (l *StringList) insert(e, at *StringElement) *StringElement {
n := at.next
at.next = e
e.prev = at
e.next = n
n.prev = e
e.list = l
l.len++
return e
}
// insertValue is a convenience wrapper for insert(&StringElement{Value: v}, at).
func (l *StringList) insertValue(v string, at *StringElement) *StringElement {
return l.insert(&StringElement{Value: v}, at)
}
// remove removes e from its list, decrements l.len, and returns e.
func (l *StringList) remove(e *StringElement) *StringElement {
e.prev.next = e.next
e.next.prev = e.prev
e.next = nil // avoid memory leaks
e.prev = nil // avoid memory leaks
e.list = nil
l.len--
return e
}
// Remove removes e from l if e is an element of list l.
// It returns the element value e.Value.
func (l *StringList) Remove(e *StringElement) string {
if e.list == l {
// if e.list == l, l must have been initialized when e was inserted
// in l or l == nil (e is a zero StringElement) and l.remove will crash
l.remove(e)
}
return e.Value
}
// PushFront inserts a new element e with value v at the front of list l and returns e.
func (l *StringList) PushFront(v string) *StringElement {
l.lazyInit()
return l.insertValue(v, &l.root)
}
// PushBack inserts a new element e with value v at the back of list l and returns e.
func (l *StringList) PushBack(v string) *StringElement {
l.lazyInit()
return l.insertValue(v, l.root.prev)
}
// InsertBefore inserts a new element e with value v immediately before mark and returns e.
// If mark is not an element of l, the list is not modified.
func (l *StringList) InsertBefore(v string, mark *StringElement) *StringElement {
if mark.list != l {
return nil
}
// see comment in StringList.Remove about initialization of l
return l.insertValue(v, mark.prev)
}
// InsertAfter inserts a new element e with value v immediately after mark and returns e.
// If mark is not an element of l, the list is not modified.
func (l *StringList) InsertAfter(v string, mark *StringElement) *StringElement {
if mark.list != l {
return nil
}
// see comment in StringList.Remove about initialization of l
return l.insertValue(v, mark)
}
// MoveToFront moves element e to the front of list l.
// If e is not an element of l, the list is not modified.
func (l *StringList) MoveToFront(e *StringElement) {
if e.list != l || l.root.next == e {
return
}
// see comment in StringList.Remove about initialization of l
l.insert(l.remove(e), &l.root)
}
// MoveToBack moves element e to the back of list l.
// If e is not an element of l, the list is not modified.
func (l *StringList) MoveToBack(e *StringElement) {
if e.list != l || l.root.prev == e {
return
}
// see comment in StringList.Remove about initialization of l
l.insert(l.remove(e), l.root.prev)
}
// MoveBefore moves element e to its new position before mark.
// If e or mark is not an element of l, or e == mark, the list is not modified.
func (l *StringList) MoveBefore(e, mark *StringElement) {
if e.list != l || e == mark || mark.list != l {
return
}
l.insert(l.remove(e), mark.prev)
}
// MoveAfter moves element e to its new position after mark.
// If e is not an element of l, or e == mark, the list is not modified.
func (l *StringList) MoveAfter(e, mark *StringElement) {
if e.list != l || e == mark || mark.list != l {
return
}
l.insert(l.remove(e), mark)
}
// PushBackList inserts a copy of an other list at the back of list l.
// The lists l and other may be the same.
func (l *StringList) PushBackList(other *StringList) {
l.lazyInit()
for i, e := other.Len(), other.Front(); i > 0; i, e = i-1, e.Next() {
l.insertValue(e.Value, l.root.prev)
}
}
// PushFrontList inserts a copy of an other list at the front of list l.
// The lists l and other may be the same.
func (l *StringList) PushFrontList(other *StringList) {
l.lazyInit()
for i, e := other.Len(), other.Back(); i > 0; i, e = i-1, e.Prev() {
l.insertValue(e.Value, &l.root)
}
}
// A Ring is an element of a circular list, or ring.
// Rings do not have a beginning or end; a pointer to any ring element
// serves as reference to the entire ring. Empty rings are represented
// as nil Ring pointers. The zero value for a Ring is a one-element
// ring with a nil Value.
//
type StringRing struct {
next, prev *StringRing
Value string // for use by client; untouched by this library
}
func (r *StringRing) init() *StringRing {
r.next = r
r.prev = r
return r
}
// Next returns the next ring element. r must not be empty.
func (r *StringRing) Next() *StringRing {
if r.next == nil {
return r.init()
}
return r.next
}
// Prev returns the previous ring element. r must not be empty.
func (r *StringRing) Prev() *StringRing {
if r.next == nil {
return r.init()
}
return r.prev
}
// Move moves n % r.Len() elements backward (n < 0) or forward (n >= 0)
// in the ring and returns that ring element. r must not be empty.
//
func (r *StringRing) Move(n int) *StringRing {
if r.next == nil {
return r.init()
}
switch {
case n < 0:
for ; n < 0; n++ {
r = r.prev
}
case n > 0:
for ; n > 0; n-- {
r = r.next
}
}
return r
}
// New creates a ring of n elements.
func NewStringRing(n int) *StringRing {
if n <= 0 {
return nil
}
r := new(StringRing)
p := r
for i := 1; i < n; i++ {
p.next = &StringRing{prev: p}
p = p.next
}
p.next = r
r.prev = p
return r
}
// Link connects ring r with ring s such that r.Next()
// becomes s and returns the original value for r.Next().
// r must not be empty.
//
// If r and s point to the same ring, linking
// them removes the elements between r and s from the ring.
// The removed elements form a subring and the result is a
// reference to that subring (if no elements were removed,
// the result is still the original value for r.Next(),
// and not nil).
//
// If r and s point to different rings, linking
// them creates a single ring with the elements of s inserted
// after r. The result points to the element following the
// last element of s after insertion.
//
func (r *StringRing) Link(s *StringRing) *StringRing {
n := r.Next()
if s != nil {
p := s.Prev()
// Note: Cannot use multiple assignment because
// evaluation order of LHS is not specified.
r.next = s
s.prev = r
n.prev = p
p.next = n
}
return n
}
// Unlink removes n % r.Len() elements from the ring r, starting
// at r.Next(). If n % r.Len() == 0, r remains unchanged.
// The result is the removed subring. r must not be empty.
//
func (r *StringRing) Unlink(n int) *StringRing {
if n <= 0 {
return nil
}
return r.Link(r.Move(n + 1))
}
// Len computes the number of elements in ring r.
// It executes in time proportional to the number of elements.
//
func (r *StringRing) Len() int {
n := 0
if r != nil {
n = 1
for p := r.Next(); p != r; p = p.next {
n++
}
}
return n
}
// Do calls function f on each element of the ring, in forward order.
// The behavior of Do is undefined if f changes *r.
func (r *StringRing) Do(f func(string)) {
if r != nil {
f(r.Value)
for p := r.Next(); p != r; p = p.next {
f(p.Value)
}
}
}