1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // The ring package implements operations on circular lists.
8 // A Ring is an element of a circular list, or ring.
9 // Rings do not have a beginning or end; a pointer to any ring element
10 // serves as reference to the entire ring. Empty rings are represented
11 // as nil Ring pointers. The zero value for a Ring is a one-element
12 // ring with a nil Value.
16 Value
interface{} // for use by client; untouched by this library
20 func (r
*Ring
) init() *Ring
{
27 // Next returns the next ring element. r must not be empty.
28 func (r
*Ring
) Next() *Ring
{
36 // Prev returns the previous ring element. r must not be empty.
37 func (r
*Ring
) Prev() *Ring
{
45 // Move moves n % r.Len() elements backward (n < 0) or forward (n >= 0)
46 // in the ring and returns that ring element. r must not be empty.
48 func (r
*Ring
) Move(n
int) *Ring
{
66 // New creates a ring of n elements.
67 func New(n
int) *Ring
{
73 for i
:= 1; i
< n
; i
++ {
74 p
.next
= &Ring
{prev
: p
}
83 // Link connects ring r with with ring s such that r.Next()
84 // becomes s and returns the original value for r.Next().
85 // r must not be empty.
87 // If r and s point to the same ring, linking
88 // them removes the elements between r and s from the ring.
89 // The removed elements form a subring and the result is a
90 // reference to that subring (if no elements were removed,
91 // the result is still the original value for r.Next(),
94 // If r and s point to different rings, linking
95 // them creates a single ring with the elements of s inserted
96 // after r. The result points to the element following the
97 // last element of s after insertion.
99 func (r
*Ring
) Link(s
*Ring
) *Ring
{
103 // Note: Cannot use multiple assignment because
104 // evaluation order of LHS is not specified.
114 // Unlink removes n % r.Len() elements from the ring r, starting
115 // at r.Next(). If n % r.Len() == 0, r remains unchanged.
116 // The result is the removed subring. r must not be empty.
118 func (r
*Ring
) Unlink(n
int) *Ring
{
122 return r
.Link(r
.Move(n
+ 1))
126 // Len computes the number of elements in ring r.
127 // It executes in time proportional to the number of elements.
129 func (r
*Ring
) Len() int {
133 for p
:= r
.Next(); p
!= r
; p
= p
.next
{
141 func (r
*Ring
) Iter() <-chan interface{} {
142 c
:= make(chan interface{})
146 for p
:= r
.Next(); p
!= r
; p
= p
.next
{