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