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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
#![no_std]
use core::fmt;
use core::mem;
use core::ops::Deref;
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum NulError {
InteriorNul(usize),
NotNulTerminated,
}
impl fmt::Display for NulError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
NulError::InteriorNul(pos) =>
write!(f, "data provided contains an interior nul at byte pos {}", pos),
NulError::NotNulTerminated =>
f.write_str("data provided is not nul terminated"),
}
}
}
pub struct NulTerminatedStr(str);
impl NulTerminatedStr {
pub fn from_str_with_nul(s: &str) -> Result<&NulTerminatedStr, NulError> {
let nul_pos = s.bytes().position(|b| b == 0);
nul_pos.ok_or(NulError::NotNulTerminated).and_then(|i| {
if i == s.len() - 1 {
Ok(unsafe { mem::transmute(s) })
} else {
Err(NulError::InteriorNul(i))
}
})
}
pub fn as_str_with_nul(&self) -> &str {
&self.0
}
}
impl Deref for NulTerminatedStr {
type Target = str;
fn deref(&self) -> &str {
&self.0[..self.0.len() - 1]
}
}
impl AsRef<str> for NulTerminatedStr {
fn as_ref(&self) -> &str {
&**self
}
}
impl fmt::Debug for NulTerminatedStr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self.as_str_with_nul(), f)
}
}
impl fmt::Display for NulTerminatedStr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[macro_export]
macro_rules! ntstr {
($e:expr) => (
match $crate::NulTerminatedStr::from_str_with_nul(concat!($e, "\0")) {
Ok(s) => s,
Err(e) => panic!("{}", e),
}
)
}
#[cfg(test)]
mod tests {
use super::{NulTerminatedStr, NulError};
#[test]
fn test() {
let s = ntstr!("foo");
assert_eq!(&**s, "foo");
assert_eq!(s.len(), 3);
assert_eq!(&s[0..2], "fo");
assert_eq!(s.as_str_with_nul(), "foo\0");
}
#[test]
fn test_err() {
assert_eq!(NulTerminatedStr::from_str_with_nul("foo").unwrap_err(),
NulError::NotNulTerminated);
assert_eq!(NulTerminatedStr::from_str_with_nul("fo\0o").unwrap_err(),
NulError::InteriorNul(2));
assert_eq!(NulTerminatedStr::from_str_with_nul("fo\0o\0").unwrap_err(),
NulError::InteriorNul(2));
}
}