1 // Copyright 2013 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 MOJO_PUBLIC_CPP_BINDINGS_LIB_BINDINGS_SERIALIZATION_H_
6 #define MOJO_PUBLIC_CPP_BINDINGS_LIB_BINDINGS_SERIALIZATION_H_
10 #include "mojo/public/cpp/system/core.h"
17 // Please note that this is a different value than |mojo::kInvalidHandleValue|,
18 // which is the "decoded" invalid handle.
19 const MojoHandle kEncodedInvalidHandleValue
= static_cast<MojoHandle
>(-1);
21 size_t Align(size_t size
);
22 char* AlignPointer(char* ptr
);
24 bool IsAligned(const void* ptr
);
26 // Pointers are encoded as relative offsets. The offsets are relative to the
27 // address of where the offset value is stored, such that the pointer may be
28 // recovered with the expression:
30 // ptr = reinterpret_cast<char*>(offset) + *offset
32 // A null pointer is encoded as an offset value of 0.
34 void EncodePointer(const void* ptr
, uint64_t* offset
);
35 // Note: This function doesn't validate the encoded pointer value.
36 const void* DecodePointerRaw(const uint64_t* offset
);
38 // Note: This function doesn't validate the encoded pointer value.
40 inline void DecodePointer(const uint64_t* offset
, T
** ptr
) {
41 *ptr
= reinterpret_cast<T
*>(const_cast<void*>(DecodePointerRaw(offset
)));
44 // Checks whether decoding the pointer will overflow and produce a pointer
45 // smaller than |offset|.
46 bool ValidateEncodedPointer(const uint64_t* offset
);
48 // Handles are encoded as indices into a vector of handles. These functions
49 // manipulate the value of |handle|, mapping it to and from an index.
50 void EncodeHandle(Handle
* handle
, std::vector
<Handle
>* handles
);
51 // Note: This function doesn't validate the encoded handle value.
52 void DecodeHandle(Handle
* handle
, std::vector
<Handle
>* handles
);
54 // The following 2 functions are used to encode/decode all objects (structs and
55 // arrays) in a consistent manner.
58 inline void Encode(T
* obj
, std::vector
<Handle
>* handles
) {
60 obj
->ptr
->EncodePointersAndHandles(handles
);
61 EncodePointer(obj
->ptr
, &obj
->offset
);
64 // Note: This function doesn't validate the encoded pointer and handle values.
66 inline void Decode(T
* obj
, std::vector
<Handle
>* handles
) {
67 DecodePointer(&obj
->offset
, &obj
->ptr
);
69 obj
->ptr
->DecodePointersAndHandles(handles
);
72 // If returns true, this function also claims the memory range of the size
73 // specified in the struct header, starting from |data|.
74 // Note: |min_num_bytes| must be no less than sizeof(StructHeader).
75 bool ValidateStructHeader(const void* data
,
76 uint32_t min_num_bytes
,
77 uint32_t min_num_fields
,
78 BoundsChecker
* bounds_checker
);
80 } // namespace internal
83 #endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_BINDINGS_SERIALIZATION_H_