Skip to main content

dear_imgui_rs/texture/
owned.rs

1use super::TextureData;
2use crate::sys;
3use std::ptr::NonNull;
4
5/// Owned texture data managed by Dear ImGui.
6///
7/// This owns an `ImTextureData` instance allocated by Dear ImGui (C++) and will
8/// destroy it on drop. It dereferences to [`TextureData`] so you can call the
9/// same APIs as on borrowed texture data (e.g. items returned by
10/// `DrawData::textures_mut()`).
11pub struct OwnedTextureData {
12    raw: NonNull<sys::ImTextureData>,
13}
14
15impl OwnedTextureData {
16    /// Create a new empty texture data object (C++ constructed).
17    pub fn new() -> Self {
18        let raw = unsafe { sys::ImTextureData_ImTextureData() };
19        let raw = NonNull::new(raw).expect("ImTextureData_ImTextureData() returned null");
20        Self { raw }
21    }
22
23    /// Leak the underlying `ImTextureData*` without destroying it.
24    pub fn into_raw(self) -> *mut sys::ImTextureData {
25        let raw = self.raw.as_ptr();
26        std::mem::forget(self);
27        raw
28    }
29
30    /// Take ownership of a raw `ImTextureData*`.
31    ///
32    /// # Safety
33    /// - `raw` must be a valid pointer returned by `ImTextureData_ImTextureData()`.
34    /// - The caller must ensure no other owner will call `ImTextureData_destroy(raw)`.
35    pub unsafe fn from_raw_owned(raw: *mut sys::ImTextureData) -> Self {
36        let raw = NonNull::new(raw).expect("raw ImTextureData pointer was null");
37        Self { raw }
38    }
39}
40
41impl Drop for OwnedTextureData {
42    fn drop(&mut self) {
43        crate::context::unregister_user_texture_from_all_contexts(self.raw.as_ptr());
44        unsafe { sys::ImTextureData_destroy(self.raw.as_ptr()) }
45    }
46}
47
48impl std::ops::Deref for OwnedTextureData {
49    type Target = TextureData;
50
51    fn deref(&self) -> &Self::Target {
52        unsafe { &*(self.raw.as_ptr() as *const TextureData) }
53    }
54}
55
56impl std::ops::DerefMut for OwnedTextureData {
57    fn deref_mut(&mut self) -> &mut Self::Target {
58        unsafe { &mut *(self.raw.as_ptr() as *mut TextureData) }
59    }
60}
61
62impl AsRef<TextureData> for OwnedTextureData {
63    fn as_ref(&self) -> &TextureData {
64        self
65    }
66}
67
68impl AsMut<TextureData> for OwnedTextureData {
69    fn as_mut(&mut self) -> &mut TextureData {
70        self
71    }
72}