bindings_serialization.h revision cedac228d2dd51db4b79ea1e72c7f249408ee061
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.
4
5#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_BINDINGS_SERIALIZATION_H_
6#define MOJO_PUBLIC_CPP_BINDINGS_LIB_BINDINGS_SERIALIZATION_H_
7
8#include <vector>
9
10#include "mojo/public/cpp/bindings/message.h"
11
12namespace mojo {
13namespace internal {
14
15size_t Align(size_t size);
16char* AlignPointer(char* ptr);
17
18// Pointers are encoded as relative offsets. The offsets are relative to the
19// address of where the offset value is stored, such that the pointer may be
20// recovered with the expression:
21//
22//   ptr = reinterpret_cast<char*>(offset) + *offset
23//
24// A null pointer is encoded as an offset value of 0.
25//
26void EncodePointer(const void* ptr, uint64_t* offset);
27const void* DecodePointerRaw(const uint64_t* offset);
28
29template <typename T>
30inline void DecodePointer(const uint64_t* offset, T** ptr) {
31  *ptr = reinterpret_cast<T*>(const_cast<void*>(DecodePointerRaw(offset)));
32}
33
34// Check that the given pointer references memory contained within the message.
35bool ValidatePointer(const void* ptr, const Message& message);
36
37// Handles are encoded as indices into a vector of handles. These functions
38// manipulate the value of |handle|, mapping it to and from an index.
39void EncodeHandle(Handle* handle, std::vector<Handle>* handles);
40bool DecodeHandle(Handle* handle, std::vector<Handle>* handles);
41
42// The following 2 functions are used to encode/decode all objects (structs and
43// arrays) in a consistent manner.
44
45template <typename T>
46inline void Encode(T* obj, std::vector<Handle>* handles) {
47  if (obj->ptr)
48    obj->ptr->EncodePointersAndHandles(handles);
49  EncodePointer(obj->ptr, &obj->offset);
50}
51
52template <typename T>
53inline bool Decode(T* obj, Message* message) {
54  DecodePointer(&obj->offset, &obj->ptr);
55  if (obj->ptr) {
56    if (!ValidatePointer(obj->ptr, *message))
57      return false;
58    if (!obj->ptr->DecodePointersAndHandles(message))
59      return false;
60  }
61  return true;
62}
63
64}  // namespace internal
65}  // namespace mojo
66
67#endif  // MOJO_PUBLIC_CPP_BINDINGS_LIB_BINDINGS_SERIALIZATION_H_
68