gauge.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package metrics
  2. import "sync/atomic"
  3. // Gauges hold an int64 value that can be set arbitrarily.
  4. //
  5. // This is an interface so as to encourage other structs to implement
  6. // the Gauge API as appropriate.
  7. type Gauge interface {
  8. Update(int64)
  9. Value() int64
  10. }
  11. // Create a new Gauge.
  12. func NewGauge() Gauge {
  13. if !ObserverEffect {
  14. return NilGauge{}
  15. }
  16. return &StandardGauge{0}
  17. }
  18. // No-op Gauge.
  19. type NilGauge struct{}
  20. // Force the compiler to check that NilGauge implements Gauge.
  21. var _ Gauge = NilGauge{}
  22. // No-op.
  23. func (g NilGauge) Update(v int64) {}
  24. // No-op.
  25. func (g NilGauge) Value() int64 { return 0 }
  26. // The standard implementation of a Gauge uses the sync/atomic package
  27. // to manage a single int64 value.
  28. type StandardGauge struct {
  29. value int64
  30. }
  31. // Force the compiler to check that StandardGauge implements Gauge.
  32. var _ Gauge = &StandardGauge{}
  33. // Update the gauge's value.
  34. func (g *StandardGauge) Update(v int64) {
  35. atomic.StoreInt64(&g.value, v)
  36. }
  37. // Return the gauge's current value.
  38. func (g *StandardGauge) Value() int64 {
  39. return atomic.LoadInt64(&g.value)
  40. }