1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "net/quic/congestion_control/leaky_bucket.h" 6 7 #include "base/time/time.h" 8 9 namespace net { 10 11 LeakyBucket::LeakyBucket(QuicBandwidth draining_rate) 12 : bytes_(0), 13 time_last_updated_(QuicTime::Zero()), 14 draining_rate_(draining_rate) { 15 } 16 17 void LeakyBucket::SetDrainingRate(QuicTime now, QuicBandwidth draining_rate) { 18 Update(now); 19 draining_rate_ = draining_rate; 20 } 21 22 void LeakyBucket::Add(QuicTime now, QuicByteCount bytes) { 23 Update(now); 24 bytes_ += bytes; 25 } 26 27 QuicTime::Delta LeakyBucket::TimeRemaining(QuicTime now) const { 28 QuicTime::Delta time_since_last_update = now.Subtract(time_last_updated_); 29 QuicTime::Delta send_delay = QuicTime::Delta::FromMicroseconds( 30 (bytes_ * base::Time::kMicrosecondsPerSecond) / 31 draining_rate_.ToBytesPerSecond()); 32 if (send_delay < time_since_last_update) { 33 return QuicTime::Delta::Zero(); 34 } 35 return send_delay.Subtract(time_since_last_update); 36 } 37 38 QuicByteCount LeakyBucket::BytesPending(QuicTime now) { 39 Update(now); 40 return bytes_; 41 } 42 43 void LeakyBucket::Update(QuicTime now) { 44 QuicTime::Delta elapsed_time = now.Subtract(time_last_updated_); 45 QuicByteCount bytes_cleared = draining_rate_.ToBytesPerPeriod(elapsed_time); 46 if (bytes_cleared >= bytes_) { 47 bytes_ = 0; 48 } else { 49 bytes_ -= bytes_cleared; 50 } 51 time_last_updated_ = now; 52 } 53 54 } // namespace net 55