blob: 47e3bf6af67cd7dec4eb24083cd5064159854722 [file] [log] [blame]
[email protected]ce208f872012-03-07 20:42:561// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commitd7cae122008-07-26 21:49:384
5#ifndef BASE_PICKLE_H__
6#define BASE_PICKLE_H__
[email protected]32b76ef2010-07-26 23:08:247#pragma once
initial.commitd7cae122008-07-26 21:49:388
9#include <string>
10
[email protected]0bea7252011-08-05 15:34:0011#include "base/base_export.h"
initial.commitd7cae122008-07-26 21:49:3812#include "base/basictypes.h"
[email protected]ce208f872012-03-07 20:42:5613#include "base/compiler_specific.h"
[email protected]a918f872010-06-01 14:30:5114#include "base/gtest_prod_util.h"
initial.commitd7cae122008-07-26 21:49:3815#include "base/logging.h"
[email protected]3a2a5d22009-03-04 03:36:3616#include "base/string16.h"
initial.commitd7cae122008-07-26 21:49:3817
[email protected]ce208f872012-03-07 20:42:5618class Pickle;
19
20// PickleIterator reads data from a Pickle. The Pickle object must remain valid
21// while the PickleIterator object is in use.
22class BASE_EXPORT PickleIterator {
23 public:
24 PickleIterator() : read_ptr_(NULL), read_end_ptr_(NULL) {}
25 explicit PickleIterator(const Pickle& pickle);
26
27 // Methods for reading the payload of the Pickle. To read from the start of
28 // the Pickle, create a PickleIterator from a Pickle. If successful, these
29 // methods return true. Otherwise, false is returned to indicate that the
30 // result could not be extracted.
31 bool ReadBool(bool* result) WARN_UNUSED_RESULT;
32 bool ReadInt(int* result) WARN_UNUSED_RESULT;
33 bool ReadLong(long* result) WARN_UNUSED_RESULT;
34 bool ReadSize(size_t* result) WARN_UNUSED_RESULT;
35 bool ReadUInt16(uint16* result) WARN_UNUSED_RESULT;
36 bool ReadUInt32(uint32* result) WARN_UNUSED_RESULT;
37 bool ReadInt64(int64* result) WARN_UNUSED_RESULT;
38 bool ReadUInt64(uint64* result) WARN_UNUSED_RESULT;
39 bool ReadString(std::string* result) WARN_UNUSED_RESULT;
40 bool ReadWString(std::wstring* result) WARN_UNUSED_RESULT;
41 bool ReadString16(string16* result) WARN_UNUSED_RESULT;
42 bool ReadData(const char** data, int* length) WARN_UNUSED_RESULT;
43 bool ReadBytes(const char** data, int length) WARN_UNUSED_RESULT;
44
45 // Safer version of ReadInt() checks for the result not being negative.
46 // Use it for reading the object sizes.
47 bool ReadLength(int* result) WARN_UNUSED_RESULT {
48 return ReadInt(result) && *result >= 0;
49 }
50
51 // Skips bytes in the read buffer and returns true if there are at least
52 // num_bytes available. Otherwise, does nothing and returns false.
53 bool SkipBytes(int num_bytes) WARN_UNUSED_RESULT {
54 return !!GetReadPointerAndAdvance(num_bytes);
55 }
56
57 private:
58 // Aligns 'i' by rounding it up to the next multiple of 'alignment'
59 static size_t AlignInt(size_t i, int alignment) {
60 return i + (alignment - (i % alignment)) % alignment;
61 }
62
63 // Read Type from Pickle.
64 template <typename Type>
65 inline bool ReadBuiltinType(Type* result);
66
67 // Get read pointer for Type and advance read pointer.
68 template<typename Type>
69 inline const char* GetReadPointerAndAdvance();
70
71 // Get read pointer for |num_bytes| and advance read pointer. This method
72 // checks num_bytes for negativity and wrapping.
73 const char* GetReadPointerAndAdvance(int num_bytes);
74
75 // Get read pointer for (num_elements * size_element) bytes and advance read
76 // pointer. This method checks for int overflow, negativity and wrapping.
77 inline const char* GetReadPointerAndAdvance(int num_elements,
78 size_t size_element);
79
80 // Pointers to the Pickle data.
81 const char* read_ptr_;
82 const char* read_end_ptr_;
83
84 FRIEND_TEST_ALL_PREFIXES(PickleTest, GetReadPointerAndAdvance);
85};
86
initial.commitd7cae122008-07-26 21:49:3887// This class provides facilities for basic binary value packing and unpacking.
88//
89// The Pickle class supports appending primitive values (ints, strings, etc.)
90// to a pickle instance. The Pickle instance grows its internal memory buffer
91// dynamically to hold the sequence of primitive values. The internal memory
92// buffer is exposed as the "data" of the Pickle. This "data" can be passed
93// to a Pickle object to initialize it for reading.
94//
95// When reading from a Pickle object, it is important for the consumer to know
96// what value types to read and in what order to read them as the Pickle does
97// not keep track of the type of data written to it.
98//
99// The Pickle's data has a header which contains the size of the Pickle's
100// payload. It can optionally support additional space in the header. That
101// space is controlled by the header_size parameter passed to the Pickle
102// constructor.
103//
[email protected]0bea7252011-08-05 15:34:00104class BASE_EXPORT Pickle {
initial.commitd7cae122008-07-26 21:49:38105 public:
initial.commitd7cae122008-07-26 21:49:38106 // Initialize a Pickle object using the default header size.
107 Pickle();
108
109 // Initialize a Pickle object with the specified header size in bytes, which
110 // must be greater-than-or-equal-to sizeof(Pickle::Header). The header size
111 // will be rounded up to ensure that the header size is 32bit-aligned.
112 explicit Pickle(int header_size);
113
114 // Initializes a Pickle from a const block of data. The data is not copied;
115 // instead the data is merely referenced by this Pickle. Only const methods
116 // should be used on the Pickle when initialized this way. The header
117 // padding size is deduced from the data length.
118 Pickle(const char* data, int data_len);
119
120 // Initializes a Pickle as a deep copy of another Pickle.
121 Pickle(const Pickle& other);
122
[email protected]f60c32b2011-09-25 03:08:13123 // Note: There are no virtual methods in this class. This destructor is
124 // virtual as an element of defensive coding. Other classes have derived from
125 // this class, and there is a *chance* that they will cast into this base
126 // class before destruction. At least one such class does have a virtual
127 // destructor, suggesting at least some need to call more derived destructors.
[email protected]a502bbe72011-01-07 18:06:45128 virtual ~Pickle();
129
initial.commitd7cae122008-07-26 21:49:38130 // Performs a deep copy.
131 Pickle& operator=(const Pickle& other);
132
133 // Returns the size of the Pickle's data.
[email protected]8a861402011-01-28 19:59:11134 size_t size() const { return header_size_ + header_->payload_size; }
initial.commitd7cae122008-07-26 21:49:38135
136 // Returns the data for this Pickle.
137 const void* data() const { return header_; }
138
[email protected]ce208f872012-03-07 20:42:56139 // For compatibility, these older style read methods pass through to the
140 // PickleIterator methods.
141 // TODO(jbates) Remove these methods.
142 bool ReadBool(PickleIterator* iter, bool* result) const {
143 return iter->ReadBool(result);
144 }
145 bool ReadInt(PickleIterator* iter, int* result) const {
146 return iter->ReadInt(result);
147 }
148 bool ReadLong(PickleIterator* iter, long* result) const {
149 return iter->ReadLong(result);
150 }
151 bool ReadSize(PickleIterator* iter, size_t* result) const {
152 return iter->ReadSize(result);
153 }
154 bool ReadUInt16(PickleIterator* iter, uint16* result) const {
155 return iter->ReadUInt16(result);
156 }
157 bool ReadUInt32(PickleIterator* iter, uint32* result) const {
158 return iter->ReadUInt32(result);
159 }
160 bool ReadInt64(PickleIterator* iter, int64* result) const {
161 return iter->ReadInt64(result);
162 }
163 bool ReadUInt64(PickleIterator* iter, uint64* result) const {
164 return iter->ReadUInt64(result);
165 }
166 bool ReadString(PickleIterator* iter, std::string* result) const {
167 return iter->ReadString(result);
168 }
169 bool ReadWString(PickleIterator* iter, std::wstring* result) const {
170 return iter->ReadWString(result);
171 }
172 bool ReadString16(PickleIterator* iter, string16* result) const {
173 return iter->ReadString16(result);
174 }
175 bool ReadData(PickleIterator* iter, const char** data, int* length) const {
176 return iter->ReadData(data, length);
177 }
178 bool ReadBytes(PickleIterator* iter, const char** data, int length) const {
179 return iter->ReadBytes(data, length);
180 }
initial.commitd7cae122008-07-26 21:49:38181
182 // Safer version of ReadInt() checks for the result not being negative.
183 // Use it for reading the object sizes.
[email protected]ce208f872012-03-07 20:42:56184 bool ReadLength(PickleIterator* iter, int* result) const {
185 return iter->ReadLength(result);
186 }
initial.commitd7cae122008-07-26 21:49:38187
188 // Methods for adding to the payload of the Pickle. These values are
189 // appended to the end of the Pickle's payload. When reading values from a
190 // Pickle, it is important to read them in the order in which they were added
191 // to the Pickle.
192 bool WriteBool(bool value) {
193 return WriteInt(value ? 1 : 0);
194 }
195 bool WriteInt(int value) {
196 return WriteBytes(&value, sizeof(value));
197 }
[email protected]43beaef42008-08-22 23:24:54198 bool WriteLong(long value) {
199 return WriteBytes(&value, sizeof(value));
200 }
initial.commitd7cae122008-07-26 21:49:38201 bool WriteSize(size_t value) {
202 return WriteBytes(&value, sizeof(value));
203 }
[email protected]6d81b482011-02-22 19:47:19204 bool WriteUInt16(uint16 value) {
205 return WriteBytes(&value, sizeof(value));
206 }
[email protected]48ce616a2008-12-29 18:55:18207 bool WriteUInt32(uint32 value) {
208 return WriteBytes(&value, sizeof(value));
209 }
initial.commitd7cae122008-07-26 21:49:38210 bool WriteInt64(int64 value) {
211 return WriteBytes(&value, sizeof(value));
212 }
[email protected]b7a5d992009-10-28 04:21:01213 bool WriteUInt64(uint64 value) {
214 return WriteBytes(&value, sizeof(value));
215 }
initial.commitd7cae122008-07-26 21:49:38216 bool WriteString(const std::string& value);
217 bool WriteWString(const std::wstring& value);
[email protected]3a2a5d22009-03-04 03:36:36218 bool WriteString16(const string16& value);
initial.commitd7cae122008-07-26 21:49:38219 bool WriteData(const char* data, int length);
220 bool WriteBytes(const void* data, int data_len);
221
222 // Same as WriteData, but allows the caller to write directly into the
223 // Pickle. This saves a copy in cases where the data is not already
224 // available in a buffer. The caller should take care to not write more
225 // than the length it declares it will. Use ReadData to get the data.
226 // Returns NULL on failure.
227 //
228 // The returned pointer will only be valid until the next write operation
229 // on this Pickle.
230 char* BeginWriteData(int length);
231
232 // For Pickles which contain variable length buffers (e.g. those created
233 // with BeginWriteData), the Pickle can
234 // be 'trimmed' if the amount of data required is less than originally
235 // requested. For example, you may have created a buffer with 10K of data,
236 // but decided to only fill 10 bytes of that data. Use this function
237 // to trim the buffer so that we don't send 9990 bytes of unused data.
238 // You cannot increase the size of the variable buffer; only shrink it.
239 // This function assumes that the length of the variable buffer has
240 // not been changed.
241 void TrimWriteData(int length);
242
[email protected]c9046af2008-08-06 20:35:17243 // Payload follows after allocation of Header (header size is customizable).
initial.commitd7cae122008-07-26 21:49:38244 struct Header {
[email protected]c9046af2008-08-06 20:35:17245 uint32 payload_size; // Specifies the size of the payload.
initial.commitd7cae122008-07-26 21:49:38246 };
247
248 // Returns the header, cast to a user-specified type T. The type T must be a
249 // subclass of Header and its size must correspond to the header_size passed
250 // to the Pickle constructor.
251 template <class T>
252 T* headerT() {
[email protected]5d2b4492011-03-01 02:48:05253 DCHECK_EQ(header_size_, sizeof(T));
initial.commitd7cae122008-07-26 21:49:38254 return static_cast<T*>(header_);
255 }
256 template <class T>
257 const T* headerT() const {
[email protected]5d2b4492011-03-01 02:48:05258 DCHECK_EQ(header_size_, sizeof(T));
initial.commitd7cae122008-07-26 21:49:38259 return static_cast<const T*>(header_);
260 }
261
initial.commitd7cae122008-07-26 21:49:38262 protected:
263 size_t payload_size() const { return header_->payload_size; }
264
265 char* payload() {
266 return reinterpret_cast<char*>(header_) + header_size_;
267 }
268 const char* payload() const {
269 return reinterpret_cast<const char*>(header_) + header_size_;
270 }
271
272 // Returns the address of the byte immediately following the currently valid
273 // header + payload.
274 char* end_of_payload() {
[email protected]d87f8e6f2010-11-15 19:31:23275 // We must have a valid header_.
initial.commitd7cae122008-07-26 21:49:38276 return payload() + payload_size();
277 }
278 const char* end_of_payload() const {
[email protected]d87f8e6f2010-11-15 19:31:23279 // This object may be invalid.
280 return header_ ? payload() + payload_size() : NULL;
initial.commitd7cae122008-07-26 21:49:38281 }
282
283 size_t capacity() const {
284 return capacity_;
285 }
286
287 // Resizes the buffer for use when writing the specified amount of data. The
288 // location that the data should be written at is returned, or NULL if there
289 // was an error. Call EndWrite with the returned offset and the given length
290 // to pad out for the next write.
291 char* BeginWrite(size_t length);
292
293 // Completes the write operation by padding the data with NULL bytes until it
294 // is padded. Should be paired with BeginWrite, but it does not necessarily
295 // have to be called after the data is written.
296 void EndWrite(char* dest, int length);
297
298 // Resize the capacity, note that the input value should include the size of
299 // the header: new_capacity = sizeof(Header) + desired_payload_capacity.
300 // A realloc() failure will cause a Resize failure... and caller should check
301 // the return result for true (i.e., successful resizing).
302 bool Resize(size_t new_capacity);
303
304 // Aligns 'i' by rounding it up to the next multiple of 'alignment'
[email protected]c9046af2008-08-06 20:35:17305 static size_t AlignInt(size_t i, int alignment) {
initial.commitd7cae122008-07-26 21:49:38306 return i + (alignment - (i % alignment)) % alignment;
307 }
308
initial.commitd7cae122008-07-26 21:49:38309 // Find the end of the pickled data that starts at range_start. Returns NULL
310 // if the entire Pickle is not found in the given data range.
311 static const char* FindNext(size_t header_size,
312 const char* range_start,
313 const char* range_end);
314
315 // The allocation granularity of the payload.
316 static const int kPayloadUnit;
317
318 private:
[email protected]ce208f872012-03-07 20:42:56319 friend class PickleIterator;
320
initial.commitd7cae122008-07-26 21:49:38321 Header* header_;
322 size_t header_size_; // Supports extra data between header and payload.
323 // Allocation size of payload (or -1 if allocation is const).
324 size_t capacity_;
325 size_t variable_buffer_offset_; // IF non-zero, then offset to a buffer.
326
[email protected]a918f872010-06-01 14:30:51327 FRIEND_TEST_ALL_PREFIXES(PickleTest, Resize);
328 FRIEND_TEST_ALL_PREFIXES(PickleTest, FindNext);
[email protected]137d2372011-01-26 13:02:27329 FRIEND_TEST_ALL_PREFIXES(PickleTest, FindNextWithIncompleteHeader);
initial.commitd7cae122008-07-26 21:49:38330};
331
332#endif // BASE_PICKLE_H__