pickle.h revision 21d179b334e59e9a3bfcaed4c4430bef1bc5759d
1// Copyright (c) 2006-2008 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 5#ifndef BASE_PICKLE_H__ 6#define BASE_PICKLE_H__ 7#pragma once 8 9#include <string> 10 11#include "base/basictypes.h" 12#include "base/gtest_prod_util.h" 13#include "base/logging.h" 14#include "base/string16.h" 15 16// This class provides facilities for basic binary value packing and unpacking. 17// 18// The Pickle class supports appending primitive values (ints, strings, etc.) 19// to a pickle instance. The Pickle instance grows its internal memory buffer 20// dynamically to hold the sequence of primitive values. The internal memory 21// buffer is exposed as the "data" of the Pickle. This "data" can be passed 22// to a Pickle object to initialize it for reading. 23// 24// When reading from a Pickle object, it is important for the consumer to know 25// what value types to read and in what order to read them as the Pickle does 26// not keep track of the type of data written to it. 27// 28// The Pickle's data has a header which contains the size of the Pickle's 29// payload. It can optionally support additional space in the header. That 30// space is controlled by the header_size parameter passed to the Pickle 31// constructor. 32// 33class Pickle { 34 public: 35 virtual ~Pickle(); 36 37 // Initialize a Pickle object using the default header size. 38 Pickle(); 39 40 // Initialize a Pickle object with the specified header size in bytes, which 41 // must be greater-than-or-equal-to sizeof(Pickle::Header). The header size 42 // will be rounded up to ensure that the header size is 32bit-aligned. 43 explicit Pickle(int header_size); 44 45 // Initializes a Pickle from a const block of data. The data is not copied; 46 // instead the data is merely referenced by this Pickle. Only const methods 47 // should be used on the Pickle when initialized this way. The header 48 // padding size is deduced from the data length. 49 Pickle(const char* data, int data_len); 50 51 // Initializes a Pickle as a deep copy of another Pickle. 52 Pickle(const Pickle& other); 53 54 // Performs a deep copy. 55 Pickle& operator=(const Pickle& other); 56 57 // Returns the size of the Pickle's data. 58 int size() const { return static_cast<int>(header_size_ + 59 header_->payload_size); } 60 61 // Returns the data for this Pickle. 62 const void* data() const { return header_; } 63 64 // Methods for reading the payload of the Pickle. To read from the start of 65 // the Pickle, initialize *iter to NULL. If successful, these methods return 66 // true. Otherwise, false is returned to indicate that the result could not 67 // be extracted. 68 bool ReadBool(void** iter, bool* result) const; 69 bool ReadInt(void** iter, int* result) const; 70 bool ReadLong(void** iter, long* result) const; 71 bool ReadSize(void** iter, size_t* result) const; 72 bool ReadUInt32(void** iter, uint32* result) const; 73 bool ReadInt64(void** iter, int64* result) const; 74 bool ReadUInt64(void** iter, uint64* result) const; 75 bool ReadString(void** iter, std::string* result) const; 76 bool ReadWString(void** iter, std::wstring* result) const; 77 bool ReadString16(void** iter, string16* result) const; 78 bool ReadData(void** iter, const char** data, int* length) const; 79 bool ReadBytes(void** iter, const char** data, int length) const; 80 81 // Safer version of ReadInt() checks for the result not being negative. 82 // Use it for reading the object sizes. 83 bool ReadLength(void** iter, int* result) const; 84 85 // Methods for adding to the payload of the Pickle. These values are 86 // appended to the end of the Pickle's payload. When reading values from a 87 // Pickle, it is important to read them in the order in which they were added 88 // to the Pickle. 89 bool WriteBool(bool value) { 90 return WriteInt(value ? 1 : 0); 91 } 92 bool WriteInt(int value) { 93 return WriteBytes(&value, sizeof(value)); 94 } 95 bool WriteLong(long value) { 96 return WriteBytes(&value, sizeof(value)); 97 } 98 bool WriteSize(size_t value) { 99 return WriteBytes(&value, sizeof(value)); 100 } 101 bool WriteUInt32(uint32 value) { 102 return WriteBytes(&value, sizeof(value)); 103 } 104 bool WriteInt64(int64 value) { 105 return WriteBytes(&value, sizeof(value)); 106 } 107 bool WriteUInt64(uint64 value) { 108 return WriteBytes(&value, sizeof(value)); 109 } 110 bool WriteString(const std::string& value); 111 bool WriteWString(const std::wstring& value); 112 bool WriteString16(const string16& value); 113 bool WriteData(const char* data, int length); 114 bool WriteBytes(const void* data, int data_len); 115 116 // Same as WriteData, but allows the caller to write directly into the 117 // Pickle. This saves a copy in cases where the data is not already 118 // available in a buffer. The caller should take care to not write more 119 // than the length it declares it will. Use ReadData to get the data. 120 // Returns NULL on failure. 121 // 122 // The returned pointer will only be valid until the next write operation 123 // on this Pickle. 124 char* BeginWriteData(int length); 125 126 // For Pickles which contain variable length buffers (e.g. those created 127 // with BeginWriteData), the Pickle can 128 // be 'trimmed' if the amount of data required is less than originally 129 // requested. For example, you may have created a buffer with 10K of data, 130 // but decided to only fill 10 bytes of that data. Use this function 131 // to trim the buffer so that we don't send 9990 bytes of unused data. 132 // You cannot increase the size of the variable buffer; only shrink it. 133 // This function assumes that the length of the variable buffer has 134 // not been changed. 135 void TrimWriteData(int length); 136 137 // Payload follows after allocation of Header (header size is customizable). 138 struct Header { 139 uint32 payload_size; // Specifies the size of the payload. 140 }; 141 142 // Returns the header, cast to a user-specified type T. The type T must be a 143 // subclass of Header and its size must correspond to the header_size passed 144 // to the Pickle constructor. 145 template <class T> 146 T* headerT() { 147 DCHECK(sizeof(T) == header_size_); 148 return static_cast<T*>(header_); 149 } 150 template <class T> 151 const T* headerT() const { 152 DCHECK(sizeof(T) == header_size_); 153 return static_cast<const T*>(header_); 154 } 155 156 // Returns true if the given iterator could point to data with the given 157 // length. If there is no room for the given data before the end of the 158 // payload, returns false. 159 bool IteratorHasRoomFor(const void* iter, int len) const { 160 if ((len < 0) || (iter < header_) || iter > end_of_payload()) 161 return false; 162 const char* end_of_region = reinterpret_cast<const char*>(iter) + len; 163 // Watch out for overflow in pointer calculation, which wraps. 164 return (iter <= end_of_region) && (end_of_region <= end_of_payload()); 165 } 166 167 protected: 168 size_t payload_size() const { return header_->payload_size; } 169 170 char* payload() { 171 return reinterpret_cast<char*>(header_) + header_size_; 172 } 173 const char* payload() const { 174 return reinterpret_cast<const char*>(header_) + header_size_; 175 } 176 177 // Returns the address of the byte immediately following the currently valid 178 // header + payload. 179 char* end_of_payload() { 180 // We must have a valid header_. 181 return payload() + payload_size(); 182 } 183 const char* end_of_payload() const { 184 // This object may be invalid. 185 return header_ ? payload() + payload_size() : NULL; 186 } 187 188 size_t capacity() const { 189 return capacity_; 190 } 191 192 // Resizes the buffer for use when writing the specified amount of data. The 193 // location that the data should be written at is returned, or NULL if there 194 // was an error. Call EndWrite with the returned offset and the given length 195 // to pad out for the next write. 196 char* BeginWrite(size_t length); 197 198 // Completes the write operation by padding the data with NULL bytes until it 199 // is padded. Should be paired with BeginWrite, but it does not necessarily 200 // have to be called after the data is written. 201 void EndWrite(char* dest, int length); 202 203 // Resize the capacity, note that the input value should include the size of 204 // the header: new_capacity = sizeof(Header) + desired_payload_capacity. 205 // A realloc() failure will cause a Resize failure... and caller should check 206 // the return result for true (i.e., successful resizing). 207 bool Resize(size_t new_capacity); 208 209 // Aligns 'i' by rounding it up to the next multiple of 'alignment' 210 static size_t AlignInt(size_t i, int alignment) { 211 return i + (alignment - (i % alignment)) % alignment; 212 } 213 214 // Moves the iterator by the given number of bytes, making sure it is aligned. 215 // Pointer (iterator) is NOT aligned, but the change in the pointer 216 // is guaranteed to be a multiple of sizeof(uint32). 217 static void UpdateIter(void** iter, int bytes) { 218 *iter = static_cast<char*>(*iter) + AlignInt(bytes, sizeof(uint32)); 219 } 220 221 // Find the end of the pickled data that starts at range_start. Returns NULL 222 // if the entire Pickle is not found in the given data range. 223 static const char* FindNext(size_t header_size, 224 const char* range_start, 225 const char* range_end); 226 227 // The allocation granularity of the payload. 228 static const int kPayloadUnit; 229 230 private: 231 Header* header_; 232 size_t header_size_; // Supports extra data between header and payload. 233 // Allocation size of payload (or -1 if allocation is const). 234 size_t capacity_; 235 size_t variable_buffer_offset_; // IF non-zero, then offset to a buffer. 236 237 FRIEND_TEST_ALL_PREFIXES(PickleTest, Resize); 238 FRIEND_TEST_ALL_PREFIXES(PickleTest, FindNext); 239 FRIEND_TEST_ALL_PREFIXES(PickleTest, IteratorHasRoom); 240}; 241 242#endif // BASE_PICKLE_H__ 243