Support converting Option<&[]> to C
[ldk-c-bindings] / lightning-c-bindings / src / c_types / mod.rs
index 274981da8e02a22c3a7dc24e7e61aba72ea9e5f5..69319563b72a8c2fd284fda2de9f7a9de460731f 100644 (file)
@@ -607,3 +607,28 @@ pub(crate) mod ObjOps {
                }
        }
 }
+
+pub(crate) struct SmartPtr<T> {
+       ptr: *mut T,
+}
+impl<T> SmartPtr<T> {
+       pub(crate) fn from_obj(o: T) -> Self {
+               Self { ptr: Box::into_raw(Box::new(o)) }
+       }
+       pub(crate) fn null() -> Self {
+               Self { ptr: std::ptr::null_mut() }
+       }
+}
+impl<T> Drop for SmartPtr<T> {
+       fn drop(&mut self) {
+               if self.ptr != std::ptr::null_mut() {
+                       unsafe { Box::from_raw(self.ptr); }
+               }
+       }
+}
+impl<T> std::ops::Deref for SmartPtr<T> {
+       type Target = *mut T;
+       fn deref(&self) -> &*mut T {
+               &self.ptr
+       }
+}