github.com/network-quality/goresponsiveness@v0.0.0-20240129151524-343954285090/saturating/saturating.go (about)

     1  /*
     2   * This file is part of Go Responsiveness.
     3   *
     4   * Go Responsiveness is free software: you can redistribute it and/or modify it under
     5   * the terms of the GNU General Public License as published by the Free Software Foundation,
     6   * either version 2 of the License, or (at your option) any later version.
     7   * Go Responsiveness is distributed in the hope that it will be useful, but WITHOUT ANY
     8   * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
     9   * PARTICULAR PURPOSE. See the GNU General Public License for more details.
    10   *
    11   * You should have received a copy of the GNU General Public License along
    12   * with Go Responsiveness. If not, see <https://www.gnu.org/licenses/>.
    13   */
    14  
    15  package saturating
    16  
    17  type Saturatable interface {
    18  	~uint | ~uint32 | ~uint64
    19  }
    20  
    21  type Saturating[T Saturatable] struct {
    22  	max       T
    23  	value     T
    24  	saturated bool
    25  }
    26  
    27  func NewSaturating[T Saturatable](max T) *Saturating[T] {
    28  	return &Saturating[T]{max: max, value: 0, saturated: false}
    29  }
    30  
    31  func (s *Saturating[T]) Value() T {
    32  	if s.saturated {
    33  		return s.max
    34  	}
    35  	return s.value
    36  }
    37  
    38  func (s *Saturating[T]) Add(operand T) {
    39  	if !s.saturated {
    40  		s.value += operand
    41  		if s.value >= s.max {
    42  			s.saturated = true
    43  		}
    44  	}
    45  }