golang.org/x/net@v0.25.1-0.20240516223405-c87a5b62e243/quic/atomic_bits.go (about)

     1  // Copyright 2023 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:build go1.21
     6  
     7  package quic
     8  
     9  import "sync/atomic"
    10  
    11  // atomicBits is an atomic uint32 that supports setting individual bits.
    12  type atomicBits[T ~uint32] struct {
    13  	bits atomic.Uint32
    14  }
    15  
    16  // set sets the bits in mask to the corresponding bits in v.
    17  // It returns the new value.
    18  func (a *atomicBits[T]) set(v, mask T) T {
    19  	if v&^mask != 0 {
    20  		panic("BUG: bits in v are not in mask")
    21  	}
    22  	for {
    23  		o := a.bits.Load()
    24  		n := (o &^ uint32(mask)) | uint32(v)
    25  		if a.bits.CompareAndSwap(o, n) {
    26  			return T(n)
    27  		}
    28  	}
    29  }
    30  
    31  func (a *atomicBits[T]) load() T {
    32  	return T(a.bits.Load())
    33  }