#ifndef TOKENBUCKET_H_INCLUDED_
#define TOKENBUCKET_H_INCLUDED_

#include <inttypes.h>

// An implementation of a token bucket with precise corrections for rounding
// errors

//lint -esym(1712,TokenBucket)

class TokenBucket {
public:
	typedef uint64_t tokencount_t;
	typedef uint64_t timeunit_t;
private:
	const tokencount_t rate;
	const timeunit_t time_unit;
	const tokencount_t limit;
	timeunit_t last_update;
	tokencount_t tokens;
	//for rounding error correction:
	const tokencount_t d;
	const timeunit_t yerr;
	timeunit_t error;
public:
	TokenBucket(tokencount_t rate_, timeunit_t time_unit_, tokencount_t limit_) throw()
	  : rate(rate_), time_unit(time_unit_), limit(limit_),
	    last_update(0), tokens(0),
	    d(rate/time_unit), yerr(rate%time_unit),
	    error(0)
	  {}
	
	tokencount_t capacity() const throw()   { return limit; }
	tokencount_t tokensLeft() const throw() { return tokens; }
	bool         empty() const throw()      { return tokens==0; }
	void         clear() throw();
	
	bool operator==(const TokenBucket &tb) const throw();
	bool operator!=(const TokenBucket &tb) const throw();

	void         update(timeunit_t current_time) throw();
	timeunit_t   lastUpdate() const { return last_update; }

	bool         canGet(tokencount_t max_tokens) const throw()               { return max_tokens<=tokens; }
	bool         canGet(timeunit_t current_time, tokencount_t max_tokens) throw();
	tokencount_t getTokens(tokencount_t max_tokens) throw();
	tokencount_t getTokens(timeunit_t current_time, tokencount_t max_tokens) throw();
	void         putTokens(tokencount_t tokens) throw();
	void         setTokens(tokencount_t tokens) throw();
	timeunit_t   whenAvail(tokencount_t desired_tokens) const throw();
	timeunit_t   whenAvail(timeunit_t current_time, tokencount_t desired_tokens) throw();

	void swap(TokenBucket &tb) throw();
	
	static const timeunit_t never;
};

#endif /*TOKENBUCKET_H_INCLUDED_*/
