1 use std::ops::{Deref, DerefMut}; 2 3 use super::*; 4 5 pub struct XSmartPointer<'a, T> { 6 xconn: &'a XConnection, 7 pub ptr: *mut T, 8 } 9 10 impl<'a, T> XSmartPointer<'a, T> { 11 // You're responsible for only passing things to this that should be XFree'd. 12 // Returns None if ptr is null. new(xconn: &'a XConnection, ptr: *mut T) -> Option<Self>13 pub fn new(xconn: &'a XConnection, ptr: *mut T) -> Option<Self> { 14 if !ptr.is_null() { 15 Some(XSmartPointer { xconn, ptr }) 16 } else { 17 None 18 } 19 } 20 } 21 22 impl<'a, T> Deref for XSmartPointer<'a, T> { 23 type Target = T; 24 deref(&self) -> &T25 fn deref(&self) -> &T { 26 unsafe { &*self.ptr } 27 } 28 } 29 30 impl<'a, T> DerefMut for XSmartPointer<'a, T> { deref_mut(&mut self) -> &mut T31 fn deref_mut(&mut self) -> &mut T { 32 unsafe { &mut *self.ptr } 33 } 34 } 35 36 impl<'a, T> Drop for XSmartPointer<'a, T> { drop(&mut self)37 fn drop(&mut self) { 38 unsafe { 39 (self.xconn.xlib.XFree)(self.ptr as *mut _); 40 } 41 } 42 } 43 44 impl XConnection { alloc_class_hint(&self) -> XSmartPointer<'_, ffi::XClassHint>45 pub fn alloc_class_hint(&self) -> XSmartPointer<'_, ffi::XClassHint> { 46 XSmartPointer::new(self, unsafe { (self.xlib.XAllocClassHint)() }) 47 .expect("`XAllocClassHint` returned null; out of memory") 48 } 49 alloc_size_hints(&self) -> XSmartPointer<'_, ffi::XSizeHints>50 pub fn alloc_size_hints(&self) -> XSmartPointer<'_, ffi::XSizeHints> { 51 XSmartPointer::new(self, unsafe { (self.xlib.XAllocSizeHints)() }) 52 .expect("`XAllocSizeHints` returned null; out of memory") 53 } 54 alloc_wm_hints(&self) -> XSmartPointer<'_, ffi::XWMHints>55 pub fn alloc_wm_hints(&self) -> XSmartPointer<'_, ffi::XWMHints> { 56 XSmartPointer::new(self, unsafe { (self.xlib.XAllocWMHints)() }) 57 .expect("`XAllocWMHints` returned null; out of memory") 58 } 59 } 60