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