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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
#![warn(clippy::all)]
#![allow(trivial_numeric_casts)]
extern crate libc;
use std::cmp::Ordering;
use std::error::Error;
use std::ffi::CStr;
use std::fmt;
use std::fmt::Debug;
use std::hash;
use std::io::Error as IoError;
use std::io::ErrorKind::InvalidInput;
use std::iter::IntoIterator;
use std::marker;
use std::mem;
use std::ops::Deref;
pub use libc::c_char;
const NUL: u8 = 0;
pub struct OwnedCString {
ptr: *const c_char,
dtor: DestroyFn,
}
impl Drop for OwnedCString {
fn drop(&mut self) {
let dtor = self.dtor;
unsafe { dtor(self.ptr) };
}
}
impl Deref for OwnedCString {
type Target = CStr;
fn deref(&self) -> &CStr {
unsafe { CStr::from_ptr(self.ptr) }
}
}
impl PartialEq for OwnedCString {
fn eq(&self, other: &OwnedCString) -> bool {
unsafe { libc::strcmp(self.ptr, other.ptr) == 0 }
}
}
impl Eq for OwnedCString {}
impl PartialOrd for OwnedCString {
#[inline]
fn partial_cmp(&self, other: &OwnedCString) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for OwnedCString {
fn cmp(&self, other: &OwnedCString) -> Ordering {
let res = unsafe { libc::strcmp(self.ptr, other.ptr) };
res.cmp(&(0 as libc::c_int))
}
}
impl hash::Hash for OwnedCString {
fn hash<H>(&self, state: &mut H)
where
H: hash::Hasher,
{
self.to_bytes().hash(state)
}
}
pub type DestroyFn = unsafe fn(*const c_char);
pub unsafe fn libc_free(ptr: *const c_char) {
libc::free(ptr as *mut libc::c_void);
}
impl OwnedCString {
pub unsafe fn new(ptr: *const c_char, dtor: DestroyFn) -> OwnedCString {
assert!(!ptr.is_null());
OwnedCString {
ptr: ptr,
dtor: dtor,
}
}
}
impl Debug for OwnedCString {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\"{}\"", escape_bytestring(self.to_bytes()))
}
}
pub struct NulError {
position: usize,
bytes: Vec<u8>,
}
impl NulError {
pub fn nul_position(&self) -> usize {
self.position
}
pub fn into_bytes(self) -> Vec<u8> {
self.bytes
}
}
impl Error for NulError {
fn description(&self) -> &str {
"invalid data for C string: contains a NUL byte"
}
}
impl fmt::Display for NulError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"invalid data for C string: NUL at position {}",
self.position
)
}
}
impl fmt::Debug for NulError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"NulError {{ position: {}, bytes: \"{}\" }}",
self.position,
escape_bytestring(&self.bytes)
)
}
}
impl From<NulError> for IoError {
fn from(err: NulError) -> IoError {
IoError::new(
InvalidInput,
format!(
"invalid data for C string: NUL at position {}",
err.position
),
)
}
}
const IN_PLACE_SIZE: usize = 31;
#[derive(Clone)]
enum CStrData {
Owned(Vec<u8>),
InPlace([u8; IN_PLACE_SIZE]),
}
#[derive(Clone)]
pub struct CStrBuf {
data: CStrData,
}
fn find_nul(bytes: &[u8]) -> Option<usize> {
bytes.iter().position(|b| *b == NUL)
}
fn vec_into_c_str(mut v: Vec<u8>) -> CStrBuf {
v.push(NUL);
CStrBuf {
data: CStrData::Owned(v),
}
}
fn escape_bytestring(s: &[u8]) -> String {
use std::ascii;
let mut acc = Vec::with_capacity(s.len());
acc.extend(s.iter().cloned().flat_map(ascii::escape_default));
unsafe { String::from_utf8_unchecked(acc) }
}
#[macro_export]
macro_rules! c_str {
($lit:expr) => {
unsafe { std::ffi::CStr::from_ptr(concat!($lit, "\0").as_ptr() as *const $crate::c_char) }
};
}
impl CStrBuf {
pub fn from_iter<I>(iterable: I) -> Result<CStrBuf, NulError>
where
I: IntoIterator<Item = u8>,
{
fn nul_error<I>(mut collected: Vec<u8>, remaining: I) -> NulError
where
I: Iterator<Item = u8>,
{
let pos = collected.len();
collected.push(NUL);
collected.extend(remaining);
NulError {
position: pos,
bytes: collected,
}
}
let mut iter = iterable.into_iter();
let mut vec: Vec<u8> = match iter.size_hint() {
(_, Some(len)) if len < IN_PLACE_SIZE => {
let mut buf = [NUL; IN_PLACE_SIZE];
for i in 0..=len {
match iter.next() {
Some(NUL) => {
return Err(nul_error(buf[..i].to_vec(), iter));
}
Some(c) => {
buf[i] = c;
}
None => {
return Ok(CStrBuf {
data: CStrData::InPlace(buf),
});
}
}
}
let mut vec = Vec::<u8>::with_capacity(len + 2);
vec.extend_from_slice(&buf[..=len]);
vec
}
(lower, _) => Vec::with_capacity(lower + 1),
};
loop {
match iter.next() {
None => {
break;
}
Some(NUL) => {
return Err(nul_error(vec, iter));
}
Some(c) => {
let len = vec.len();
unsafe {
*vec.get_unchecked_mut(len) = c;
vec.set_len(len + 1);
}
if vec.len() == vec.capacity() {
let (lower, _) = iter.size_hint();
vec.reserve(lower + 1);
}
}
}
}
{
let len = vec.len();
unsafe {
*vec.get_unchecked_mut(len) = NUL;
vec.set_len(len + 1);
}
}
Ok(CStrBuf {
data: CStrData::Owned(vec),
})
}
#[inline]
pub fn from_str(s: &str) -> Result<CStrBuf, NulError> {
CStrBuf::from_iter(s.as_bytes().iter().cloned())
}
pub fn from_vec(vec: Vec<u8>) -> Result<CStrBuf, NulError> {
if let Some(pos) = find_nul(&vec[..]) {
return Err(NulError {
position: pos,
bytes: vec,
});
}
Ok(vec_into_c_str(vec))
}
pub unsafe fn from_vec_unchecked(vec: Vec<u8>) -> CStrBuf {
vec_into_c_str(vec)
}
pub fn into_vec(mut self) -> Vec<u8> {
match mem::replace(&mut self.data, CStrData::InPlace([NUL; IN_PLACE_SIZE])) {
CStrData::Owned(mut v) => {
let len = v.len();
v.truncate(len - 1);
v
}
CStrData::InPlace(ref a) => a[..find_nul(a).unwrap()].to_vec(),
}
}
fn as_bytes(&self) -> &[u8] {
match self.data {
CStrData::Owned(ref v) => &v[..v.len() - 1],
CStrData::InPlace(ref a) => &a[..find_nul(a).unwrap()],
}
}
}
impl fmt::Debug for CStrBuf {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\"{}\"", escape_bytestring(self.as_bytes()))
}
}
impl Deref for CStrBuf {
type Target = CStr;
fn deref(&self) -> &CStr {
let p = match self.data {
CStrData::Owned(ref v) => (*v).as_ptr(),
CStrData::InPlace(ref a) => a.as_ptr(),
} as *const c_char;
unsafe { CStr::from_ptr(p) }
}
}
pub struct CChars<'a> {
ptr: *const c_char,
lifetime: marker::PhantomData<&'a [c_char]>,
}
impl<'a> CChars<'a> {
#[inline]
pub fn from_c_str(s: &'a CStr) -> CChars<'a> {
CChars {
ptr: s.as_ptr(),
lifetime: marker::PhantomData,
}
}
}
impl<'a> Clone for CChars<'a> {
#[inline]
fn clone(&self) -> CChars<'a> {
CChars {
ptr: self.ptr,
lifetime: marker::PhantomData,
}
}
}
impl<'a> Copy for CChars<'a> {}
impl<'a> Iterator for CChars<'a> {
type Item = c_char;
fn next(&mut self) -> Option<c_char> {
let ch = unsafe { *self.ptr };
if ch == 0 {
None
} else {
self.ptr = unsafe { self.ptr.offset(1) };
Some(ch)
}
}
}
pub unsafe fn parse_c_multistring<F>(buf: *const c_char, limit: Option<usize>, mut f: F) -> usize
where
F: FnMut(&[u8]),
{
let mut curr_ptr = buf;
let mut ctr: usize = 0;
let (limited_count, limit) = match limit {
Some(limit) => (true, limit),
None => (false, 0),
};
while (!limited_count || ctr < limit) && *curr_ptr != 0 {
let bytes = CStr::from_ptr(curr_ptr).to_bytes();
f(bytes);
curr_ptr = curr_ptr.offset(bytes.len() as isize + 1);
ctr += 1;
}
return ctr;
}