michael@0: /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ michael@0: /* vim: set ts=2 et sw=2 tw=80: */ michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this file, michael@0: * You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: /* Original author: bcampen@mozilla.com */ michael@0: michael@0: #include "simpletokenbucket.h" michael@0: michael@0: #include michael@0: michael@0: #include "prinrval.h" michael@0: michael@0: namespace mozilla { michael@0: michael@0: SimpleTokenBucket::SimpleTokenBucket(size_t bucket_size, michael@0: size_t tokens_per_second) : michael@0: max_tokens_(bucket_size), michael@0: num_tokens_(bucket_size), michael@0: tokens_per_second_(tokens_per_second), michael@0: last_time_tokens_added_(PR_IntervalNow()) { michael@0: } michael@0: michael@0: size_t SimpleTokenBucket::getTokens(size_t num_requested_tokens) { michael@0: // Only fill if there isn't enough to satisfy the request. michael@0: // If we get tokens so seldomly that we are able to roll the timer all michael@0: // the way around its range, then we lose that entire range of time michael@0: // for token accumulation. Probably not the end of the world. michael@0: if (num_requested_tokens > num_tokens_) { michael@0: PRIntervalTime now = PR_IntervalNow(); michael@0: michael@0: // If we roll over the max, since everything in this calculation is the same michael@0: // unsigned type, this will still yield the elapsed time (unless we've michael@0: // wrapped more than once). michael@0: PRIntervalTime elapsed_ticks = now - last_time_tokens_added_; michael@0: michael@0: uint32_t elapsed_milli_sec = PR_IntervalToMilliseconds(elapsed_ticks); michael@0: size_t tokens_to_add = (elapsed_milli_sec * tokens_per_second_)/1000; michael@0: michael@0: // Only update our timestamp if we added some tokens michael@0: // TODO:(bcampen@mozilla.com) Should we attempt to "save" leftover time? michael@0: if (tokens_to_add) { michael@0: num_tokens_ += tokens_to_add; michael@0: if (num_tokens_ > max_tokens_) { michael@0: num_tokens_ = max_tokens_; michael@0: } michael@0: michael@0: last_time_tokens_added_ = now; michael@0: } michael@0: michael@0: if (num_requested_tokens > num_tokens_) { michael@0: return num_tokens_; michael@0: } michael@0: } michael@0: michael@0: num_tokens_ -= num_requested_tokens; michael@0: return num_requested_tokens; michael@0: } michael@0: michael@0: } // namespace mozilla michael@0: