safe_libc/stdlib.rs
1//
2// Created: Thu 16 Apr 2020 01:20:13 PM PDT
3// Modified: Sun 19 Apr 2020 07:44:00 PM PDT
4//
5// Copyright (C) 2020 Robert Gill <rtgill82@gmail.com>
6//
7// Permission is hereby granted, free of charge, to any person obtaining a copy
8// of this software and associated documentation files (the "Software"), to
9// deal in the Software without restriction, including without limitation the
10// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
11// sell copies of the Software, and to permit persons to whom the Software is
12// furnished to do so, subject to the following conditions:
13//
14// The above copyright notice and this permission notice shall be included in
15// all copies of the Software, its documentation and marketing & publicity
16// materials, and acknowledgment shall be given in the documentation, materials
17// and software packages that this Software was used.
18//
19// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22// THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
23// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
24// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25//
26
27use crate::errno;
28use crate::errno::{Error,Result};
29use crate::VoidPtr;
30
31#[cfg(target_family = "unix")]
32use crate::posix::string::strerror_s;
33
34#[cfg(target_family = "windows")]
35use crate::windows::string::strerror_s;
36
37macro_rules! try_alloc {
38 ($fn:expr) => {
39 let ptr = $fn;
40 match ptr.is_null() {
41 false => return Ok(ptr),
42 true => {
43 let errnum = errno::errno();
44 match strerror_s(errnum) {
45 Ok(errmsg) => return Err(Error::new_msg(errnum, errmsg)),
46 Err(err) => return Err(err)
47 }
48 }
49 }
50 }
51}
52
53pub fn malloc(size: usize) -> Result<VoidPtr> {
54 unsafe {
55 try_alloc!(libc::malloc(size));
56 }
57}
58
59pub fn realloc(ptr: VoidPtr, size: usize) -> Result<VoidPtr> {
60 unsafe {
61 try_alloc!(libc::realloc(ptr, size));
62 }
63}