Forráskód Böngészése

Hacky version of memalign

Jeremy Soller 7 éve
szülő
commit
742339ca9e
2 módosított fájl, 27 hozzáadás és 1 törlés
  1. 18 0
      src/stdlib/src/lib.rs
  2. 9 1
      tests/alloc.c

+ 18 - 0
src/stdlib/src/lib.rs

@@ -323,6 +323,24 @@ pub unsafe extern "C" fn malloc(size: size_t) -> *mut c_void {
     }
 }
 
+#[no_mangle]
+pub unsafe extern "C" fn memalign(alignment: size_t, size: size_t) -> *mut c_void {
+    let mut align = 16;
+    while align <= alignment {
+        align *= 2;
+    }
+
+    let offset = align/2;
+    let ptr = ralloc::alloc(size + offset, align);
+    if !ptr.is_null() {
+        *(ptr as *mut u64) = (size + offset) as u64;
+        *(ptr as *mut u64).offset(1) = align as u64;
+        ptr.offset(offset as isize) as *mut c_void
+    } else {
+        ptr as *mut c_void
+    }
+}
+
 #[no_mangle]
 pub extern "C" fn mblen(s: *const c_char, n: size_t) -> c_int {
     unimplemented!();

+ 9 - 1
tests/alloc.c

@@ -10,11 +10,19 @@ int main(int argc, char ** argv) {
     }
     free(ptr);
 
-    char * ptrc = (char *)calloc(256,1);
+    char * ptrc = (char *)calloc(256, 1);
     printf("calloc %p\n", ptrc);
     for(i = 0; i < 256; i++) {
         ptrc[i] = (char)i;
     }
     free(ptrc);
+
+    char * ptra = (char *)memalign(256, 256);
+    printf("memalign %p\n", ptra);
+    for(i = 0; i < 256; i++) {
+        ptra[i] = (char)i;
+    }
+    free(ptra);
+
     return 0;
 }