github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/rcrowley/go-metrics/gauge.go (about)

     1  package metrics
     2  
     3  import "sync/atomic"
     4  
     5  // Gauges hold an int64 value that can be set arbitrarily.
     6  type Gauge interface {
     7  	Snapshot() Gauge
     8  	Update(int64)
     9  	Value() int64
    10  }
    11  
    12  // GetOrRegisterGauge returns an existing Gauge or constructs and registers a
    13  // new StandardGauge.
    14  func GetOrRegisterGauge(name string, r Registry) Gauge {
    15  	if nil == r {
    16  		r = DefaultRegistry
    17  	}
    18  	return r.GetOrRegister(name, NewGauge).(Gauge)
    19  }
    20  
    21  // NewGauge constructs a new StandardGauge.
    22  func NewGauge() Gauge {
    23  	if UseNilMetrics {
    24  		return NilGauge{}
    25  	}
    26  	return &StandardGauge{0}
    27  }
    28  
    29  // NewRegisteredGauge constructs and registers a new StandardGauge.
    30  func NewRegisteredGauge(name string, r Registry) Gauge {
    31  	c := NewGauge()
    32  	if nil == r {
    33  		r = DefaultRegistry
    34  	}
    35  	r.Register(name, c)
    36  	return c
    37  }
    38  
    39  // GaugeSnapshot is a read-only copy of another Gauge.
    40  type GaugeSnapshot int64
    41  
    42  // Snapshot returns the snapshot.
    43  func (g GaugeSnapshot) Snapshot() Gauge { return g }
    44  
    45  // Update panics.
    46  func (GaugeSnapshot) Update(int64) {
    47  	panic("Update called on a GaugeSnapshot")
    48  }
    49  
    50  // Value returns the value at the time the snapshot was taken.
    51  func (g GaugeSnapshot) Value() int64 { return int64(g) }
    52  
    53  // NilGauge is a no-op Gauge.
    54  type NilGauge struct{}
    55  
    56  // Snapshot is a no-op.
    57  func (NilGauge) Snapshot() Gauge { return NilGauge{} }
    58  
    59  // Update is a no-op.
    60  func (NilGauge) Update(v int64) {}
    61  
    62  // Value is a no-op.
    63  func (NilGauge) Value() int64 { return 0 }
    64  
    65  // StandardGauge is the standard implementation of a Gauge and uses the
    66  // sync/atomic package to manage a single int64 value.
    67  type StandardGauge struct {
    68  	value int64
    69  }
    70  
    71  // Snapshot returns a read-only copy of the gauge.
    72  func (g *StandardGauge) Snapshot() Gauge {
    73  	return GaugeSnapshot(g.Value())
    74  }
    75  
    76  // Update updates the gauge's value.
    77  func (g *StandardGauge) Update(v int64) {
    78  	atomic.StoreInt64(&g.value, v)
    79  }
    80  
    81  // Value returns the gauge's current value.
    82  func (g *StandardGauge) Value() int64 {
    83  	return atomic.LoadInt64(&g.value)
    84  }