github.com/phuslu/lru@v1.0.16-0.20240421170520-46288a2fd47c/bytes_shard_list.go (about)

     1  // Copyright 2023-2024 Phus Lu. All rights reserved.
     2  
     3  package lru
     4  
     5  import (
     6  	"unsafe"
     7  )
     8  
     9  func (s *bytesshard) list_Init(size uint32) {
    10  	size += 1
    11  	if len(s.list) == 0 {
    12  		s.list = make([]bytesnode, size)
    13  	}
    14  	for i := uint32(0); i < size; i++ {
    15  		s.list[i].next = (i + 1) % size
    16  		s.list[i].prev = (i + size - 1) % size
    17  	}
    18  }
    19  
    20  func (s *bytesshard) list_Back() uint32 {
    21  	return s.list[0].prev
    22  }
    23  
    24  func (s *bytesshard) list_MoveToFront(i uint32) {
    25  	root := &s.list[0]
    26  	if root.next == i {
    27  		return
    28  	}
    29  
    30  	base := unsafe.Pointer(root)
    31  	nodei := (*bytesnode)(unsafe.Add(base, uintptr(i)*unsafe.Sizeof(s.list[0])))
    32  
    33  	((*bytesnode)(unsafe.Add(base, uintptr(nodei.prev)*unsafe.Sizeof(s.list[0])))).next = nodei.next
    34  	((*bytesnode)(unsafe.Add(base, uintptr(nodei.next)*unsafe.Sizeof(s.list[0])))).prev = nodei.prev
    35  
    36  	nodei.prev = 0
    37  	nodei.next = root.next
    38  
    39  	root.next = i
    40  	((*bytesnode)(unsafe.Add(base, uintptr(nodei.next)*unsafe.Sizeof(s.list[0])))).prev = i
    41  }
    42  
    43  func (s *bytesshard) list_MoveToBack(i uint32) {
    44  	j := s.list[0].prev
    45  	if i == j {
    46  		return
    47  	}
    48  
    49  	base := unsafe.Pointer(&s.list[0])
    50  	nodei := (*bytesnode)(unsafe.Add(base, uintptr(i)*unsafe.Sizeof(s.list[0])))
    51  	at := (*bytesnode)(unsafe.Add(base, uintptr(j)*unsafe.Sizeof(s.list[0])))
    52  
    53  	((*bytesnode)(unsafe.Add(base, uintptr(nodei.prev)*unsafe.Sizeof(s.list[0])))).next = nodei.next
    54  	((*bytesnode)(unsafe.Add(base, uintptr(nodei.next)*unsafe.Sizeof(s.list[0])))).prev = nodei.prev
    55  
    56  	nodei.prev = j
    57  	nodei.next = at.next
    58  
    59  	((*bytesnode)(unsafe.Add(base, uintptr(j)*unsafe.Sizeof(s.list[0])))).next = i
    60  	((*bytesnode)(unsafe.Add(base, uintptr(nodei.next)*unsafe.Sizeof(s.list[0])))).prev = i
    61  }