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#pragma once
6
7#include <functional>
8
9#include "flutter/fml/logging.h"
10#include "flutter/fml/macros.h"
11#include "flutter/vulkan/procs/vulkan_interface.h"
12
13namespace vulkan {
14
15template <class T>
16class VulkanHandle {
17 public:
18 using Handle = T;
19 using Disposer = std::function<void(Handle)>;
20
21 VulkanHandle() : handle_(VK_NULL_HANDLE) {}
22
23 explicit VulkanHandle(Handle handle, const Disposer& disposer = nullptr)
24 : handle_(handle), disposer_(disposer) {}
25
26 VulkanHandle(VulkanHandle&& other)
27 : handle_(other.handle_), disposer_(other.disposer_) {
28 other.handle_ = VK_NULL_HANDLE;
29 other.disposer_ = nullptr;
30 }
31
32 ~VulkanHandle() { DisposeIfNecessary(); }
33
34 VulkanHandle& operator=(VulkanHandle&& other) {
35 if (handle_ != other.handle_) {
36 DisposeIfNecessary();
37 }
38
39 handle_ = other.handle_;
40 disposer_ = other.disposer_;
41
42 other.handle_ = VK_NULL_HANDLE;
43 other.disposer_ = nullptr;
44
45 return *this;
46 }
47
48 explicit operator bool() const { return handle_ != VK_NULL_HANDLE; }
49
50 // NOLINTNEXTLINE(google-explicit-constructor)
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

source code of flutter_engine/flutter/vulkan/procs/vulkan_handle.h