ByteBuf.h (1758B)
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 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 /* A type that can be sent without needing to make a copy during 8 * serialization. In addition the receiver can take ownership of the 9 * data to avoid having to make an additional copy. */ 10 11 #ifndef mozilla_ipc_ByteBuf_h 12 #define mozilla_ipc_ByteBuf_h 13 14 #include "mozilla/Assertions.h" 15 16 namespace IPC { 17 template <typename T> 18 struct ParamTraits; 19 } 20 21 namespace mozilla { 22 23 namespace ipc { 24 25 class ByteBuf final { 26 friend struct IPC::ParamTraits<mozilla::ipc::ByteBuf>; 27 28 public: 29 bool Allocate(size_t aLength) { 30 MOZ_ASSERT(mData == nullptr); 31 mData = (uint8_t*)malloc(aLength); 32 if (!mData) { 33 return false; 34 } 35 mLen = aLength; 36 mCapacity = aLength; 37 return true; 38 } 39 40 ByteBuf() : mData(nullptr), mLen(0), mCapacity(0) {} 41 42 ByteBuf(uint8_t* aData, size_t aLen, size_t aCapacity) 43 : mData(aData), mLen(aLen), mCapacity(aCapacity) {} 44 45 ByteBuf(const ByteBuf& aFrom) = delete; 46 47 ByteBuf(ByteBuf&& aFrom) 48 : mData(aFrom.mData), mLen(aFrom.mLen), mCapacity(aFrom.mCapacity) { 49 aFrom.mData = nullptr; 50 aFrom.mLen = 0; 51 aFrom.mCapacity = 0; 52 } 53 54 ByteBuf& operator=(ByteBuf&& aFrom) { 55 std::swap(mData, aFrom.mData); 56 std::swap(mLen, aFrom.mLen); 57 std::swap(mCapacity, aFrom.mCapacity); 58 return *this; 59 } 60 61 ~ByteBuf() { free(mData); } 62 63 uint8_t* mData; 64 size_t mLen; 65 size_t mCapacity; 66 }; 67 68 } // namespace ipc 69 } // namespace mozilla 70 71 #endif // ifndef mozilla_ipc_ByteBuf_h