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() {
50 // We haven't allocated the buffer, so remove it before the base class
51 // destructor tries to delete[] it.
55 DrainableIOBuffer::DrainableIOBuffer(IOBuffer* base, int size)
56 : IOBuffer(base->data()),
62 void DrainableIOBuffer::DidConsume(int bytes) {
63 SetOffset(used_ + bytes);
66 int DrainableIOBuffer::BytesRemaining() const {
70 // Returns the number of consumed bytes.
71 int DrainableIOBuffer::BytesConsumed() const {
75 void DrainableIOBuffer::SetOffset(int bytes) {
77 DCHECK_LE(bytes, size_);
79 data_ = base_->data() + used_;
82 DrainableIOBuffer::~DrainableIOBuffer() {
83 // The buffer is owned by the |base_| instance.
87 GrowableIOBuffer::GrowableIOBuffer()
93 void GrowableIOBuffer::SetCapacity(int capacity) {
94 DCHECK_GE(capacity, 0);
95 // realloc will crash if it fails.
96 real_data_.reset(static_cast<char*>(realloc(real_data_.release(), capacity)));
98 if (offset_ > capacity)
101 set_offset(offset_); // The pointer may have changed.
104 void GrowableIOBuffer::set_offset(int offset) {
105 DCHECK_GE(offset, 0);
106 DCHECK_LE(offset, capacity_);
108 data_ = real_data_.get() + offset;
111 int GrowableIOBuffer::RemainingCapacity() {
112 return capacity_ - offset_;
115 char* GrowableIOBuffer::StartOfBuffer() {
116 return real_data_.get();
119 GrowableIOBuffer::~GrowableIOBuffer() {
123 PickledIOBuffer::PickledIOBuffer() : IOBuffer() {}
125 void PickledIOBuffer::Done() {
126 data_ = const_cast<char*>(static_cast<const char*>(pickle_.data()));
129 PickledIOBuffer::~PickledIOBuffer() { data_ = NULL; }
131 WrappedIOBuffer::WrappedIOBuffer(const char* data)
132 : IOBuffer(const_cast<char*>(data)) {
135 WrappedIOBuffer::~WrappedIOBuffer() {