From c1488507f2dc14c998cf9c35dfc10c6921d1c39e Mon Sep 17 00:00:00 2001 From: Erick Ahmed Date: Wed, 12 Nov 2025 15:14:20 +0100 Subject: [PATCH] ffi: wrap unsafe FFI functions in safe wrappers --- src/wrappers/point.rs | 97 +++++++++++++++++-------------------------- 1 file changed, 38 insertions(+), 59 deletions(-) diff --git a/src/wrappers/point.rs b/src/wrappers/point.rs index b69f6f4..60b9bd5 100644 --- a/src/wrappers/point.rs +++ b/src/wrappers/point.rs @@ -1,29 +1,12 @@ -/* - SPDX-License-Identifier: AGPL-3.0-or-later - Copyright (C) 2025 Erick Ahmed -*/ +mod ffi_point { + use std::os::raw::c_double; -use std::os::raw::c_double; + #[repr(C)] + pub(crate) struct PointShape { + _private: [u8; 0], + } -// FFI bindings - -#[repr(C)] -pub struct PointShape { - _private: [u8; 0], -} - -extern "C" { - pub fn make_point(x: c_double, y: c_double, z: c_double) -> *mut PointShape; - pub fn coord_point( - shape: *const PointShape, - x: *mut c_double, - y: *mut c_double, - z: *mut c_double, - ); - pub fn delete_point(shape: *mut PointShape); -} - - extern "C" { + unsafe extern "C" { fn make_point(x: c_double, y: c_double, z: c_double) -> *mut PointShape; fn coord_point( shape: *const PointShape, @@ -34,47 +17,43 @@ extern "C" { fn delete_point(shape: *mut PointShape); } -pub struct Point { - ptr: *mut PointShape, -} + // Safe wrapper -impl Point { - pub fn new(x: f64, y: f64, z: f64) -> Self { - unsafe { - let ptr = make_point(x, y, z); - if ptr.is_null() { - panic!("Error: null pointer"); + pub struct Point { + ptr: *mut PointShape, + } + + impl Point { + pub fn new(x: f64, y: f64, z: f64) -> Result { + unsafe { + let ptr = make_point(x, y, z); + if ptr.is_null() { + Err("Error: null pointer returned") + } else { + Ok(Point { ptr }) + } + } + } + + pub fn coordinates(&self) -> (f64, f64, f64) { + unsafe { + let mut x = 0.0; + let mut y = 0.0; + let mut z = 0.0; + coord_point(self.ptr, &mut x, &mut y, &mut z); + (x, y, z) } - Self { ptr } } } - pub fn coordinates(&self) -> (f64, f64, f64) { - unsafe { - let mut x = 0.0; - let mut y = 0.0; - let mut z = 0.0; - - coord_point(self.ptr, &mut x, &mut y, &mut z); - (x, y, z) + impl Drop for Point { + fn drop(&mut self) { + unsafe { + delete_point(self.ptr); + } } } -} -impl Drop for Point { - fn drop(&mut self) { - unsafe { - delete_point(self.ptr); - } - } + unsafe impl Send for Point {} + unsafe impl Sync for Point {} } - -impl Clone for Point { - fn clone(&self) -> Self { - let (x, y, z) = self.coordinates(); - Self::new(x, y, z) - } -} - -unsafe impl Send for Point {} -unsafe impl Sync for Point {}