github.com/insolar/vanilla@v0.0.0-20201023172447-248fdf805322/ratelimiter/bucket_config.go (about)

     1  // Copyright 2020 Insolar Network Ltd.
     2  // All rights reserved.
     3  // This material is licensed under the Insolar License version 1.0,
     4  // available at https://github.com/insolar/assured-ledger/blob/master/LICENSE.md.
     5  
     6  package ratelimiter
     7  
     8  import (
     9  	"math"
    10  
    11  	"github.com/insolar/vanilla/throw"
    12  )
    13  
    14  type BucketConfig struct {
    15  	RefillAmount uint32
    16  	Quantum      uint32
    17  	MaxAmount    uint32
    18  }
    19  
    20  func (v BucketConfig) IsZero() bool {
    21  	return v.Quantum == 0
    22  }
    23  
    24  func (v BucketConfig) Check() {
    25  	switch {
    26  	case v.Quantum == 0:
    27  		panic(throw.IllegalValue())
    28  	case v.MaxAmount < v.Quantum:
    29  		panic(throw.IllegalValue())
    30  	case v.MaxAmount < v.RefillAmount:
    31  		panic(throw.IllegalValue())
    32  	}
    33  }
    34  
    35  func scaleUint32(v uint32, scale float32) uint32 {
    36  	switch {
    37  	case v == 0:
    38  		return 0
    39  	case scale <= 0:
    40  		return 0
    41  	default:
    42  		f := float32(v) * scale
    43  		if f > math.MaxUint32 {
    44  			return math.MaxUint32
    45  		}
    46  		v = uint32(f)
    47  		if v > 0 {
    48  			return v
    49  		}
    50  		return 1
    51  	}
    52  }
    53  
    54  func (v BucketConfig) Scale(refillRatio, maxRatio float32) BucketConfig {
    55  	v.RefillAmount = scaleUint32(v.RefillAmount, refillRatio)
    56  	v.MaxAmount = scaleUint32(v.MaxAmount, maxRatio)
    57  	return v
    58  }