1 | // Copyright 2013 The Flutter 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 FLUTTER_VULKAN_VULKAN_HANDLE_H_ |
6 | #define FLUTTER_VULKAN_VULKAN_HANDLE_H_ |
7 | |
8 | #include <functional> |
9 | |
10 | #include "flutter/fml/logging.h" |
11 | #include "flutter/fml/macros.h" |
12 | #include "vulkan_interface.h" |
13 | |
14 | namespace vulkan { |
15 | |
16 | template <class T> |
17 | class VulkanHandle { |
18 | public: |
19 | using Handle = T; |
20 | using Disposer = std::function<void(Handle)>; |
21 | |
22 | VulkanHandle() : handle_(VK_NULL_HANDLE) {} |
23 | |
24 | VulkanHandle(Handle handle, const Disposer& disposer = nullptr) |
25 | : handle_(handle), disposer_(disposer) {} |
26 | |
27 | VulkanHandle(VulkanHandle&& other) |
28 | : handle_(other.handle_), disposer_(other.disposer_) { |
29 | other.handle_ = VK_NULL_HANDLE; |
30 | other.disposer_ = nullptr; |
31 | } |
32 | |
33 | ~VulkanHandle() { DisposeIfNecessary(); } |
34 | |
35 | VulkanHandle& operator=(VulkanHandle&& other) { |
36 | if (handle_ != other.handle_) { |
37 | DisposeIfNecessary(); |
38 | } |
39 | |
40 | handle_ = other.handle_; |
41 | disposer_ = other.disposer_; |
42 | |
43 | other.handle_ = VK_NULL_HANDLE; |
44 | other.disposer_ = nullptr; |
45 | |
46 | return *this; |
47 | } |
48 | |
49 | operator bool() const { return handle_ != VK_NULL_HANDLE; } |
50 | |
51 | operator Handle() const { return handle_; } |
52 | |
53 | /// Relinquish responsibility of collecting the underlying handle when this |
54 | /// object is collected. It is the responsibility of the caller to ensure that |
55 | /// the lifetime of the handle extends past the lifetime of this object. |
56 | void ReleaseOwnership() { disposer_ = nullptr; } |
57 | |
58 | void Reset() { DisposeIfNecessary(); } |
59 | |
60 | private: |
61 | Handle handle_; |
62 | Disposer disposer_; |
63 | |
64 | void DisposeIfNecessary() { |
65 | if (handle_ == VK_NULL_HANDLE) { |
66 | return; |
67 | } |
68 | if (disposer_) { |
69 | disposer_(handle_); |
70 | } |
71 | handle_ = VK_NULL_HANDLE; |
72 | disposer_ = nullptr; |
73 | } |
74 | |
75 | FML_DISALLOW_COPY_AND_ASSIGN(VulkanHandle); |
76 | }; |
77 | |
78 | } // namespace vulkan |
79 | |
80 | #endif // FLUTTER_VULKAN_VULKAN_HANDLE_H_ |
81 |