/src/mozilla-central/media/mtransport/simpletokenbucket.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ |
2 | | /* vim: set ts=2 et sw=2 tw=80: */ |
3 | | /* This Source Code Form is subject to the terms of the Mozilla Public |
4 | | * License, v. 2.0. If a copy of the MPL was not distributed with this file, |
5 | | * You can obtain one at http://mozilla.org/MPL/2.0/. */ |
6 | | |
7 | | /* Original author: bcampen@mozilla.com */ |
8 | | |
9 | | #include "simpletokenbucket.h" |
10 | | |
11 | | #include <stdint.h> |
12 | | |
13 | | #include "prinrval.h" |
14 | | |
15 | | namespace mozilla { |
16 | | |
17 | | SimpleTokenBucket::SimpleTokenBucket(size_t bucket_size, |
18 | | size_t tokens_per_second) : |
19 | | max_tokens_(bucket_size), |
20 | | num_tokens_(bucket_size), |
21 | | tokens_per_second_(tokens_per_second), |
22 | 0 | last_time_tokens_added_(PR_IntervalNow()) { |
23 | 0 | } |
24 | | |
25 | 0 | size_t SimpleTokenBucket::getTokens(size_t num_requested_tokens) { |
26 | 0 | // Only fill if there isn't enough to satisfy the request. |
27 | 0 | // If we get tokens so seldomly that we are able to roll the timer all |
28 | 0 | // the way around its range, then we lose that entire range of time |
29 | 0 | // for token accumulation. Probably not the end of the world. |
30 | 0 | if (num_requested_tokens > num_tokens_) { |
31 | 0 | PRIntervalTime now = PR_IntervalNow(); |
32 | 0 |
|
33 | 0 | // If we roll over the max, since everything in this calculation is the same |
34 | 0 | // unsigned type, this will still yield the elapsed time (unless we've |
35 | 0 | // wrapped more than once). |
36 | 0 | PRIntervalTime elapsed_ticks = now - last_time_tokens_added_; |
37 | 0 |
|
38 | 0 | uint32_t elapsed_milli_sec = PR_IntervalToMilliseconds(elapsed_ticks); |
39 | 0 | size_t tokens_to_add = (elapsed_milli_sec * tokens_per_second_)/1000; |
40 | 0 |
|
41 | 0 | // Only update our timestamp if we added some tokens |
42 | 0 | // TODO:(bcampen@mozilla.com) Should we attempt to "save" leftover time? |
43 | 0 | if (tokens_to_add) { |
44 | 0 | num_tokens_ += tokens_to_add; |
45 | 0 | if (num_tokens_ > max_tokens_) { |
46 | 0 | num_tokens_ = max_tokens_; |
47 | 0 | } |
48 | 0 |
|
49 | 0 | last_time_tokens_added_ = now; |
50 | 0 | } |
51 | 0 |
|
52 | 0 | if (num_requested_tokens > num_tokens_) { |
53 | 0 | return num_tokens_; |
54 | 0 | } |
55 | 0 | } |
56 | 0 | |
57 | 0 | num_tokens_ -= num_requested_tokens; |
58 | 0 | return num_requested_tokens; |
59 | 0 | } |
60 | | |
61 | | } // namespace mozilla |
62 | | |