github.com/cockroachdb/pebble@v1.1.1-0.20240513155919-3622ade60459/objstorage/objstorageprovider/sharedcache/shared_cache_internal_test.go (about)

     1  // Copyright 2023 The LevelDB-Go and Pebble Authors. All rights reserved. Use
     2  // of this source code is governed by a BSD-style license that can be found in
     3  // the LICENSE file.
     4  
     5  package sharedcache
     6  
     7  import (
     8  	"reflect"
     9  	"testing"
    10  
    11  	"github.com/stretchr/testify/require"
    12  )
    13  
    14  func TestSharedCacheLruList(t *testing.T) {
    15  	var s shard
    16  	s.mu.blocks = make([]cacheBlockState, 100)
    17  	expect := func(vals ...int) {
    18  		t.Helper()
    19  		if s.mu.lruHead == invalidBlockIndex {
    20  			if len(vals) != 0 {
    21  				t.Fatalf("expected non-empty list")
    22  			}
    23  			return
    24  		}
    25  		var list []int
    26  		prev := s.lruPrev(s.mu.lruHead)
    27  		b := s.mu.lruHead
    28  		for {
    29  			list = append(list, int(b))
    30  			if s.lruPrev(b) != prev {
    31  				t.Fatalf("back link broken: %d:next=%d,prev=%d  %d:next=%d,prev=%d",
    32  					prev, s.lruNext(prev), s.lruPrev(prev),
    33  					b, s.lruNext(b), s.lruPrev(b),
    34  				)
    35  			}
    36  			prev = b
    37  			b = s.lruNext(b)
    38  			if b == s.mu.lruHead {
    39  				break
    40  			}
    41  		}
    42  		if !reflect.DeepEqual(vals, list) {
    43  			t.Fatalf("expected %v, got %v", vals, list)
    44  		}
    45  	}
    46  
    47  	s.mu.lruHead = invalidBlockIndex
    48  	expect()
    49  	s.lruInsertFront(1)
    50  	expect(1)
    51  	s.lruInsertFront(10)
    52  	expect(10, 1)
    53  	s.lruInsertFront(5)
    54  	expect(5, 10, 1)
    55  	s.lruUnlink(5)
    56  	expect(10, 1)
    57  	s.lruUnlink(1)
    58  	expect(10)
    59  	s.lruUnlink(10)
    60  	expect()
    61  }
    62  
    63  func TestSharedCacheFreeList(t *testing.T) {
    64  	var s shard
    65  	s.mu.blocks = make([]cacheBlockState, 100)
    66  	expect := func(vals ...int) {
    67  		t.Helper()
    68  		var list []int
    69  		for b := s.mu.freeHead; b != invalidBlockIndex; b = s.mu.blocks[b].next {
    70  			list = append(list, int(b))
    71  		}
    72  		if !reflect.DeepEqual(vals, list) {
    73  			t.Fatalf("expected %v, got %v", vals, list)
    74  		}
    75  	}
    76  	s.mu.freeHead = invalidBlockIndex
    77  	expect()
    78  	s.freePush(1)
    79  	expect(1)
    80  	s.freePush(10)
    81  	expect(10, 1)
    82  	s.freePush(20)
    83  	expect(20, 10, 1)
    84  	require.Equal(t, cacheBlockIndex(20), s.freePop())
    85  	expect(10, 1)
    86  	require.Equal(t, cacheBlockIndex(10), s.freePop())
    87  	expect(1)
    88  	require.Equal(t, cacheBlockIndex(1), s.freePop())
    89  	expect()
    90  }