1 // Copyright (c) 2012 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 #ifndef BASE_PICKLE_H__
6 #define BASE_PICKLE_H__
10 #include "base/base_export.h"
11 #include "base/basictypes.h"
12 #include "base/compiler_specific.h"
13 #include "base/gtest_prod_util.h"
14 #include "base/logging.h"
15 #include "base/string16.h"
19 // PickleIterator reads data from a Pickle. The Pickle object must remain valid
20 // while the PickleIterator object is in use.
21 class BASE_EXPORT PickleIterator
{
23 PickleIterator() : read_ptr_(NULL
), read_end_ptr_(NULL
) {}
24 explicit PickleIterator(const Pickle
& pickle
);
26 // Methods for reading the payload of the Pickle. To read from the start of
27 // the Pickle, create a PickleIterator from a Pickle. If successful, these
28 // methods return true. Otherwise, false is returned to indicate that the
29 // result could not be extracted.
30 bool ReadBool(bool* result
) WARN_UNUSED_RESULT
;
31 bool ReadInt(int* result
) WARN_UNUSED_RESULT
;
32 bool ReadLong(long* result
) WARN_UNUSED_RESULT
;
33 bool ReadUInt16(uint16
* result
) WARN_UNUSED_RESULT
;
34 bool ReadUInt32(uint32
* result
) WARN_UNUSED_RESULT
;
35 bool ReadInt64(int64
* result
) WARN_UNUSED_RESULT
;
36 bool ReadUInt64(uint64
* result
) WARN_UNUSED_RESULT
;
37 bool ReadString(std::string
* result
) WARN_UNUSED_RESULT
;
38 bool ReadWString(std::wstring
* result
) WARN_UNUSED_RESULT
;
39 bool ReadString16(string16
* result
) WARN_UNUSED_RESULT
;
40 bool ReadData(const char** data
, int* length
) WARN_UNUSED_RESULT
;
41 bool ReadBytes(const char** data
, int length
) WARN_UNUSED_RESULT
;
43 // Safer version of ReadInt() checks for the result not being negative.
44 // Use it for reading the object sizes.
45 bool ReadLength(int* result
) WARN_UNUSED_RESULT
{
46 return ReadInt(result
) && *result
>= 0;
49 // Skips bytes in the read buffer and returns true if there are at least
50 // num_bytes available. Otherwise, does nothing and returns false.
51 bool SkipBytes(int num_bytes
) WARN_UNUSED_RESULT
{
52 return !!GetReadPointerAndAdvance(num_bytes
);
56 // Aligns 'i' by rounding it up to the next multiple of 'alignment'
57 static size_t AlignInt(size_t i
, int alignment
) {
58 return i
+ (alignment
- (i
% alignment
)) % alignment
;
61 // Read Type from Pickle.
62 template <typename Type
>
63 inline bool ReadBuiltinType(Type
* result
);
65 // Get read pointer for Type and advance read pointer.
66 template<typename Type
>
67 inline const char* GetReadPointerAndAdvance();
69 // Get read pointer for |num_bytes| and advance read pointer. This method
70 // checks num_bytes for negativity and wrapping.
71 const char* GetReadPointerAndAdvance(int num_bytes
);
73 // Get read pointer for (num_elements * size_element) bytes and advance read
74 // pointer. This method checks for int overflow, negativity and wrapping.
75 inline const char* GetReadPointerAndAdvance(int num_elements
,
78 // Pointers to the Pickle data.
79 const char* read_ptr_
;
80 const char* read_end_ptr_
;
82 FRIEND_TEST_ALL_PREFIXES(PickleTest
, GetReadPointerAndAdvance
);
85 // This class provides facilities for basic binary value packing and unpacking.
87 // The Pickle class supports appending primitive values (ints, strings, etc.)
88 // to a pickle instance. The Pickle instance grows its internal memory buffer
89 // dynamically to hold the sequence of primitive values. The internal memory
90 // buffer is exposed as the "data" of the Pickle. This "data" can be passed
91 // to a Pickle object to initialize it for reading.
93 // When reading from a Pickle object, it is important for the consumer to know
94 // what value types to read and in what order to read them as the Pickle does
95 // not keep track of the type of data written to it.
97 // The Pickle's data has a header which contains the size of the Pickle's
98 // payload. It can optionally support additional space in the header. That
99 // space is controlled by the header_size parameter passed to the Pickle
102 class BASE_EXPORT Pickle
{
104 // Initialize a Pickle object using the default header size.
107 // Initialize a Pickle object with the specified header size in bytes, which
108 // must be greater-than-or-equal-to sizeof(Pickle::Header). The header size
109 // will be rounded up to ensure that the header size is 32bit-aligned.
110 explicit Pickle(int header_size
);
112 // Initializes a Pickle from a const block of data. The data is not copied;
113 // instead the data is merely referenced by this Pickle. Only const methods
114 // should be used on the Pickle when initialized this way. The header
115 // padding size is deduced from the data length.
116 Pickle(const char* data
, int data_len
);
118 // Initializes a Pickle as a deep copy of another Pickle.
119 Pickle(const Pickle
& other
);
121 // Note: There are no virtual methods in this class. This destructor is
122 // virtual as an element of defensive coding. Other classes have derived from
123 // this class, and there is a *chance* that they will cast into this base
124 // class before destruction. At least one such class does have a virtual
125 // destructor, suggesting at least some need to call more derived destructors.
128 // Performs a deep copy.
129 Pickle
& operator=(const Pickle
& other
);
131 // Returns the size of the Pickle's data.
132 size_t size() const { return header_size_
+ header_
->payload_size
; }
134 // Returns the data for this Pickle.
135 const void* data() const { return header_
; }
137 // For compatibility, these older style read methods pass through to the
138 // PickleIterator methods.
139 // TODO(jbates) Remove these methods.
140 bool ReadBool(PickleIterator
* iter
, bool* result
) const {
141 return iter
->ReadBool(result
);
143 bool ReadInt(PickleIterator
* iter
, int* result
) const {
144 return iter
->ReadInt(result
);
146 bool ReadLong(PickleIterator
* iter
, long* result
) const {
147 return iter
->ReadLong(result
);
149 bool ReadUInt16(PickleIterator
* iter
, uint16
* result
) const {
150 return iter
->ReadUInt16(result
);
152 bool ReadUInt32(PickleIterator
* iter
, uint32
* result
) const {
153 return iter
->ReadUInt32(result
);
155 bool ReadInt64(PickleIterator
* iter
, int64
* result
) const {
156 return iter
->ReadInt64(result
);
158 bool ReadUInt64(PickleIterator
* iter
, uint64
* result
) const {
159 return iter
->ReadUInt64(result
);
161 bool ReadString(PickleIterator
* iter
, std::string
* result
) const {
162 return iter
->ReadString(result
);
164 bool ReadWString(PickleIterator
* iter
, std::wstring
* result
) const {
165 return iter
->ReadWString(result
);
167 bool ReadString16(PickleIterator
* iter
, string16
* result
) const {
168 return iter
->ReadString16(result
);
170 // A pointer to the data will be placed in *data, and the length will be
171 // placed in *length. This buffer will be into the message's buffer so will
172 // be scoped to the lifetime of the message (or until the message data is
174 bool ReadData(PickleIterator
* iter
, const char** data
, int* length
) const {
175 return iter
->ReadData(data
, length
);
177 // A pointer to the data will be placed in *data. The caller specifies the
178 // number of bytes to read, and ReadBytes will validate this length. The
179 // returned buffer will be into the message's buffer so will be scoped to the
180 // lifetime of the message (or until the message data is mutated).
181 bool ReadBytes(PickleIterator
* iter
, const char** data
, int length
) const {
182 return iter
->ReadBytes(data
, length
);
185 // Safer version of ReadInt() checks for the result not being negative.
186 // Use it for reading the object sizes.
187 bool ReadLength(PickleIterator
* iter
, int* result
) const {
188 return iter
->ReadLength(result
);
191 // Methods for adding to the payload of the Pickle. These values are
192 // appended to the end of the Pickle's payload. When reading values from a
193 // Pickle, it is important to read them in the order in which they were added
195 bool WriteBool(bool value
) {
196 return WriteInt(value
? 1 : 0);
198 bool WriteInt(int value
) {
199 return WriteBytes(&value
, sizeof(value
));
201 // WARNING: DO NOT USE THIS METHOD IF PICKLES ARE PERSISTED IN ANY WAY.
202 // It will write whatever a "long" is on this architecture. On 32-bit
203 // platforms, it is 32 bits. On 64-bit platforms, it is 64 bits. If persisted
204 // pickles are still around after upgrading to 64-bit, or if they are copied
205 // between dissimilar systems, YOUR PICKLES WILL HAVE GONE BAD.
206 bool WriteLongUsingDangerousNonPortableLessPersistableForm(long value
) {
207 return WriteBytes(&value
, sizeof(value
));
209 bool WriteUInt16(uint16 value
) {
210 return WriteBytes(&value
, sizeof(value
));
212 bool WriteUInt32(uint32 value
) {
213 return WriteBytes(&value
, sizeof(value
));
215 bool WriteInt64(int64 value
) {
216 return WriteBytes(&value
, sizeof(value
));
218 bool WriteUInt64(uint64 value
) {
219 return WriteBytes(&value
, sizeof(value
));
221 bool WriteString(const std::string
& value
);
222 bool WriteWString(const std::wstring
& value
);
223 bool WriteString16(const string16
& value
);
224 // "Data" is a blob with a length. When you read it out you will be given the
225 // length. See also WriteBytes.
226 bool WriteData(const char* data
, int length
);
227 // "Bytes" is a blob with no length. The caller must specify the lenght both
228 // when reading and writing. It is normally used to serialize PoD types of a
229 // known size. See also WriteData.
230 bool WriteBytes(const void* data
, int data_len
);
232 // Same as WriteData, but allows the caller to write directly into the
233 // Pickle. This saves a copy in cases where the data is not already
234 // available in a buffer. The caller should take care to not write more
235 // than the length it declares it will. Use ReadData to get the data.
236 // Returns NULL on failure.
238 // The returned pointer will only be valid until the next write operation
240 char* BeginWriteData(int length
);
242 // For Pickles which contain variable length buffers (e.g. those created
243 // with BeginWriteData), the Pickle can
244 // be 'trimmed' if the amount of data required is less than originally
245 // requested. For example, you may have created a buffer with 10K of data,
246 // but decided to only fill 10 bytes of that data. Use this function
247 // to trim the buffer so that we don't send 9990 bytes of unused data.
248 // You cannot increase the size of the variable buffer; only shrink it.
249 // This function assumes that the length of the variable buffer has
251 void TrimWriteData(int length
);
253 // Payload follows after allocation of Header (header size is customizable).
255 uint32 payload_size
; // Specifies the size of the payload.
258 // Returns the header, cast to a user-specified type T. The type T must be a
259 // subclass of Header and its size must correspond to the header_size passed
260 // to the Pickle constructor.
263 DCHECK_EQ(header_size_
, sizeof(T
));
264 return static_cast<T
*>(header_
);
267 const T
* headerT() const {
268 DCHECK_EQ(header_size_
, sizeof(T
));
269 return static_cast<const T
*>(header_
);
272 // The payload is the pickle data immediately following the header.
273 size_t payload_size() const { return header_
->payload_size
; }
274 const char* payload() const {
275 return reinterpret_cast<const char*>(header_
) + header_size_
;
280 return reinterpret_cast<char*>(header_
) + header_size_
;
283 // Returns the address of the byte immediately following the currently valid
285 char* end_of_payload() {
286 // We must have a valid header_.
287 return payload() + payload_size();
289 const char* end_of_payload() const {
290 // This object may be invalid.
291 return header_
? payload() + payload_size() : NULL
;
294 size_t capacity() const {
298 // Resizes the buffer for use when writing the specified amount of data. The
299 // location that the data should be written at is returned, or NULL if there
300 // was an error. Call EndWrite with the returned offset and the given length
301 // to pad out for the next write.
302 char* BeginWrite(size_t length
);
304 // Completes the write operation by padding the data with NULL bytes until it
305 // is padded. Should be paired with BeginWrite, but it does not necessarily
306 // have to be called after the data is written.
307 void EndWrite(char* dest
, int length
);
309 // Resize the capacity, note that the input value should include the size of
310 // the header: new_capacity = sizeof(Header) + desired_payload_capacity.
311 // A realloc() failure will cause a Resize failure... and caller should check
312 // the return result for true (i.e., successful resizing).
313 bool Resize(size_t new_capacity
);
315 // Aligns 'i' by rounding it up to the next multiple of 'alignment'
316 static size_t AlignInt(size_t i
, int alignment
) {
317 return i
+ (alignment
- (i
% alignment
)) % alignment
;
320 // Find the end of the pickled data that starts at range_start. Returns NULL
321 // if the entire Pickle is not found in the given data range.
322 static const char* FindNext(size_t header_size
,
323 const char* range_start
,
324 const char* range_end
);
326 // The allocation granularity of the payload.
327 static const int kPayloadUnit
;
330 friend class PickleIterator
;
333 size_t header_size_
; // Supports extra data between header and payload.
334 // Allocation size of payload (or -1 if allocation is const).
336 size_t variable_buffer_offset_
; // IF non-zero, then offset to a buffer.
338 FRIEND_TEST_ALL_PREFIXES(PickleTest
, Resize
);
339 FRIEND_TEST_ALL_PREFIXES(PickleTest
, FindNext
);
340 FRIEND_TEST_ALL_PREFIXES(PickleTest
, FindNextWithIncompleteHeader
);
343 #endif // BASE_PICKLE_H__