github.com/Asutorufa/yuhaiin@v0.3.6-0.20240502055049-7984da7023a0/pkg/utils/synclist/list.go (about) 1 package synclist 2 3 import ( 4 "container/list" 5 "sync" 6 ) 7 8 type Element[T any] struct { 9 // The list to which this element belongs. 10 e *list.Element 11 12 // The value stored with this element. 13 Value T 14 } 15 16 func (e *Element[T]) Next() *Element[T] { 17 n := e.e.Next() 18 if n == nil { 19 return nil 20 } 21 22 return &Element[T]{e: n, Value: n.Value.(T)} 23 } 24 25 func (e *Element[T]) Prev() *Element[T] { 26 p := e.e.Prev() 27 if p == nil { 28 return nil 29 } 30 31 return &Element[T]{e: p, Value: p.Value.(T)} 32 } 33 34 func (e *Element[T]) SetValue(t T) *Element[T] { 35 e.Value = t 36 return e 37 } 38 39 type SyncList[T any] struct { 40 l *list.List 41 mu sync.RWMutex 42 } 43 44 func New[T any]() *SyncList[T] { return &SyncList[T]{l: list.New()} } 45 46 func (s *SyncList[T]) MoveToFront(e *Element[T]) { 47 s.mu.Lock() 48 defer s.mu.Unlock() 49 e.e.Value = e.Value 50 s.l.MoveToFront(e.e) 51 } 52 53 func (s *SyncList[T]) PushFront(v T) *Element[T] { 54 s.mu.Lock() 55 defer s.mu.Unlock() 56 return &Element[T]{e: s.l.PushFront(v), Value: v} 57 } 58 59 func (s *SyncList[T]) PushBack(v T) *Element[T] { 60 s.mu.Lock() 61 defer s.mu.Unlock() 62 return &Element[T]{e: s.l.PushBack(v), Value: v} 63 } 64 65 func (s *SyncList[T]) Remove(e *Element[T]) T { 66 s.mu.Lock() 67 defer s.mu.Unlock() 68 s.l.Remove(e.e) 69 return e.Value 70 } 71 72 func (s *SyncList[T]) Back() *Element[T] { 73 s.mu.RLock() 74 defer s.mu.RUnlock() 75 b := s.l.Back() 76 if b == nil { 77 return nil 78 } 79 return &Element[T]{e: b, Value: b.Value.(T)} 80 } 81 82 func (s *SyncList[T]) Front() *Element[T] { 83 s.mu.RLock() 84 defer s.mu.RUnlock() 85 b := s.l.Front() 86 if b == nil { 87 return nil 88 } 89 return &Element[T]{e: b, Value: b.Value.(T)} 90 } 91 92 func (s *SyncList[T]) Len() int { 93 s.mu.RLock() 94 defer s.mu.RUnlock() 95 return s.l.Len() 96 }