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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
use crate::lang::c::CType;
use crate::lang::rust::CTypeInfo;
use crate::patterns::TypePattern;
use crate::Error;
use std::ffi::CStr;
use std::marker::PhantomData;
use std::option::Option::None;
use std::os::raw::c_char;
use std::ptr::null;
static EMPTY: &[u8] = b"\0";
#[repr(transparent)]
#[derive(Debug)]
pub struct AsciiPointer<'a> {
ptr: *const c_char,
_phandom: PhantomData<&'a ()>,
}
impl<'a> Default for AsciiPointer<'a> {
fn default() -> Self {
Self {
ptr: null(),
_phandom: Default::default(),
}
}
}
impl<'a> AsciiPointer<'a> {
pub fn empty() -> Self {
Self {
ptr: EMPTY.as_ptr().cast(),
_phandom: Default::default(),
}
}
pub fn from_slice_with_nul(ascii_with_nul: &[u8]) -> Result<Self, Error> {
if !ascii_with_nul.contains(&0) {
return Err(Error::Ascii);
}
if ascii_with_nul.iter().any(|x| *x > 127) {
return Err(Error::Ascii);
}
Ok(Self {
ptr: ascii_with_nul.as_ptr().cast(),
_phandom: Default::default(),
})
}
pub fn from_cstr(cstr: &'a CStr) -> Self {
Self {
ptr: cstr.as_ptr(),
_phandom: Default::default(),
}
}
pub fn as_c_str(&self) -> Option<&'a CStr> {
if self.ptr.is_null() {
None
} else {
unsafe { Some(CStr::from_ptr(self.ptr)) }
}
}
pub fn as_str(&self) -> Result<&'a str, Error> {
Ok(self.as_c_str().ok_or(Error::Null)?.to_str()?)
}
}
unsafe impl<'a> CTypeInfo for AsciiPointer<'a> {
fn type_info() -> CType {
CType::Pattern(TypePattern::AsciiPointer)
}
}
#[cfg(test)]
mod test {
use crate::patterns::string::AsciiPointer;
use std::ffi::CString;
#[test]
fn can_create() {
let s = "hello world";
let cstr = CString::new(s).unwrap();
let ptr_some = AsciiPointer::from_cstr(&cstr);
assert_eq!(s, ptr_some.as_str().unwrap());
}
#[test]
fn from_slice_with_nul_works() {
let s = b"hello\0world";
let ptr_some = AsciiPointer::from_slice_with_nul(&s[..]).unwrap();
assert_eq!("hello", ptr_some.as_str().unwrap());
}
#[test]
fn from_slice_with_nul_fails_if_not_nul() {
let s = b"hello world";
let ptr_some = AsciiPointer::from_slice_with_nul(&s[..]);
assert!(ptr_some.is_err());
}
}