test_data_stream.cc 1.7 KB

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