changeset 1058:0e149bf58579 draft

WIP: fix malloc/free
author Josef 'Jeff' Sipek <jeffpc@josefsipek.net>
date Wed, 20 Mar 2024 22:20:25 -0400
parents 48906c77fd87
children
files cmake/rust-errno.cmake common.rs
diffstat 2 files changed, 16 insertions(+), 4 deletions(-) [+]
line wrap: on
line diff
--- a/cmake/rust-errno.cmake	Wed Mar 20 22:03:41 2024 -0400
+++ b/cmake/rust-errno.cmake	Wed Mar 20 22:20:25 2024 -0400
@@ -51,6 +51,12 @@
 	"pub enum ERRNO {\n"
 	"${RUST_CODE}"
 	"}\n"
+    "impl core::ops::Neg for ERRNO {\n"
+    "   type Output = isize\;\n"
+    "   fn neg(self) -> Self::Output {\n"
+    "       -(self as isize)\n"
+    "   }\n"
+    "}\n"
 	"#[allow(dead_code)]\n"
 	"pub const ELAST: i32 = ${ELAST}\;\n"
 )
--- a/common.rs	Wed Mar 20 22:03:41 2024 -0400
+++ b/common.rs	Wed Mar 20 22:20:25 2024 -0400
@@ -22,6 +22,8 @@
 
 use core::mem;
 
+use super::ERRNO;
+
 const ELAST: isize = super::errno::ELAST as isize;
 
 pub mod raw {
@@ -35,15 +37,19 @@
 /*
  * Memory allocation
  */
-pub fn malloc_size<'a, T>(size: usize) -> Option<&'a mut T> {
+pub fn malloc_size<T>(size: usize) -> Result<T> {
     unsafe {
-        let ptr = raw::malloc(size) as *mut T;
+        let ptr = raw::malloc(size);
 
-        ptr.as_mut()
+        if ptr as usize == 0 {
+            Result::<T>::err(-ERRNO::ENOMEM)
+        } else {
+            Result::<T>::ptr(&mut *(ptr as *mut T))
+        }
     }
 }
 
-pub fn malloc<'a, T>() -> Option<&'a mut T> {
+pub fn malloc<T>() -> Result<T> {
     malloc_size::<T>(mem::size_of::<T>())
 }