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.
5 #include "net/base/io_buffer.h"
7 #include "base/logging.h"
15 IOBuffer::IOBuffer(int buffer_size) {
16 CHECK_GE(buffer_size, 0);
17 data_ = new char[buffer_size];
20 IOBuffer::IOBuffer(char* data)
24 IOBuffer::~IOBuffer() {
29 IOBufferWithSize::IOBufferWithSize(int size)
34 IOBufferWithSize::IOBufferWithSize(char* data, int size)
39 IOBufferWithSize::~IOBufferWithSize() {
42 StringIOBuffer::StringIOBuffer(const std::string& s)
43 : IOBuffer(static_cast<char*>(NULL)),
45 CHECK_LT(s.size(), static_cast<size_t>(INT_MAX));
46 data_ = const_cast<char*>(string_data_.data());
49 StringIOBuffer::StringIOBuffer(scoped_ptr<std::string> s)
50 : IOBuffer(static_cast<char*>(NULL)) {
51 CHECK_LT(s->size(), static_cast<size_t>(INT_MAX));
52 string_data_.swap(*s.get());
53 data_ = const_cast<char*>(string_data_.data());
56 StringIOBuffer::~StringIOBuffer() {
57 // We haven't allocated the buffer, so remove it before the base class
58 // destructor tries to delete[] it.
62 DrainableIOBuffer::DrainableIOBuffer(IOBuffer* base, int size)
63 : IOBuffer(base->data()),
69 void DrainableIOBuffer::DidConsume(int bytes) {
70 SetOffset(used_ + bytes);
73 int DrainableIOBuffer::BytesRemaining() const {
77 // Returns the number of consumed bytes.
78 int DrainableIOBuffer::BytesConsumed() const {
82 void DrainableIOBuffer::SetOffset(int bytes) {
84 DCHECK_LE(bytes, size_);
86 data_ = base_->data() + used_;
89 DrainableIOBuffer::~DrainableIOBuffer() {
90 // The buffer is owned by the |base_| instance.
94 GrowableIOBuffer::GrowableIOBuffer()
100 void GrowableIOBuffer::SetCapacity(int capacity) {
101 DCHECK_GE(capacity, 0);
102 // realloc will crash if it fails.
103 real_data_.reset(static_cast<char*>(realloc(real_data_.release(), capacity)));
104 capacity_ = capacity;
105 if (offset_ > capacity)
106 set_offset(capacity);
108 set_offset(offset_); // The pointer may have changed.
111 void GrowableIOBuffer::set_offset(int offset) {
112 DCHECK_GE(offset, 0);
113 DCHECK_LE(offset, capacity_);
115 data_ = real_data_.get() + offset;
118 int GrowableIOBuffer::RemainingCapacity() {
119 return capacity_ - offset_;
122 char* GrowableIOBuffer::StartOfBuffer() {
123 return real_data_.get();
126 GrowableIOBuffer::~GrowableIOBuffer() {
130 PickledIOBuffer::PickledIOBuffer() : IOBuffer() {}
132 void PickledIOBuffer::Done() {
133 data_ = const_cast<char*>(static_cast<const char*>(pickle_.data()));
136 PickledIOBuffer::~PickledIOBuffer() { data_ = NULL; }
138 WrappedIOBuffer::WrappedIOBuffer(const char* data)
139 : IOBuffer(const_cast<char*>(data)) {
142 WrappedIOBuffer::~WrappedIOBuffer() {