demo_vk/graphics/vulkan/raii/
instance.rs

1use {
2    crate::trace,
3    anyhow::{Context, Result},
4    ash::vk,
5    std::sync::Arc,
6};
7
8/// A RAII wrapper for the ash library entry and instance that destroys itself
9/// when dropped.
10pub struct Instance {
11    pub entry: ash::Entry,
12    pub raw: ash::Instance,
13}
14
15impl Instance {
16    pub fn new(create_info: &vk::InstanceCreateInfo) -> Result<Arc<Self>> {
17        let entry = unsafe {
18            ash::Entry::load().with_context(trace!(
19                "Unable to load the default Vulkan library!"
20            ))?
21        };
22        let raw = unsafe {
23            entry
24                .create_instance(create_info, None)
25                .with_context(trace!("Unable to create the Vulkan instance!"))?
26        };
27        Ok(Arc::new(Self { entry, raw }))
28    }
29}
30
31impl std::ops::Deref for Instance {
32    type Target = ash::Instance;
33
34    fn deref(&self) -> &Self::Target {
35        &self.raw
36    }
37}
38
39impl Drop for Instance {
40    fn drop(&mut self) {
41        unsafe {
42            self.raw.destroy_instance(None);
43        }
44    }
45}
46
47impl std::fmt::Debug for Instance {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        f.debug_struct("<Ash Library Instance>").finish()
50    }
51}