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/strings/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() : payload_(NULL
), read_index_(0), end_index_(0) {}
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. It is not possible to read from iterator
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 ReadUInt16(uint16
* result
) WARN_UNUSED_RESULT
;
35 bool ReadUInt32(uint32
* result
) WARN_UNUSED_RESULT
;
36 bool ReadInt64(int64
* result
) WARN_UNUSED_RESULT
;
37 bool ReadUInt64(uint64
* result
) WARN_UNUSED_RESULT
;
38 bool ReadSizeT(size_t* result
) WARN_UNUSED_RESULT
;
39 bool ReadFloat(float* result
) WARN_UNUSED_RESULT
;
40 bool ReadDouble(double* result
) WARN_UNUSED_RESULT
;
41 bool ReadString(std::string
* result
) WARN_UNUSED_RESULT
;
42 bool ReadWString(std::wstring
* result
) WARN_UNUSED_RESULT
;
43 bool ReadString16(base::string16
* result
) WARN_UNUSED_RESULT
;
44 bool ReadData(const char** data
, int* length
) WARN_UNUSED_RESULT
;
45 bool ReadBytes(const char** data
, int length
) WARN_UNUSED_RESULT
;
47 // Safer version of ReadInt() checks for the result not being negative.
48 // Use it for reading the object sizes.
49 bool ReadLength(int* result
) WARN_UNUSED_RESULT
{
50 return ReadInt(result
) && *result
>= 0;
53 // Skips bytes in the read buffer and returns true if there are at least
54 // num_bytes available. Otherwise, does nothing and returns false.
55 bool SkipBytes(int num_bytes
) WARN_UNUSED_RESULT
{
56 return !!GetReadPointerAndAdvance(num_bytes
);
60 // Aligns 'i' by rounding it up to the next multiple of 'alignment'
61 static size_t AlignInt(size_t i
, int alignment
) {
62 return i
+ (alignment
- (i
% alignment
)) % alignment
;
65 // Read Type from Pickle.
66 template <typename Type
>
67 bool ReadBuiltinType(Type
* result
);
69 // Advance read_index_ but do not allow it to exceed end_index_.
70 // Keeps read_index_ aligned.
71 void Advance(size_t size
);
73 // Get read pointer for Type and advance read pointer.
74 template<typename Type
>
75 const char* GetReadPointerAndAdvance();
77 // Get read pointer for |num_bytes| and advance read pointer. This method
78 // checks num_bytes for negativity and wrapping.
79 const char* GetReadPointerAndAdvance(int num_bytes
);
81 // Get read pointer for (num_elements * size_element) bytes and advance read
82 // pointer. This method checks for int overflow, negativity and wrapping.
83 const char* GetReadPointerAndAdvance(int num_elements
,
86 const char* payload_
; // Start of our pickle's payload.
87 size_t read_index_
; // Offset of the next readable byte in payload.
88 size_t end_index_
; // Payload size.
90 FRIEND_TEST_ALL_PREFIXES(PickleTest
, GetReadPointerAndAdvance
);
93 // This class provides facilities for basic binary value packing and unpacking.
95 // The Pickle class supports appending primitive values (ints, strings, etc.)
96 // to a pickle instance. The Pickle instance grows its internal memory buffer
97 // dynamically to hold the sequence of primitive values. The internal memory
98 // buffer is exposed as the "data" of the Pickle. This "data" can be passed
99 // to a Pickle object to initialize it for reading.
101 // When reading from a Pickle object, it is important for the consumer to know
102 // what value types to read and in what order to read them as the Pickle does
103 // not keep track of the type of data written to it.
105 // The Pickle's data has a header which contains the size of the Pickle's
106 // payload. It can optionally support additional space in the header. That
107 // space is controlled by the header_size parameter passed to the Pickle
110 class BASE_EXPORT Pickle
{
112 // Initialize a Pickle object using the default header size.
115 // Initialize a Pickle object with the specified header size in bytes, which
116 // must be greater-than-or-equal-to sizeof(Pickle::Header). The header size
117 // will be rounded up to ensure that the header size is 32bit-aligned.
118 explicit Pickle(int header_size
);
120 // Initializes a Pickle from a const block of data. The data is not copied;
121 // instead the data is merely referenced by this Pickle. Only const methods
122 // should be used on the Pickle when initialized this way. The header
123 // padding size is deduced from the data length.
124 Pickle(const char* data
, int data_len
);
126 // Initializes a Pickle as a deep copy of another Pickle.
127 Pickle(const Pickle
& other
);
129 // Note: There are no virtual methods in this class. This destructor is
130 // virtual as an element of defensive coding. Other classes have derived from
131 // this class, and there is a *chance* that they will cast into this base
132 // class before destruction. At least one such class does have a virtual
133 // destructor, suggesting at least some need to call more derived destructors.
136 // Performs a deep copy.
137 Pickle
& operator=(const Pickle
& other
);
139 // Returns the size of the Pickle's data.
140 size_t size() const { return header_size_
+ header_
->payload_size
; }
142 // Returns the data for this Pickle.
143 const void* data() const { return header_
; }
145 // For compatibility, these older style read methods pass through to the
146 // PickleIterator methods.
147 // TODO(jbates) Remove these methods.
148 bool ReadBool(PickleIterator
* iter
,
149 bool* result
) const WARN_UNUSED_RESULT
{
150 return iter
->ReadBool(result
);
152 bool ReadInt(PickleIterator
* iter
,
153 int* result
) const WARN_UNUSED_RESULT
{
154 return iter
->ReadInt(result
);
156 bool ReadLong(PickleIterator
* iter
,
157 long* result
) const WARN_UNUSED_RESULT
{
158 return iter
->ReadLong(result
);
160 bool ReadUInt16(PickleIterator
* iter
,
161 uint16
* result
) const WARN_UNUSED_RESULT
{
162 return iter
->ReadUInt16(result
);
164 bool ReadUInt32(PickleIterator
* iter
,
165 uint32
* result
) const WARN_UNUSED_RESULT
{
166 return iter
->ReadUInt32(result
);
168 bool ReadInt64(PickleIterator
* iter
,
169 int64
* result
) const WARN_UNUSED_RESULT
{
170 return iter
->ReadInt64(result
);
172 bool ReadUInt64(PickleIterator
* iter
,
173 uint64
* result
) const WARN_UNUSED_RESULT
{
174 return iter
->ReadUInt64(result
);
176 bool ReadSizeT(PickleIterator
* iter
,
177 size_t* result
) const WARN_UNUSED_RESULT
{
178 return iter
->ReadSizeT(result
);
180 bool ReadFloat(PickleIterator
* iter
,
181 float* result
) const WARN_UNUSED_RESULT
{
182 return iter
->ReadFloat(result
);
184 bool ReadDouble(PickleIterator
* iter
,
185 double* result
) const WARN_UNUSED_RESULT
{
186 return iter
->ReadDouble(result
);
188 bool ReadString(PickleIterator
* iter
,
189 std::string
* result
) const WARN_UNUSED_RESULT
{
190 return iter
->ReadString(result
);
192 bool ReadWString(PickleIterator
* iter
,
193 std::wstring
* result
) const WARN_UNUSED_RESULT
{
194 return iter
->ReadWString(result
);
196 bool ReadString16(PickleIterator
* iter
,
197 base::string16
* result
) const WARN_UNUSED_RESULT
{
198 return iter
->ReadString16(result
);
200 // A pointer to the data will be placed in *data, and the length will be
201 // placed in *length. This buffer will be into the message's buffer so will
202 // be scoped to the lifetime of the message (or until the message data is
204 bool ReadData(PickleIterator
* iter
,
206 int* length
) const WARN_UNUSED_RESULT
{
207 return iter
->ReadData(data
, length
);
209 // A pointer to the data will be placed in *data. The caller specifies the
210 // number of bytes to read, and ReadBytes will validate this length. The
211 // returned buffer will be into the message's buffer so will be scoped to the
212 // lifetime of the message (or until the message data is mutated).
213 bool ReadBytes(PickleIterator
* iter
,
215 int length
) const WARN_UNUSED_RESULT
{
216 return iter
->ReadBytes(data
, length
);
219 // Safer version of ReadInt() checks for the result not being negative.
220 // Use it for reading the object sizes.
221 bool ReadLength(PickleIterator
* iter
,
222 int* result
) const WARN_UNUSED_RESULT
{
223 return iter
->ReadLength(result
);
226 // Methods for adding to the payload of the Pickle. These values are
227 // appended to the end of the Pickle's payload. When reading values from a
228 // Pickle, it is important to read them in the order in which they were added
230 bool WriteBool(bool value
) {
231 return WriteInt(value
? 1 : 0);
233 bool WriteInt(int value
) {
234 return WritePOD(value
);
236 // WARNING: DO NOT USE THIS METHOD IF PICKLES ARE PERSISTED IN ANY WAY.
237 // It will write whatever a "long" is on this architecture. On 32-bit
238 // platforms, it is 32 bits. On 64-bit platforms, it is 64 bits. If persisted
239 // pickles are still around after upgrading to 64-bit, or if they are copied
240 // between dissimilar systems, YOUR PICKLES WILL HAVE GONE BAD.
241 bool WriteLongUsingDangerousNonPortableLessPersistableForm(long value
) {
242 return WritePOD(value
);
244 bool WriteUInt16(uint16 value
) {
245 return WritePOD(value
);
247 bool WriteUInt32(uint32 value
) {
248 return WritePOD(value
);
250 bool WriteInt64(int64 value
) {
251 return WritePOD(value
);
253 bool WriteUInt64(uint64 value
) {
254 return WritePOD(value
);
256 bool WriteSizeT(size_t value
) {
257 // Always write size_t as a 64-bit value to ensure compatibility between
258 // 32-bit and 64-bit processes.
259 return WritePOD(static_cast<uint64
>(value
));
261 bool WriteFloat(float value
) {
262 return WritePOD(value
);
264 bool WriteDouble(double value
) {
265 return WritePOD(value
);
267 bool WriteString(const std::string
& value
);
268 bool WriteWString(const std::wstring
& value
);
269 bool WriteString16(const base::string16
& value
);
270 // "Data" is a blob with a length. When you read it out you will be given the
271 // length. See also WriteBytes.
272 bool WriteData(const char* data
, int length
);
273 // "Bytes" is a blob with no length. The caller must specify the length both
274 // when reading and writing. It is normally used to serialize PoD types of a
275 // known size. See also WriteData.
276 bool WriteBytes(const void* data
, int length
);
278 // Reserves space for upcoming writes when multiple writes will be made and
279 // their sizes are computed in advance. It can be significantly faster to call
280 // Reserve() before calling WriteFoo() multiple times.
281 void Reserve(size_t additional_capacity
);
283 // Payload follows after allocation of Header (header size is customizable).
285 uint32 payload_size
; // Specifies the size of the payload.
288 // Returns the header, cast to a user-specified type T. The type T must be a
289 // subclass of Header and its size must correspond to the header_size passed
290 // to the Pickle constructor.
293 DCHECK_EQ(header_size_
, sizeof(T
));
294 return static_cast<T
*>(header_
);
297 const T
* headerT() const {
298 DCHECK_EQ(header_size_
, sizeof(T
));
299 return static_cast<const T
*>(header_
);
302 // The payload is the pickle data immediately following the header.
303 size_t payload_size() const {
304 return header_
? header_
->payload_size
: 0;
307 const char* payload() const {
308 return reinterpret_cast<const char*>(header_
) + header_size_
;
311 // Returns the address of the byte immediately following the currently valid
313 const char* end_of_payload() const {
314 // This object may be invalid.
315 return header_
? payload() + payload_size() : NULL
;
319 char* mutable_payload() {
320 return reinterpret_cast<char*>(header_
) + header_size_
;
323 size_t capacity_after_header() const {
324 return capacity_after_header_
;
327 // Resize the capacity, note that the input value should not include the size
329 void Resize(size_t new_capacity
);
331 // Aligns 'i' by rounding it up to the next multiple of 'alignment'
332 static size_t AlignInt(size_t i
, int alignment
) {
333 return i
+ (alignment
- (i
% alignment
)) % alignment
;
336 // Find the end of the pickled data that starts at range_start. Returns NULL
337 // if the entire Pickle is not found in the given data range.
338 static const char* FindNext(size_t header_size
,
339 const char* range_start
,
340 const char* range_end
);
342 // The allocation granularity of the payload.
343 static const int kPayloadUnit
;
346 friend class PickleIterator
;
349 size_t header_size_
; // Supports extra data between header and payload.
350 // Allocation size of payload (or -1 if allocation is const). Note: this
351 // doesn't count the header.
352 size_t capacity_after_header_
;
353 // The offset at which we will write the next field. Note: this doesn't count
355 size_t write_offset_
;
357 // Just like WriteBytes, but with a compile-time size, for performance.
358 template<size_t length
> void BASE_EXPORT
WriteBytesStatic(const void* data
);
360 // Writes a POD by copying its bytes.
361 template <typename T
> bool WritePOD(const T
& data
) {
362 WriteBytesStatic
<sizeof(data
)>(&data
);
365 inline void WriteBytesCommon(const void* data
, size_t length
);
367 FRIEND_TEST_ALL_PREFIXES(PickleTest
, Resize
);
368 FRIEND_TEST_ALL_PREFIXES(PickleTest
, FindNext
);
369 FRIEND_TEST_ALL_PREFIXES(PickleTest
, FindNextWithIncompleteHeader
);
370 FRIEND_TEST_ALL_PREFIXES(PickleTest
, FindNextOverflow
);
373 #endif // BASE_PICKLE_H__