github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/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  	"github.com/aacfactory/fns/commons/spinlock"
    22  	"sync"
    23  	"sync/atomic"
    24  	"time"
    25  )
    26  
    27  func NewTimes(win time.Duration) *Times {
    28  	return &Times{
    29  		locker:   new(spinlock.Locker),
    30  		n:        0,
    31  		window:   win,
    32  		deadline: time.Now().Truncate(win),
    33  	}
    34  }
    35  
    36  type Times struct {
    37  	locker   sync.Locker
    38  	n        int64
    39  	window   time.Duration
    40  	deadline time.Time
    41  }
    42  
    43  func (times *Times) Incr() int64 {
    44  	times.locker.Lock()
    45  	defer times.locker.Unlock()
    46  	if times.deadline.Before(time.Now()) {
    47  		times.deadline = time.Now().Truncate(times.window)
    48  		atomic.StoreInt64(&times.n, 1)
    49  		return 1
    50  	}
    51  	return atomic.AddInt64(&times.n, 1)
    52  }
    53  
    54  func (times *Times) Decr() int64 {
    55  	times.locker.Lock()
    56  	defer times.locker.Unlock()
    57  	if times.deadline.Before(time.Now()) {
    58  		times.deadline = time.Now().Truncate(times.window)
    59  		atomic.StoreInt64(&times.n, 0)
    60  		return 0
    61  	}
    62  	return atomic.AddInt64(&times.n, -1)
    63  }
    64  
    65  func (times *Times) Value() int64 {
    66  	return atomic.LoadInt64(&times.n)
    67  }