github.com/songzhibin97/go-baseutils@v0.0.2-0.20240302024150-487d8ce9c082/structure/maps/skipmap/flag.go (about)

     1  package skipmap
     2  
     3  import "sync/atomic"
     4  
     5  const (
     6  	fullyLinked = 1 << iota
     7  	marked
     8  )
     9  
    10  // concurrent-safe bitflag.
    11  type bitflag struct {
    12  	data uint32
    13  }
    14  
    15  func (f *bitflag) SetTrue(flags uint32) {
    16  	for {
    17  		old := atomic.LoadUint32(&f.data)
    18  		if old&flags == flags {
    19  			return
    20  		}
    21  		// Flag is 0, need set it to 1.
    22  		n := old | flags
    23  		if atomic.CompareAndSwapUint32(&f.data, old, n) {
    24  			return
    25  		}
    26  		continue
    27  	}
    28  }
    29  
    30  func (f *bitflag) SetFalse(flags uint32) {
    31  	for {
    32  		old := atomic.LoadUint32(&f.data)
    33  		check := old & flags
    34  		if check == 0 {
    35  			return
    36  		}
    37  		// Flag is 1, need set it to 0.
    38  		n := old ^ check
    39  		if atomic.CompareAndSwapUint32(&f.data, old, n) {
    40  			return
    41  		}
    42  		continue
    43  	}
    44  }
    45  
    46  func (f *bitflag) Get(flag uint32) bool {
    47  	return (atomic.LoadUint32(&f.data) & flag) != 0
    48  }
    49  
    50  func (f *bitflag) MGet(check, expect uint32) bool {
    51  	return (atomic.LoadUint32(&f.data) & check) == expect
    52  }