github.com/insolar/vanilla@v0.0.0-20201023172447-248fdf805322/atomickit/int64.go (about)

     1  // Copyright 2020 Insolar Network Ltd.
     2  // All rights reserved.
     3  // This material is licensed under the Insolar License version 1.0,
     4  // available at https://github.com/insolar/assured-ledger/blob/master/LICENSE.md.
     5  
     6  package atomickit
     7  
     8  import (
     9  	"strconv"
    10  	"sync/atomic"
    11  )
    12  
    13  func NewInt64(v int64) Int64 {
    14  	return Int64{v}
    15  }
    16  
    17  type Int64 struct {
    18  	v int64
    19  }
    20  
    21  func (p *Int64) Load() int64 {
    22  	return atomic.LoadInt64(&p.v)
    23  }
    24  
    25  func (p *Int64) Store(v int64) {
    26  	atomic.StoreInt64(&p.v, v)
    27  }
    28  
    29  func (p *Int64) Swap(v int64) int64 {
    30  	return atomic.SwapInt64(&p.v, v)
    31  }
    32  
    33  func (p *Int64) CompareAndSwap(old, new int64) bool {
    34  	return atomic.CompareAndSwapInt64(&p.v, old, new)
    35  }
    36  
    37  func (p *Int64) Add(v int64) int64 {
    38  	return atomic.AddInt64(&p.v, v)
    39  }
    40  
    41  func (p *Int64) Sub(v int64) int64 {
    42  	return p.Add(-v)
    43  }
    44  
    45  func (p *Int64) String() string {
    46  	return strconv.FormatInt(p.Load(), 10)
    47  }
    48  
    49  func (p *Int64) SetLesser(v int64) int64 {
    50  	for {
    51  		switch x := p.Load(); {
    52  		case x <= v:
    53  			return x
    54  		case p.CompareAndSwap(x, v):
    55  			return v
    56  		}
    57  	}
    58  }
    59  
    60  func (p *Int64) SetGreater(v int64) int64 {
    61  	for {
    62  		switch x := p.Load(); {
    63  		case x >= v:
    64  			return x
    65  		case p.CompareAndSwap(x, v):
    66  			return v
    67  		}
    68  	}
    69  }