blob: fdfdb2be265f6b129cff27a39fdead137892a676 [file] [log] [blame]
license.botbf09a502008-08-24 00:55:551// Copyright (c) 2006-2008 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.
initial.commitd7cae122008-07-26 21:49:384
5#ifndef BASE_PICKLE_H__
6#define BASE_PICKLE_H__
7
8#include <string>
9
10#include "base/basictypes.h"
[email protected]a918f872010-06-01 14:30:5111#include "base/gtest_prod_util.h"
initial.commitd7cae122008-07-26 21:49:3812#include "base/logging.h"
[email protected]3a2a5d22009-03-04 03:36:3613#include "base/string16.h"
initial.commitd7cae122008-07-26 21:49:3814
15// This class provides facilities for basic binary value packing and unpacking.
16//
17// The Pickle class supports appending primitive values (ints, strings, etc.)
18// to a pickle instance. The Pickle instance grows its internal memory buffer
19// dynamically to hold the sequence of primitive values. The internal memory
20// buffer is exposed as the "data" of the Pickle. This "data" can be passed
21// to a Pickle object to initialize it for reading.
22//
23// When reading from a Pickle object, it is important for the consumer to know
24// what value types to read and in what order to read them as the Pickle does
25// not keep track of the type of data written to it.
26//
27// The Pickle's data has a header which contains the size of the Pickle's
28// payload. It can optionally support additional space in the header. That
29// space is controlled by the header_size parameter passed to the Pickle
30// constructor.
31//
32class Pickle {
33 public:
[email protected]b944f612009-08-07 23:13:3534 virtual ~Pickle();
initial.commitd7cae122008-07-26 21:49:3835
36 // Initialize a Pickle object using the default header size.
37 Pickle();
38
39 // Initialize a Pickle object with the specified header size in bytes, which
40 // must be greater-than-or-equal-to sizeof(Pickle::Header). The header size
41 // will be rounded up to ensure that the header size is 32bit-aligned.
42 explicit Pickle(int header_size);
43
44 // Initializes a Pickle from a const block of data. The data is not copied;
45 // instead the data is merely referenced by this Pickle. Only const methods
46 // should be used on the Pickle when initialized this way. The header
47 // padding size is deduced from the data length.
48 Pickle(const char* data, int data_len);
49
50 // Initializes a Pickle as a deep copy of another Pickle.
51 Pickle(const Pickle& other);
52
53 // Performs a deep copy.
54 Pickle& operator=(const Pickle& other);
55
56 // Returns the size of the Pickle's data.
57 int size() const { return static_cast<int>(header_size_ +
58 header_->payload_size); }
59
60 // Returns the data for this Pickle.
61 const void* data() const { return header_; }
62
63 // Methods for reading the payload of the Pickle. To read from the start of
64 // the Pickle, initialize *iter to NULL. If successful, these methods return
65 // true. Otherwise, false is returned to indicate that the result could not
66 // be extracted.
67 bool ReadBool(void** iter, bool* result) const;
68 bool ReadInt(void** iter, int* result) const;
[email protected]43beaef42008-08-22 23:24:5469 bool ReadLong(void** iter, long* result) const;
initial.commitd7cae122008-07-26 21:49:3870 bool ReadSize(void** iter, size_t* result) const;
[email protected]48ce6162008-12-29 18:55:1871 bool ReadUInt32(void** iter, uint32* result) const;
initial.commitd7cae122008-07-26 21:49:3872 bool ReadInt64(void** iter, int64* result) const;
[email protected]b7a5d992009-10-28 04:21:0173 bool ReadUInt64(void** iter, uint64* result) const;
initial.commitd7cae122008-07-26 21:49:3874 bool ReadString(void** iter, std::string* result) const;
75 bool ReadWString(void** iter, std::wstring* result) const;
[email protected]3a2a5d22009-03-04 03:36:3676 bool ReadString16(void** iter, string16* result) const;
initial.commitd7cae122008-07-26 21:49:3877 bool ReadData(void** iter, const char** data, int* length) const;
78 bool ReadBytes(void** iter, const char** data, int length) const;
79
80 // Safer version of ReadInt() checks for the result not being negative.
81 // Use it for reading the object sizes.
[email protected]75c8f1d2008-08-11 11:00:1382 bool ReadLength(void** iter, int* result) const;
initial.commitd7cae122008-07-26 21:49:3883
84 // Methods for adding to the payload of the Pickle. These values are
85 // appended to the end of the Pickle's payload. When reading values from a
86 // Pickle, it is important to read them in the order in which they were added
87 // to the Pickle.
88 bool WriteBool(bool value) {
89 return WriteInt(value ? 1 : 0);
90 }
91 bool WriteInt(int value) {
92 return WriteBytes(&value, sizeof(value));
93 }
[email protected]43beaef42008-08-22 23:24:5494 bool WriteLong(long value) {
95 return WriteBytes(&value, sizeof(value));
96 }
initial.commitd7cae122008-07-26 21:49:3897 bool WriteSize(size_t value) {
98 return WriteBytes(&value, sizeof(value));
99 }
[email protected]48ce6162008-12-29 18:55:18100 bool WriteUInt32(uint32 value) {
101 return WriteBytes(&value, sizeof(value));
102 }
initial.commitd7cae122008-07-26 21:49:38103 bool WriteInt64(int64 value) {
104 return WriteBytes(&value, sizeof(value));
105 }
[email protected]b7a5d992009-10-28 04:21:01106 bool WriteUInt64(uint64 value) {
107 return WriteBytes(&value, sizeof(value));
108 }
initial.commitd7cae122008-07-26 21:49:38109 bool WriteString(const std::string& value);
110 bool WriteWString(const std::wstring& value);
[email protected]3a2a5d22009-03-04 03:36:36111 bool WriteString16(const string16& value);
initial.commitd7cae122008-07-26 21:49:38112 bool WriteData(const char* data, int length);
113 bool WriteBytes(const void* data, int data_len);
114
115 // Same as WriteData, but allows the caller to write directly into the
116 // Pickle. This saves a copy in cases where the data is not already
117 // available in a buffer. The caller should take care to not write more
118 // than the length it declares it will. Use ReadData to get the data.
119 // Returns NULL on failure.
120 //
121 // The returned pointer will only be valid until the next write operation
122 // on this Pickle.
123 char* BeginWriteData(int length);
124
125 // For Pickles which contain variable length buffers (e.g. those created
126 // with BeginWriteData), the Pickle can
127 // be 'trimmed' if the amount of data required is less than originally
128 // requested. For example, you may have created a buffer with 10K of data,
129 // but decided to only fill 10 bytes of that data. Use this function
130 // to trim the buffer so that we don't send 9990 bytes of unused data.
131 // You cannot increase the size of the variable buffer; only shrink it.
132 // This function assumes that the length of the variable buffer has
133 // not been changed.
134 void TrimWriteData(int length);
135
[email protected]c9046af2008-08-06 20:35:17136 // Payload follows after allocation of Header (header size is customizable).
initial.commitd7cae122008-07-26 21:49:38137 struct Header {
[email protected]c9046af2008-08-06 20:35:17138 uint32 payload_size; // Specifies the size of the payload.
initial.commitd7cae122008-07-26 21:49:38139 };
140
141 // Returns the header, cast to a user-specified type T. The type T must be a
142 // subclass of Header and its size must correspond to the header_size passed
143 // to the Pickle constructor.
144 template <class T>
145 T* headerT() {
146 DCHECK(sizeof(T) == header_size_);
147 return static_cast<T*>(header_);
148 }
149 template <class T>
150 const T* headerT() const {
151 DCHECK(sizeof(T) == header_size_);
152 return static_cast<const T*>(header_);
153 }
154
155 // Returns true if the given iterator could point to data with the given
156 // length. If there is no room for the given data before the end of the
157 // payload, returns false.
158 bool IteratorHasRoomFor(const void* iter, int len) const {
159 if ((len < 0) || (iter < header_) || iter > end_of_payload())
160 return false;
161 const char* end_of_region = reinterpret_cast<const char*>(iter) + len;
162 // Watch out for overflow in pointer calculation, which wraps.
163 return (iter <= end_of_region) && (end_of_region <= end_of_payload());
164 }
165
166 protected:
167 size_t payload_size() const { return header_->payload_size; }
168
169 char* payload() {
170 return reinterpret_cast<char*>(header_) + header_size_;
171 }
172 const char* payload() const {
173 return reinterpret_cast<const char*>(header_) + header_size_;
174 }
175
176 // Returns the address of the byte immediately following the currently valid
177 // header + payload.
178 char* end_of_payload() {
179 return payload() + payload_size();
180 }
181 const char* end_of_payload() const {
182 return payload() + payload_size();
183 }
184
185 size_t capacity() const {
186 return capacity_;
187 }
188
189 // Resizes the buffer for use when writing the specified amount of data. The
190 // location that the data should be written at is returned, or NULL if there
191 // was an error. Call EndWrite with the returned offset and the given length
192 // to pad out for the next write.
193 char* BeginWrite(size_t length);
194
195 // Completes the write operation by padding the data with NULL bytes until it
196 // is padded. Should be paired with BeginWrite, but it does not necessarily
197 // have to be called after the data is written.
198 void EndWrite(char* dest, int length);
199
200 // Resize the capacity, note that the input value should include the size of
201 // the header: new_capacity = sizeof(Header) + desired_payload_capacity.
202 // A realloc() failure will cause a Resize failure... and caller should check
203 // the return result for true (i.e., successful resizing).
204 bool Resize(size_t new_capacity);
205
206 // Aligns 'i' by rounding it up to the next multiple of 'alignment'
[email protected]c9046af2008-08-06 20:35:17207 static size_t AlignInt(size_t i, int alignment) {
initial.commitd7cae122008-07-26 21:49:38208 return i + (alignment - (i % alignment)) % alignment;
209 }
210
211 // Moves the iterator by the given number of bytes, making sure it is aligned.
212 // Pointer (iterator) is NOT aligned, but the change in the pointer
213 // is guaranteed to be a multiple of sizeof(uint32).
[email protected]c9046af2008-08-06 20:35:17214 static void UpdateIter(void** iter, int bytes) {
initial.commitd7cae122008-07-26 21:49:38215 *iter = static_cast<char*>(*iter) + AlignInt(bytes, sizeof(uint32));
216 }
217
218 // Find the end of the pickled data that starts at range_start. Returns NULL
219 // if the entire Pickle is not found in the given data range.
220 static const char* FindNext(size_t header_size,
221 const char* range_start,
222 const char* range_end);
223
224 // The allocation granularity of the payload.
225 static const int kPayloadUnit;
226
227 private:
initial.commitd7cae122008-07-26 21:49:38228 Header* header_;
229 size_t header_size_; // Supports extra data between header and payload.
230 // Allocation size of payload (or -1 if allocation is const).
231 size_t capacity_;
232 size_t variable_buffer_offset_; // IF non-zero, then offset to a buffer.
233
[email protected]a918f872010-06-01 14:30:51234 FRIEND_TEST_ALL_PREFIXES(PickleTest, Resize);
235 FRIEND_TEST_ALL_PREFIXES(PickleTest, FindNext);
236 FRIEND_TEST_ALL_PREFIXES(PickleTest, IteratorHasRoom);
initial.commitd7cae122008-07-26 21:49:38237};
238
239#endif // BASE_PICKLE_H__