github.com/zhongdalu/gf@v1.0.0/g/container/gtype/uint.go (about)

     1  // Copyright 2018 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/zhongdalu/gf.
     6  
     7  package gtype
     8  
     9  import (
    10  	"sync/atomic"
    11  )
    12  
    13  type Uint struct {
    14  	value uint64
    15  }
    16  
    17  // NewUint returns a concurrent-safe object for uint type,
    18  // with given initial value <value>.
    19  func NewUint(value ...uint) *Uint {
    20  	if len(value) > 0 {
    21  		return &Uint{
    22  			value: uint64(value[0]),
    23  		}
    24  	}
    25  	return &Uint{}
    26  }
    27  
    28  // Clone clones and returns a new concurrent-safe object for uint type.
    29  func (v *Uint) Clone() *Uint {
    30  	return NewUint(v.Val())
    31  }
    32  
    33  // Set atomically stores <value> into t.value and returns the previous value of t.value.
    34  func (v *Uint) Set(value uint) (old uint) {
    35  	return uint(atomic.SwapUint64(&v.value, uint64(value)))
    36  }
    37  
    38  // Val atomically loads t.value.
    39  func (v *Uint) Val() uint {
    40  	return uint(atomic.LoadUint64(&v.value))
    41  }
    42  
    43  // Add atomically adds <delta> to t.value and returns the new value.
    44  func (v *Uint) Add(delta uint) (new uint) {
    45  	return uint(atomic.AddUint64(&v.value, uint64(delta)))
    46  }
    47  
    48  // Cas executes the compare-and-swap operation for value.
    49  func (v *Uint) Cas(old, new uint) bool {
    50  	return atomic.CompareAndSwapUint64(&v.value, uint64(old), uint64(new))
    51  }