Home | History | Annotate | Download | only in base
      1 // Copyright (c) 2011 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/base/test_data_stream.h"
      6 
      7 namespace net {
      8 
      9 TestDataStream::TestDataStream() {
     10   Reset();
     11 }
     12 
     13 // Fill |buffer| with |length| bytes of data from the stream.
     14 void TestDataStream::GetBytes(char* buffer, int length) {
     15   while (length) {
     16     AdvanceIndex();
     17     int bytes_to_copy = std::min(length, bytes_remaining_);
     18     memcpy(buffer, buffer_ptr_, bytes_to_copy);
     19     buffer += bytes_to_copy;
     20     Consume(bytes_to_copy);
     21     length -= bytes_to_copy;
     22   }
     23 }
     24 
     25 bool TestDataStream::VerifyBytes(const char *buffer, int length) {
     26   while (length) {
     27     AdvanceIndex();
     28     int bytes_to_compare = std::min(length, bytes_remaining_);
     29     if (memcmp(buffer, buffer_ptr_, bytes_to_compare))
     30       return false;
     31     Consume(bytes_to_compare);
     32     length -= bytes_to_compare;
     33     buffer += bytes_to_compare;
     34   }
     35   return true;
     36 }
     37 
     38 void TestDataStream::Reset() {
     39   index_ = 0;
     40   bytes_remaining_ = 0;
     41   buffer_ptr_ = buffer_;
     42 }
     43 
     44 // If there is no data spilled over from the previous index, advance the
     45 // index and fill the buffer.
     46 void TestDataStream::AdvanceIndex() {
     47   if (bytes_remaining_ == 0) {
     48     // Convert it to ascii, but don't bother to reverse it.
     49     // (e.g. 12345 becomes "54321")
     50     int val = index_++;
     51     do {
     52       buffer_[bytes_remaining_++] = (val % 10) + '0';
     53     } while ((val /= 10) > 0);
     54     buffer_[bytes_remaining_++] = '.';
     55   }
     56 }
     57 
     58 // Consume data from the spill buffer.
     59 void TestDataStream::Consume(int bytes) {
     60   bytes_remaining_ -= bytes;
     61   if (bytes_remaining_)
     62     buffer_ptr_ += bytes;
     63   else
     64     buffer_ptr_ = buffer_;
     65 }
     66 
     67 }  // namespace net
     68 
     69