- add sources.
[platform/framework/web/crosswalk.git] / src / mojo / public / bindings / lib / bindings_serialization.cc
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 #include "mojo/public/bindings/lib/bindings_serialization.h"
6
7 #include <assert.h>
8
9 namespace mojo {
10 namespace internal {
11
12 size_t Align(size_t size) {
13   const size_t kAlignment = 8;
14   return size + (kAlignment - (size % kAlignment)) % kAlignment;
15 }
16
17 void EncodePointer(const void* ptr, uint64_t* offset) {
18   if (!ptr) {
19     *offset = 0;
20     return;
21   }
22
23   const char* p_obj = reinterpret_cast<const char*>(ptr);
24   const char* p_slot = reinterpret_cast<const char*>(offset);
25   assert(p_obj > p_slot);
26
27   *offset = static_cast<uint64_t>(p_obj - p_slot);
28 }
29
30 const void* DecodePointerRaw(const uint64_t* offset) {
31   if (!*offset)
32     return NULL;
33   return reinterpret_cast<const char*>(offset) + *offset;
34 }
35
36 bool ValidatePointer(const void* ptr, const Message& message) {
37   const uint8_t* data = static_cast<const uint8_t*>(ptr);
38   if (reinterpret_cast<ptrdiff_t>(data) % 8 != 0)
39     return false;
40
41   const uint8_t* data_start = reinterpret_cast<const uint8_t*>(message.data);
42   const uint8_t* data_end = data_start + message.data->header.num_bytes;
43
44   return data >= data_start && data < data_end;
45 }
46
47 void EncodeHandle(Handle* handle, std::vector<Handle>* handles) {
48   handles->push_back(*handle);
49   handle->value = static_cast<MojoHandle>(handles->size() - 1);
50 }
51
52 bool DecodeHandle(Handle* handle, const std::vector<Handle>& handles) {
53   if (handle->value >= handles.size())
54     return false;
55   *handle = handles[handle->value];
56   return true;
57 }
58
59 // static
60 void ArrayHelper<Handle>::EncodePointersAndHandles(
61     const ArrayHeader* header,
62     ElementType* elements,
63     std::vector<Handle>* handles) {
64   for (uint32_t i = 0; i < header->num_elements; ++i)
65     EncodeHandle(&elements[i], handles);
66 }
67
68 // static
69 bool ArrayHelper<Handle>::DecodePointersAndHandles(
70     const ArrayHeader* header,
71     ElementType* elements,
72     const Message& message) {
73   for (uint32_t i = 0; i < header->num_elements; ++i) {
74     if (!DecodeHandle(&elements[i], message.handles))
75       return false;
76   }
77   return true;
78 }
79
80 }  // namespace internal
81 }  // namespace mojo