1 // Copyright 2014 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 // This file provides a C++ wrapping around the Mojo C API for shared buffers, 6 // replacing the prefix of "Mojo" with a "mojo" namespace, and using more 7 // strongly-typed representations of |MojoHandle|s. 8 // 9 // Please see "mojo/public/c/system/buffer.h" for complete documentation of the 10 // API. 11 12 #ifndef MOJO_PUBLIC_CPP_SYSTEM_BUFFER_H_ 13 #define MOJO_PUBLIC_CPP_SYSTEM_BUFFER_H_ 14 15 #include <stdint.h> 16 17 #include <memory> 18 19 #include "base/compiler_specific.h" 20 #include "base/logging.h" 21 #include "mojo/public/c/system/buffer.h" 22 #include "mojo/public/cpp/system/handle.h" 23 24 namespace mojo { 25 namespace internal { 26 27 struct Unmapper { 28 void operator()(void* buffer) { 29 MojoResult result = MojoUnmapBuffer(buffer); 30 DCHECK_EQ(MOJO_RESULT_OK, result); 31 } 32 }; 33 34 } // namespace internal 35 36 using ScopedSharedBufferMapping = std::unique_ptr<void, internal::Unmapper>; 37 38 class SharedBufferHandle; 39 40 typedef ScopedHandleBase<SharedBufferHandle> ScopedSharedBufferHandle; 41 42 // A strongly-typed representation of a |MojoHandle| referring to a shared 43 // buffer. 44 class SharedBufferHandle : public Handle { 45 public: 46 enum class AccessMode { 47 READ_WRITE, 48 READ_ONLY, 49 }; 50 51 SharedBufferHandle() {} 52 explicit SharedBufferHandle(MojoHandle value) : Handle(value) {} 53 54 // Copying and assignment allowed. 55 56 // Creates a new SharedBufferHandle. Returns an invalid handle on failure. 57 static ScopedSharedBufferHandle Create(uint64_t num_bytes); 58 59 // Clones this shared buffer handle. If |access_mode| is READ_ONLY or this is 60 // a read-only handle, the new handle will be read-only. On failure, this will 61 // return an empty result. 62 ScopedSharedBufferHandle Clone(AccessMode = AccessMode::READ_WRITE) const; 63 64 // Maps |size| bytes of this shared buffer. On failure, this will return a 65 // null mapping. 66 ScopedSharedBufferMapping Map(uint64_t size) const; 67 68 // Maps |size| bytes of this shared buffer, starting |offset| bytes into the 69 // buffer. On failure, this will return a null mapping. 70 ScopedSharedBufferMapping MapAtOffset(uint64_t size, uint64_t offset) const; 71 }; 72 73 static_assert(sizeof(SharedBufferHandle) == sizeof(Handle), 74 "Bad size for C++ SharedBufferHandle"); 75 static_assert(sizeof(ScopedSharedBufferHandle) == sizeof(SharedBufferHandle), 76 "Bad size for C++ ScopedSharedBufferHandle"); 77 78 } // namespace mojo 79 80 #endif // MOJO_PUBLIC_CPP_SYSTEM_BUFFER_H_ 81