github.com/aacfactory/fns@v1.2.85/commons/window/times.go (about) 1 /* 2 * Copyright 2023 Wang Min Xiang 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 * 16 */ 17 18 package window 19 20 import ( 21 "sync/atomic" 22 "time" 23 ) 24 25 func NewTimes(win time.Duration) *Times { 26 return &Times{ 27 n: 0, 28 window: win, 29 deadline: time.Now().Truncate(win), 30 } 31 } 32 33 type Times struct { 34 n int64 35 window time.Duration 36 deadline time.Time 37 } 38 39 func (times *Times) Incr() int64 { 40 if times.deadline.Before(time.Now()) { 41 times.deadline = time.Now().Truncate(times.window) 42 atomic.StoreInt64(×.n, 1) 43 return 1 44 } 45 return atomic.AddInt64(×.n, 1) 46 } 47 48 func (times *Times) Decr() int64 { 49 if times.deadline.Before(time.Now()) { 50 times.deadline = time.Now().Truncate(times.window) 51 atomic.StoreInt64(×.n, 0) 52 return 0 53 } 54 return atomic.AddInt64(×.n, -1) 55 } 56 57 func (times *Times) Value() int64 { 58 return atomic.LoadInt64(×.n) 59 }