blob: 8bcc02822454c198c3a0b4f5acb0c45d2ed6f8c3 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
use std::ffi::{self, CStr};
use std::ptr;
use libc;
/// Consumes and frees the input pointer, and assumes it points to
/// a nul-terminated C-string that contains valid UTF8.
pub unsafe fn string_from_utf8_charp(p: *mut i8) -> String {
let bytes = CStr::from_ptr(p).to_bytes();
let res = String::from_utf8(bytes.to_vec()).unwrap();
libc::free(p as *mut ffi::c_void);
res
}
pub fn strdup(s: &str) -> *mut i8 {
unsafe {
let p: *mut i8 = malloc(s.len() + 1);
ptr::copy_nonoverlapping(s.as_ptr(), p as *mut u8, s.len());
*p.add(s.len()) = 0;
p
}
}
pub unsafe fn malloc<T>(count: usize) -> *mut T {
libc::malloc(count * std::mem::size_of::<T>()) as *mut T
}
|