upload_bytes_element_reader.cc 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. #include "net/base/upload_bytes_element_reader.h"
  5. #include "base/check_op.h"
  6. #include "net/base/io_buffer.h"
  7. #include "net/base/net_errors.h"
  8. namespace net {
  9. UploadBytesElementReader::UploadBytesElementReader(const char* bytes,
  10. uint64_t length)
  11. : bytes_(bytes), length_(length) {}
  12. UploadBytesElementReader::~UploadBytesElementReader() = default;
  13. const UploadBytesElementReader*
  14. UploadBytesElementReader::AsBytesReader() const {
  15. return this;
  16. }
  17. int UploadBytesElementReader::Init(CompletionOnceCallback callback) {
  18. offset_ = 0;
  19. return OK;
  20. }
  21. uint64_t UploadBytesElementReader::GetContentLength() const {
  22. return length_;
  23. }
  24. uint64_t UploadBytesElementReader::BytesRemaining() const {
  25. return length_ - offset_;
  26. }
  27. bool UploadBytesElementReader::IsInMemory() const {
  28. return true;
  29. }
  30. int UploadBytesElementReader::Read(IOBuffer* buf,
  31. int buf_length,
  32. CompletionOnceCallback callback) {
  33. DCHECK_LT(0, buf_length);
  34. const int num_bytes_to_read = static_cast<int>(
  35. std::min(BytesRemaining(), static_cast<uint64_t>(buf_length)));
  36. // Check if we have anything to copy first, because we are getting
  37. // the address of an element in |bytes_| and that will throw an
  38. // exception if |bytes_| is an empty vector.
  39. if (num_bytes_to_read > 0)
  40. memcpy(buf->data(), bytes_ + offset_, num_bytes_to_read);
  41. offset_ += num_bytes_to_read;
  42. return num_bytes_to_read;
  43. }
  44. UploadOwnedBytesElementReader::UploadOwnedBytesElementReader(
  45. std::vector<char>* data)
  46. : UploadBytesElementReader(data->data(), data->size()) {
  47. data_.swap(*data);
  48. }
  49. UploadOwnedBytesElementReader::~UploadOwnedBytesElementReader() = default;
  50. std::unique_ptr<UploadOwnedBytesElementReader>
  51. UploadOwnedBytesElementReader::CreateWithString(const std::string& string) {
  52. std::vector<char> data(string.begin(), string.end());
  53. return std::make_unique<UploadOwnedBytesElementReader>(&data);
  54. }
  55. } // namespace net