Roll src/third_party/WebKit d9c6159:8139f33 (svn 201974:201975)
[chromium-blink-merge.git] / base / pickle.h
blobb6ec116ebf68361fd4b3ab9e2f9110508e291bc2
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_
8 #include <string>
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"
16 #include "base/strings/string_piece.h"
18 namespace base {
20 class Pickle;
22 // PickleIterator reads data from a Pickle. The Pickle object must remain valid
23 // while the PickleIterator object is in use.
24 class BASE_EXPORT PickleIterator {
25 public:
26 PickleIterator() : payload_(NULL), read_index_(0), end_index_(0) {}
27 explicit PickleIterator(const Pickle& pickle);
29 // Methods for reading the payload of the Pickle. To read from the start of
30 // the Pickle, create a PickleIterator from a Pickle. If successful, these
31 // methods return true. Otherwise, false is returned to indicate that the
32 // result could not be extracted. It is not possible to read from the iterator
33 // after that.
34 bool ReadBool(bool* result) WARN_UNUSED_RESULT;
35 bool ReadInt(int* result) WARN_UNUSED_RESULT;
36 bool ReadLong(long* result) WARN_UNUSED_RESULT;
37 bool ReadUInt16(uint16* result) WARN_UNUSED_RESULT;
38 bool ReadUInt32(uint32* result) WARN_UNUSED_RESULT;
39 bool ReadInt64(int64* result) WARN_UNUSED_RESULT;
40 bool ReadUInt64(uint64* result) WARN_UNUSED_RESULT;
41 bool ReadSizeT(size_t* result) WARN_UNUSED_RESULT;
42 bool ReadFloat(float* result) WARN_UNUSED_RESULT;
43 bool ReadDouble(double* result) WARN_UNUSED_RESULT;
44 bool ReadString(std::string* result) WARN_UNUSED_RESULT;
45 // The StringPiece data will only be valid for the lifetime of the message.
46 bool ReadStringPiece(StringPiece* result) WARN_UNUSED_RESULT;
47 bool ReadString16(string16* result) WARN_UNUSED_RESULT;
48 // The StringPiece16 data will only be valid for the lifetime of the message.
49 bool ReadStringPiece16(StringPiece16* result) WARN_UNUSED_RESULT;
51 // A pointer to the data will be placed in |*data|, and the length will be
52 // placed in |*length|. The pointer placed into |*data| points into the
53 // message's buffer so it will be scoped to the lifetime of the message (or
54 // until the message data is mutated). Do not keep the pointer around!
55 bool ReadData(const char** data, int* length) WARN_UNUSED_RESULT;
57 // A pointer to the data will be placed in |*data|. The caller specifies the
58 // number of bytes to read, and ReadBytes will validate this length. The
59 // pointer placed into |*data| points into the message's buffer so it will be
60 // scoped to the lifetime of the message (or until the message data is
61 // mutated). Do not keep the pointer around!
62 bool ReadBytes(const char** data, int length) WARN_UNUSED_RESULT;
64 // A safer version of ReadInt() that checks for the result not being negative.
65 // Use it for reading the object sizes.
66 bool ReadLength(int* result) WARN_UNUSED_RESULT {
67 return ReadInt(result) && *result >= 0;
70 // Skips bytes in the read buffer and returns true if there are at least
71 // num_bytes available. Otherwise, does nothing and returns false.
72 bool SkipBytes(int num_bytes) WARN_UNUSED_RESULT {
73 return !!GetReadPointerAndAdvance(num_bytes);
76 private:
77 // Read Type from Pickle.
78 template <typename Type>
79 bool ReadBuiltinType(Type* result);
81 // Advance read_index_ but do not allow it to exceed end_index_.
82 // Keeps read_index_ aligned.
83 void Advance(size_t size);
85 // Get read pointer for Type and advance read pointer.
86 template<typename Type>
87 const char* GetReadPointerAndAdvance();
89 // Get read pointer for |num_bytes| and advance read pointer. This method
90 // checks num_bytes for negativity and wrapping.
91 const char* GetReadPointerAndAdvance(int num_bytes);
93 // Get read pointer for (num_elements * size_element) bytes and advance read
94 // pointer. This method checks for int overflow, negativity and wrapping.
95 const char* GetReadPointerAndAdvance(int num_elements,
96 size_t size_element);
98 const char* payload_; // Start of our pickle's payload.
99 size_t read_index_; // Offset of the next readable byte in payload.
100 size_t end_index_; // Payload size.
102 FRIEND_TEST_ALL_PREFIXES(PickleTest, GetReadPointerAndAdvance);
105 // This class provides facilities for basic binary value packing and unpacking.
107 // The Pickle class supports appending primitive values (ints, strings, etc.)
108 // to a pickle instance. The Pickle instance grows its internal memory buffer
109 // dynamically to hold the sequence of primitive values. The internal memory
110 // buffer is exposed as the "data" of the Pickle. This "data" can be passed
111 // to a Pickle object to initialize it for reading.
113 // When reading from a Pickle object, it is important for the consumer to know
114 // what value types to read and in what order to read them as the Pickle does
115 // not keep track of the type of data written to it.
117 // The Pickle's data has a header which contains the size of the Pickle's
118 // payload. It can optionally support additional space in the header. That
119 // space is controlled by the header_size parameter passed to the Pickle
120 // constructor.
122 class BASE_EXPORT Pickle {
123 public:
124 // Initialize a Pickle object using the default header size.
125 Pickle();
127 // Initialize a Pickle object with the specified header size in bytes, which
128 // must be greater-than-or-equal-to sizeof(Pickle::Header). The header size
129 // will be rounded up to ensure that the header size is 32bit-aligned.
130 explicit Pickle(int header_size);
132 // Initializes a Pickle from a const block of data. The data is not copied;
133 // instead the data is merely referenced by this Pickle. Only const methods
134 // should be used on the Pickle when initialized this way. The header
135 // padding size is deduced from the data length.
136 Pickle(const char* data, int data_len);
138 // Initializes a Pickle as a deep copy of another Pickle.
139 Pickle(const Pickle& other);
141 // Note: There are no virtual methods in this class. This destructor is
142 // virtual as an element of defensive coding. Other classes have derived from
143 // this class, and there is a *chance* that they will cast into this base
144 // class before destruction. At least one such class does have a virtual
145 // destructor, suggesting at least some need to call more derived destructors.
146 virtual ~Pickle();
148 // Performs a deep copy.
149 Pickle& operator=(const Pickle& other);
151 // Returns the number of bytes written in the Pickle, including the header.
152 size_t size() const { return header_size_ + header_->payload_size; }
154 // Returns the data for this Pickle.
155 const void* data() const { return header_; }
157 // Returns the effective memory capacity of this Pickle, that is, the total
158 // number of bytes currently dynamically allocated or 0 in the case of a
159 // read-only Pickle. This should be used only for diagnostic / profiling
160 // purposes.
161 size_t GetTotalAllocatedSize() const;
163 // Methods for adding to the payload of the Pickle. These values are
164 // appended to the end of the Pickle's payload. When reading values from a
165 // Pickle, it is important to read them in the order in which they were added
166 // to the Pickle.
168 bool WriteBool(bool value) {
169 return WriteInt(value ? 1 : 0);
171 bool WriteInt(int value) {
172 return WritePOD(value);
174 // WARNING: DO NOT USE THIS METHOD IF PICKLES ARE PERSISTED IN ANY WAY.
175 // It will write whatever a "long" is on this architecture. On 32-bit
176 // platforms, it is 32 bits. On 64-bit platforms, it is 64 bits. If persisted
177 // pickles are still around after upgrading to 64-bit, or if they are copied
178 // between dissimilar systems, YOUR PICKLES WILL HAVE GONE BAD.
179 bool WriteLongUsingDangerousNonPortableLessPersistableForm(long value) {
180 return WritePOD(value);
182 bool WriteUInt16(uint16 value) {
183 return WritePOD(value);
185 bool WriteUInt32(uint32 value) {
186 return WritePOD(value);
188 bool WriteInt64(int64 value) {
189 return WritePOD(value);
191 bool WriteUInt64(uint64 value) {
192 return WritePOD(value);
194 bool WriteSizeT(size_t value) {
195 // Always write size_t as a 64-bit value to ensure compatibility between
196 // 32-bit and 64-bit processes.
197 return WritePOD(static_cast<uint64>(value));
199 bool WriteFloat(float value) {
200 return WritePOD(value);
202 bool WriteDouble(double value) {
203 return WritePOD(value);
205 bool WriteString(const StringPiece& value);
206 bool WriteString16(const StringPiece16& value);
207 // "Data" is a blob with a length. When you read it out you will be given the
208 // length. See also WriteBytes.
209 bool WriteData(const char* data, int length);
210 // "Bytes" is a blob with no length. The caller must specify the length both
211 // when reading and writing. It is normally used to serialize PoD types of a
212 // known size. See also WriteData.
213 bool WriteBytes(const void* data, int length);
215 // Reserves space for upcoming writes when multiple writes will be made and
216 // their sizes are computed in advance. It can be significantly faster to call
217 // Reserve() before calling WriteFoo() multiple times.
218 void Reserve(size_t additional_capacity);
220 // Payload follows after allocation of Header (header size is customizable).
221 struct Header {
222 uint32 payload_size; // Specifies the size of the payload.
225 // Returns the header, cast to a user-specified type T. The type T must be a
226 // subclass of Header and its size must correspond to the header_size passed
227 // to the Pickle constructor.
228 template <class T>
229 T* headerT() {
230 DCHECK_EQ(header_size_, sizeof(T));
231 return static_cast<T*>(header_);
233 template <class T>
234 const T* headerT() const {
235 DCHECK_EQ(header_size_, sizeof(T));
236 return static_cast<const T*>(header_);
239 // The payload is the pickle data immediately following the header.
240 size_t payload_size() const {
241 return header_ ? header_->payload_size : 0;
244 const char* payload() const {
245 return reinterpret_cast<const char*>(header_) + header_size_;
248 // Returns the address of the byte immediately following the currently valid
249 // header + payload.
250 const char* end_of_payload() const {
251 // This object may be invalid.
252 return header_ ? payload() + payload_size() : NULL;
255 protected:
256 char* mutable_payload() {
257 return reinterpret_cast<char*>(header_) + header_size_;
260 size_t capacity_after_header() const {
261 return capacity_after_header_;
264 // Resize the capacity, note that the input value should not include the size
265 // of the header.
266 void Resize(size_t new_capacity);
268 // Find the end of the pickled data that starts at range_start. Returns NULL
269 // if the entire Pickle is not found in the given data range.
270 static const char* FindNext(size_t header_size,
271 const char* range_start,
272 const char* range_end);
274 // The allocation granularity of the payload.
275 static const int kPayloadUnit;
277 private:
278 friend class PickleIterator;
280 Header* header_;
281 size_t header_size_; // Supports extra data between header and payload.
282 // Allocation size of payload (or -1 if allocation is const). Note: this
283 // doesn't count the header.
284 size_t capacity_after_header_;
285 // The offset at which we will write the next field. Note: this doesn't count
286 // the header.
287 size_t write_offset_;
289 // Just like WriteBytes, but with a compile-time size, for performance.
290 template<size_t length> void BASE_EXPORT WriteBytesStatic(const void* data);
292 // Writes a POD by copying its bytes.
293 template <typename T> bool WritePOD(const T& data) {
294 WriteBytesStatic<sizeof(data)>(&data);
295 return true;
297 inline void WriteBytesCommon(const void* data, size_t length);
299 FRIEND_TEST_ALL_PREFIXES(PickleTest, DeepCopyResize);
300 FRIEND_TEST_ALL_PREFIXES(PickleTest, Resize);
301 FRIEND_TEST_ALL_PREFIXES(PickleTest, FindNext);
302 FRIEND_TEST_ALL_PREFIXES(PickleTest, FindNextWithIncompleteHeader);
303 FRIEND_TEST_ALL_PREFIXES(PickleTest, FindNextOverflow);
306 } // namespace base
308 #endif // BASE_PICKLE_H_