blob: 47e3bf6af67cd7dec4eb24083cd5064159854722 [file] [log] [blame]
jbates@chromium.org0fc87362012-03-08 05:42:56 +09001// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botf003cfe2008-08-24 09:55:55 +09002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit3f4a7322008-07-27 06:49:38 +09004
5#ifndef BASE_PICKLE_H__
6#define BASE_PICKLE_H__
thakis@chromium.org01d14522010-07-27 08:08:24 +09007#pragma once
initial.commit3f4a7322008-07-27 06:49:38 +09008
9#include <string>
10
darin@chromium.orge585bed2011-08-06 00:34:00 +090011#include "base/base_export.h"
initial.commit3f4a7322008-07-27 06:49:38 +090012#include "base/basictypes.h"
jbates@chromium.org0fc87362012-03-08 05:42:56 +090013#include "base/compiler_specific.h"
phajdan.jr@chromium.orgdd43b732010-06-01 23:30:51 +090014#include "base/gtest_prod_util.h"
initial.commit3f4a7322008-07-27 06:49:38 +090015#include "base/logging.h"
estade@chromium.org38a18bf2009-03-04 12:36:36 +090016#include "base/string16.h"
initial.commit3f4a7322008-07-27 06:49:38 +090017
jbates@chromium.org0fc87362012-03-08 05:42:56 +090018class 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.commit3f4a7322008-07-27 06:49:38 +090087// 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//
darin@chromium.orge585bed2011-08-06 00:34:00 +0900104class BASE_EXPORT Pickle {
initial.commit3f4a7322008-07-27 06:49:38 +0900105 public:
initial.commit3f4a7322008-07-27 06:49:38 +0900106 // 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
jar@chromium.org4bf312a2011-09-25 12:08:13 +0900123 // 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.
erg@google.comd5fffd42011-01-08 03:06:45 +0900128 virtual ~Pickle();
129
initial.commit3f4a7322008-07-27 06:49:38 +0900130 // Performs a deep copy.
131 Pickle& operator=(const Pickle& other);
132
133 // Returns the size of the Pickle's data.
mrossetti@chromium.org84db36d2011-01-29 04:59:11 +0900134 size_t size() const { return header_size_ + header_->payload_size; }
initial.commit3f4a7322008-07-27 06:49:38 +0900135
136 // Returns the data for this Pickle.
137 const void* data() const { return header_; }
138
jbates@chromium.org0fc87362012-03-08 05:42:56 +0900139 // 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.commit3f4a7322008-07-27 06:49:38 +0900181
182 // Safer version of ReadInt() checks for the result not being negative.
183 // Use it for reading the object sizes.
jbates@chromium.org0fc87362012-03-08 05:42:56 +0900184 bool ReadLength(PickleIterator* iter, int* result) const {
185 return iter->ReadLength(result);
186 }
initial.commit3f4a7322008-07-27 06:49:38 +0900187
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 }
klink@google.comd7f60032008-08-23 08:24:54 +0900198 bool WriteLong(long value) {
199 return WriteBytes(&value, sizeof(value));
200 }
initial.commit3f4a7322008-07-27 06:49:38 +0900201 bool WriteSize(size_t value) {
202 return WriteBytes(&value, sizeof(value));
203 }
bryner@chromium.orgc85d0fd2011-02-23 04:47:19 +0900204 bool WriteUInt16(uint16 value) {
205 return WriteBytes(&value, sizeof(value));
206 }
jeremy@chromium.org62ace902008-12-30 03:55:18 +0900207 bool WriteUInt32(uint32 value) {
208 return WriteBytes(&value, sizeof(value));
209 }
initial.commit3f4a7322008-07-27 06:49:38 +0900210 bool WriteInt64(int64 value) {
211 return WriteBytes(&value, sizeof(value));
212 }
thestig@chromium.orgeb9afb42009-10-28 13:21:01 +0900213 bool WriteUInt64(uint64 value) {
214 return WriteBytes(&value, sizeof(value));
215 }
initial.commit3f4a7322008-07-27 06:49:38 +0900216 bool WriteString(const std::string& value);
217 bool WriteWString(const std::wstring& value);
estade@chromium.org38a18bf2009-03-04 12:36:36 +0900218 bool WriteString16(const string16& value);
initial.commit3f4a7322008-07-27 06:49:38 +0900219 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
maruel@google.com825f8792008-08-07 05:35:17 +0900243 // Payload follows after allocation of Header (header size is customizable).
initial.commit3f4a7322008-07-27 06:49:38 +0900244 struct Header {
maruel@google.com825f8792008-08-07 05:35:17 +0900245 uint32 payload_size; // Specifies the size of the payload.
initial.commit3f4a7322008-07-27 06:49:38 +0900246 };
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() {
mhm@chromium.org73bfc432011-03-01 11:48:05 +0900253 DCHECK_EQ(header_size_, sizeof(T));
initial.commit3f4a7322008-07-27 06:49:38 +0900254 return static_cast<T*>(header_);
255 }
256 template <class T>
257 const T* headerT() const {
mhm@chromium.org73bfc432011-03-01 11:48:05 +0900258 DCHECK_EQ(header_size_, sizeof(T));
initial.commit3f4a7322008-07-27 06:49:38 +0900259 return static_cast<const T*>(header_);
260 }
261
initial.commit3f4a7322008-07-27 06:49:38 +0900262 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() {
rvargas@google.com8d9b2b92010-11-16 04:31:23 +0900275 // We must have a valid header_.
initial.commit3f4a7322008-07-27 06:49:38 +0900276 return payload() + payload_size();
277 }
278 const char* end_of_payload() const {
rvargas@google.com8d9b2b92010-11-16 04:31:23 +0900279 // This object may be invalid.
280 return header_ ? payload() + payload_size() : NULL;
initial.commit3f4a7322008-07-27 06:49:38 +0900281 }
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'
maruel@google.com825f8792008-08-07 05:35:17 +0900305 static size_t AlignInt(size_t i, int alignment) {
initial.commit3f4a7322008-07-27 06:49:38 +0900306 return i + (alignment - (i % alignment)) % alignment;
307 }
308
initial.commit3f4a7322008-07-27 06:49:38 +0900309 // 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:
jbates@chromium.org0fc87362012-03-08 05:42:56 +0900319 friend class PickleIterator;
320
initial.commit3f4a7322008-07-27 06:49:38 +0900321 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
phajdan.jr@chromium.orgdd43b732010-06-01 23:30:51 +0900327 FRIEND_TEST_ALL_PREFIXES(PickleTest, Resize);
328 FRIEND_TEST_ALL_PREFIXES(PickleTest, FindNext);
glider@chromium.org8b725fa2011-01-26 22:02:27 +0900329 FRIEND_TEST_ALL_PREFIXES(PickleTest, FindNextWithIncompleteHeader);
initial.commit3f4a7322008-07-27 06:49:38 +0900330};
331
332#endif // BASE_PICKLE_H__