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