| 1 | // Copyright 2017 fatedier, fatedier@gmail.com |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package metric |
| 16 | |
| 17 | import ( |
| 18 | "sync/atomic" |
| 19 | ) |
| 20 | |
| 21 | type Counter interface { |
| 22 | Count() int32 |
| 23 | Inc(int32) |
| 24 | Dec(int32) |
| 25 | Snapshot() Counter |
| 26 | Clear() |
| 27 | } |
| 28 | |
| 29 | func NewCounter() Counter { |
| 30 | return &StandardCounter{ |
| 31 | count: 0, |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | type StandardCounter struct { |
| 36 | count int32 |
| 37 | } |
| 38 | |
| 39 | func (c *StandardCounter) Count() int32 { |
| 40 | return atomic.LoadInt32(&c.count) |
| 41 | } |
| 42 | |
| 43 | func (c *StandardCounter) Inc(count int32) { |
| 44 | atomic.AddInt32(&c.count, count) |
| 45 | } |
| 46 | |
| 47 | func (c *StandardCounter) Dec(count int32) { |
| 48 | atomic.AddInt32(&c.count, -count) |
| 49 | } |
| 50 | |
| 51 | func (c *StandardCounter) Snapshot() Counter { |
| 52 | tmp := &StandardCounter{ |
| 53 | count: atomic.LoadInt32(&c.count), |
| 54 | } |
| 55 | return tmp |
| 56 | } |
| 57 | |
| 58 | func (c *StandardCounter) Clear() { |
| 59 | atomic.StoreInt32(&c.count, 0) |
| 60 | } |