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