Class: R4r::BoundedTokenBucket

Inherits:
TokenBucket show all
Defined in:
lib/r4r/token_bucket.rb

Overview

A token bucket that doesn’t exceed a given bound.

This is threadsafe, and does not require further synchronization. The token bucket starts empty.

Instance Method Summary collapse

Constructor Details

#initialize(limit:) ⇒ BoundedTokenBucket

Creates a new R4r::BoundedTokenBucket.

Parameters:

  • limit (Fixnum)

    the upper bound on the number of tokens in the bucket.

Raises:

  • (ArgumentError)

    if limit isn’t positive



43
44
45
46
47
48
# File 'lib/r4r/token_bucket.rb', line 43

def initialize(limit:)
  raise ArgumentError, "limit must be positive, got #{limit}" if limit.to_i <= 0

  @limit = limit.to_i
  @counter = 0
end

Instance Method Details

#countObject

See Also:



78
79
80
# File 'lib/r4r/token_bucket.rb', line 78

def count
  @counter
end

#put(n) ⇒ Object

Put ‘n` tokens into the bucket.

If putting in ‘n` tokens would overflow `limit` tokens, instead sets the number of tokens to be `limit`.

Raises:

  • (ArgumentError)

    is n isn’t positive



56
57
58
59
60
61
# File 'lib/r4r/token_bucket.rb', line 56

def put(n)
  n = n.to_i
  raise ArgumentError, "number of tokens must be positive" if n <= 0

  @counter = [@counter + n, @limit].min
end

#try_get(n) ⇒ Object

Raises:

  • (ArgumentError)

See Also:



64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/r4r/token_bucket.rb', line 64

def try_get(n)
  n = n.to_i
  raise ArgumentError, "number of tokens must be positive" if n <= 0

  ok = @counter >= n

  if ok
    @counter -= n
  end

  ok
end