github.com/bruceshao/lockfree@v1.1.3-0.20230816090528-e89824c0a6e9/buffer_386.go (about)

     1  //go:build 386
     2  
     3  /*
     4   * Copyright (C) THL A29 Limited, a Tencent company. All rights reserved.
     5   *
     6   * SPDX-License-Identifier: Apache-2.0
     7   *
     8   */
     9  
    10  package lockfree
    11  
    12  import (
    13  	"sync"
    14  )
    15  
    16  type e[T any] struct {
    17  	c   uint64
    18  	val T
    19  }
    20  
    21  // ringBuffer 具体对象的存放区域,通过数组(定长切片)实现环状数据结构
    22  // 其中e为具体对象,非指针,这样可以一次性进行内存申请
    23  type ringBuffer[T any] struct {
    24  	sync.RWMutex
    25  	// 增加默认的对象以便于return,处理data race问题
    26  	tDefault T
    27  	buf      []e[T]
    28  	capMask  uint64
    29  }
    30  
    31  func newRingBuffer[T any](cap int) *ringBuffer[T] {
    32  	x := ringBuffer[T]{
    33  		capMask: uint64(cap) - 1,
    34  		buf:     make([]e[T], cap),
    35  	}
    36  	return &x
    37  }
    38  
    39  func (r *ringBuffer[T]) write(c uint64, v T) {
    40  	x := &r.buf[c&r.capMask]
    41  	r.Lock()
    42  	defer r.Unlock()
    43  	x.val = v
    44  	x.c = c + 1
    45  }
    46  
    47  func (r *ringBuffer[T]) element(c uint64) e[T] {
    48  	return r.buf[c&r.capMask]
    49  }
    50  
    51  func (r *ringBuffer[T]) contains(c uint64) (T, *uint64, bool) {
    52  	x := &r.buf[c&r.capMask]
    53  	r.RLock()
    54  	defer r.RUnlock()
    55  	if x.c == c+1 {
    56  		v := x.val
    57  		return v, &x.c, true
    58  	}
    59  	return r.tDefault, &x.c, false
    60  }
    61  
    62  func (r *ringBuffer[T]) cap() uint64 {
    63  	return r.capMask + 1
    64  }