]> git.lizzy.rs Git - rust.git/blob - src/liballoc/libc_heap.rs
alloc: Refactor OOM into a common routine
[rust.git] / src / liballoc / libc_heap.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11
12 //! The global (exchange) heap.
13
14 use libc::{c_void, size_t, free, malloc, realloc};
15 use core::ptr::{RawPtr, mut_null};
16
17 /// A wrapper around libc::malloc, aborting on out-of-memory
18 #[inline]
19 pub unsafe fn malloc_raw(size: uint) -> *mut u8 {
20     // `malloc(0)` may allocate, but it may also return a null pointer
21     // http://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html
22     if size == 0 {
23         mut_null()
24     } else {
25         let p = malloc(size as size_t);
26         if p.is_null() {
27             ::oom();
28         }
29         p as *mut u8
30     }
31 }
32
33 /// A wrapper around libc::realloc, aborting on out-of-memory
34 #[inline]
35 pub unsafe fn realloc_raw(ptr: *mut u8, size: uint) -> *mut u8 {
36     // `realloc(ptr, 0)` may allocate, but it may also return a null pointer
37     // http://pubs.opengroup.org/onlinepubs/9699919799/functions/realloc.html
38     if size == 0 {
39         free(ptr as *mut c_void);
40         mut_null()
41     } else {
42         let p = realloc(ptr as *mut c_void, size as size_t);
43         if p.is_null() {
44             ::oom();
45         }
46         p as *mut u8
47     }
48 }