SerializeToBytesUtil.h (2260B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 3 /* This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this file, 5 * You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 #ifndef mozilla_ipc_SerializeToBytesUtil_h 8 #define mozilla_ipc_SerializeToBytesUtil_h 9 10 #include "chrome/common/ipc_message_utils.h" 11 #include "chrome/common/ipc_message.h" 12 13 namespace mozilla::ipc { 14 15 // This file contains a pair of functions which (ab-)use the IPC::ParamTraits 16 // serializers with a temporary on-stack IPC::Message to serialize & 17 // de-serialize a value from a byte span. 18 // 19 // NOTE: This is _not_ efficient, and is _not_ guaranteed to work for arbitrary 20 // types! Many IPC serializers depend on the IPC::Message supporting additional 21 // information, such as attached endpoints and file handles. 22 23 template <typename T> 24 void SerializeToBytesUtil(T&& aValue, nsTArray<char>& aBytes) { 25 IPC::Message tmpMessage(MSG_ROUTING_NONE, -1); 26 27 { 28 IPC::MessageWriter writer(tmpMessage); 29 IPC::WriteParam(&writer, std::forward<T>(aValue)); 30 } 31 32 MOZ_RELEASE_ASSERT(!tmpMessage.has_any_attachments(), 33 "Value contains attachments (e.g. endpoints, file " 34 "handles) which cannot be serialized as bytes"); 35 36 aBytes.SetLength(tmpMessage.size() - IPC::Message::HeaderSize()); 37 38 IPC::MessageReader reader(tmpMessage); 39 bool readOk = reader.ReadBytesInto(aBytes.Elements(), aBytes.Length()); 40 MOZ_RELEASE_ASSERT(readOk); 41 // Double-check that the entire Message body was used. 42 MOZ_RELEASE_ASSERT(!reader.HasBytesAvailable(1)); 43 } 44 45 template <typename T> 46 IPC::ReadResult<T> DeserializeFromBytesUtil(const Span<char>& aBytes) { 47 IPC::Message tmpMessage(MSG_ROUTING_NONE, -1); 48 49 { 50 IPC::MessageWriter writer(tmpMessage); 51 writer.WriteBytes(aBytes.Elements(), aBytes.Length()); 52 } 53 54 IPC::MessageReader reader(tmpMessage); 55 auto rv = IPC::ReadParam<T>(&reader); 56 if (rv.isOk() && reader.HasBytesAvailable(1)) { 57 // Unexpected trailing data after deserialization. 58 return {}; 59 } 60 return rv; 61 } 62 63 } // namespace mozilla::ipc 64 65 #endif // mozilla_ipc_SerializeToBytesUtil_h