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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
use core::fmt;
use core::isize;
use core::marker::PhantomData;
use core::mem;
use core::slice;
use core::str;
use swim_c_sys::{void, cchar};
use crate::string;
pub struct CStr {
lifetime: PhantomData<[cchar]>,
}
impl CStr {
pub fn from_ptr<'a>(ptr: *const u8) -> &'a Self {
unsafe { mem::transmute(ptr) }
}
pub fn from_cptr<'a>(ptr: *const cchar) -> &'a Self {
unsafe { mem::transmute(ptr) }
}
pub fn from_bytes(bytes: &[u8]) -> Result<&Self, ()> {
let len = bytes.len();
let ptr = bytes.as_ptr() as *mut void;
unsafe {
if len > 0 && string::memchr(ptr, 0, len) == ptr.offset((len - 1) as isize) {
Ok(mem::transmute(ptr))
} else {
Err(())
}
}
}
pub unsafe fn from_bytes_unchecked(bytes: &[u8]) -> &Self {
mem::transmute(bytes.as_ptr())
}
pub fn as_ptr(&self) -> *const u8 {
unsafe { mem::transmute(self) }
}
pub fn as_cptr(&self) -> *const cchar {
unsafe { mem::transmute(self) }
}
pub unsafe fn to_bytes(&self) -> &[u8] {
let len = string::strlen(self.as_cptr()) as usize;
slice::from_raw_parts(self.as_ptr(), len.wrapping_add(1))
}
pub unsafe fn to_str(&self) -> Result<&str, str::Utf8Error> {
let len = string::strlen(self.as_cptr()) as usize;
str::from_utf8(slice::from_raw_parts(self.as_ptr(), len))
}
pub unsafe fn to_str_unchecked(&self) -> &str {
let len = string::strlen(self.as_cptr()) as usize;
str::from_utf8_unchecked(slice::from_raw_parts(self.as_ptr(), len))
}
}
impl AsRef<CStr> for CStr {
#[inline]
fn as_ref(&self) -> &CStr {
self
}
}
impl fmt::Debug for CStr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
unsafe { self.to_str() }.fmt(f)
}
}
impl Default for &'static CStr {
#[inline]
fn default() -> &'static CStr {
CStr::from_ptr(b"\0".as_ptr())
}
}