gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/pkg/ilist/ring_test.go (about)

     1  // Copyright 2023 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //	http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package ring
    16  
    17  import (
    18  	"testing"
    19  )
    20  
    21  type testContainer struct {
    22  	value int
    23  	entry testEntry
    24  }
    25  
    26  func newContainer(value int) *testContainer {
    27  	c := &testContainer{value: value}
    28  	c.entry.Init(c)
    29  	return c
    30  }
    31  
    32  func TestAdd(t *testing.T) {
    33  	e1 := newContainer(1)
    34  	e2 := newContainer(2)
    35  	e3 := newContainer(3)
    36  
    37  	e1.entry.Add(&e2.entry)
    38  	e1.entry.Add(&e3.entry)
    39  
    40  	sum := 0
    41  	want := 6
    42  	e := e1
    43  	for {
    44  		sum += e.value
    45  		e = e.entry.Next()
    46  		if e == e1 {
    47  			break
    48  		}
    49  	}
    50  	if sum != want {
    51  		t.Errorf("wrong sum: want %d, got %d", want, sum)
    52  	}
    53  }
    54  
    55  func TestRemove(t *testing.T) {
    56  	e1 := newContainer(1)
    57  	e2 := newContainer(2)
    58  	e3 := newContainer(3)
    59  
    60  	e1.entry.Add(&e2.entry)
    61  	e2.entry.Add(&e3.entry)
    62  	e2.entry.Remove()
    63  
    64  	sum := 0
    65  	want := 4
    66  	e := e1
    67  	for {
    68  		sum += e.value
    69  		e = e.entry.Next()
    70  		if e == e1 {
    71  			break
    72  		}
    73  	}
    74  	if sum != want {
    75  		t.Errorf("wrong sum: want %d, got %d", want, sum)
    76  	}
    77  }
    78  
    79  func TestEmpty(t *testing.T) {
    80  	head := newContainer(1)
    81  	e2 := newContainer(2)
    82  	e3 := newContainer(3)
    83  
    84  	head.entry.Add(&e2.entry)
    85  	e2.entry.Add(&e3.entry)
    86  	e3.entry.Remove()
    87  	e2.entry.Remove()
    88  
    89  	sum := 0
    90  	want := 0
    91  	for e := head.entry.Next(); e != head; e = e.entry.Next() {
    92  		sum += e.value
    93  	}
    94  	if sum != want {
    95  		t.Errorf("wrong sum: want %d, got %d", want, sum)
    96  	}
    97  }