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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
use_prelude!();
use ::core::slice;
ReprC! {
#[repr(transparent)]
#[derive(Clone, Copy)]
pub
struct char_p_ref['lt,] (
ptr::NonNullRef<c_char>,
PhantomCovariantLifetime<'lt>,
);
}
const NUL: u8 = b'\0';
impl char_p_ref<'static> {
pub
const EMPTY: Self = unsafe {
Self::from_ptr_unchecked(ptr::NonNull::new_unchecked({
const IT: u8 = NUL;
&IT as *const u8 as *mut u8
}))
};
}
impl<'lt> char_p_ref<'lt> {
pub
const
unsafe
fn from_ptr_unchecked (ptr: ptr::NonNull<u8>)
-> Self
{
Self(
ptr::NonNullRef(ptr.cast()),
PhantomCovariantLifetime::<'static>(PhantomData),
)
}
}
impl fmt::Debug
for char_p_ref<'_>
{
fn fmt (self: &'_ Self, fmt: &'_ mut fmt::Formatter<'_>)
-> fmt::Result
{
fmt::Debug::fmt(self.to_str(), fmt)
}
}
impl fmt::Display
for char_p_ref<'_>
{
fn fmt (self: &'_ Self, fmt: &'_ mut fmt::Formatter<'_>)
-> fmt::Result
{
fmt::Display::fmt(self.to_str(), fmt)
}
}
#[derive(Debug)]
pub
struct InvalidNulTerminator<Payload> (
pub Payload,
);
impl<T> fmt::Display
for InvalidNulTerminator<T>
{
fn fmt (self: &'_ Self, fmt: &'_ mut fmt::Formatter<'_>)
-> fmt::Result
{
fmt::Display::fmt(
"Null byte not at the expected terminating position",
fmt,
)
}
}
impl<'lt> TryFrom<&'lt str>
for char_p_ref<'lt>
{
type Error = InvalidNulTerminator<()>;
fn try_from (s: &'lt str)
-> Result<
char_p_ref<'lt>,
InvalidNulTerminator<()>,
>
{
Ok(if let Some(len_minus_one) = s.len().checked_sub(1) {
unsafe {
if s.bytes().position(|b| b == NUL) != Some(len_minus_one) {
return Err(InvalidNulTerminator(()));
}
Self::from_ptr_unchecked(
ptr::NonNull::new(s.as_ptr() as _).unwrap()
)
}
} else {
char_p_ref::EMPTY
})
}
}
cfg_std! {
impl<T : fmt::Debug> ::std::error::Error
for InvalidNulTerminator<T>
{}
impl<'lt> From<&'lt ::std::ffi::CStr>
for char_p_ref<'lt>
{
#[inline]
fn from (s: &'lt ::std::ffi::CStr)
-> char_p_ref<'lt>
{
unsafe {
let _assert_valid_utf8 =
::core::str::from_utf8(s.to_bytes())
.unwrap()
;
Self::from_ptr_unchecked(
ptr::NonNull::new(s.as_ptr() as _)
.unwrap()
)
}
}
}
}
impl<'lt> char_p_ref<'lt> {
#[inline]
pub
fn bytes (self: char_p_ref<'lt>)
-> impl Iterator<Item = ::core::num::NonZeroU8> + 'lt
{
::core::iter::from_fn({
let mut ptr = self.0.as_ptr().cast::<u8>();
move || {
let ret = ::core::num::NonZeroU8::new(unsafe { ptr.read() });
if ret.is_some() {
unsafe {
ptr = ptr.add(1);
}
}
ret
}
})
}
#[inline]
pub
fn to_nonzero_bytes (self: char_p_ref<'lt>)
-> &'lt [::core::num::NonZeroU8]
{
unsafe {
slice::from_raw_parts(
self.0.as_ptr().cast(),
self.bytes().count(),
)
}
}
#[inline]
pub
fn to_bytes (self: char_p_ref<'lt>)
-> &'lt [u8]
{
unsafe {
slice::from_raw_parts(
self.0.as_ptr().cast(),
self.bytes().count(),
)
}
}
#[inline]
pub
fn to_bytes_with_null (self: char_p_ref<'lt>)
-> &'lt [u8]
{
unsafe {
slice::from_raw_parts(
self.0.as_ptr().cast(),
self.bytes().count() + 1,
)
}
}
#[inline]
pub
fn to_str (self: char_p_ref<'lt>)
-> &'lt str
{
unsafe {
::core::str::from_utf8_unchecked(self.to_bytes())
}
}
#[inline]
pub
fn to_str_with_null (self: char_p_ref<'lt>)
-> &'lt str
{
unsafe {
::core::str::from_utf8_unchecked(self.to_bytes_with_null())
}
}
cfg_alloc! {
#[inline]
pub
fn to_owned (self: char_p_ref<'lt>)
-> char_p_boxed
{
self.to_str_with_null()
.to_owned()
.try_into().unwrap()
}
}
}
impl<'lt> Eq for char_p_ref<'lt> {}
impl<'lt> PartialEq for char_p_ref<'lt> {
#[inline]
fn eq (self: &'_ Self, other: &'_ Self)
-> bool
{
*self.to_str() == *other.to_str()
}
}
ReprC! {
#[repr(transparent)]
#[allow(missing_copy_implementations)]
pub
struct char_p_raw (
ptr::NonNullRef<c_char>,
);
}
#[cfg_attr(feature = "proc_macros",
require_unsafe_in_bodies,
)]
#[cfg_attr(not(feature = "proc_macros"),
allow(unused_unsafe),
)]
impl char_p_raw {
pub
unsafe
fn as_ref<'borrow> (self: &'borrow Self)
-> char_p_ref<'borrow>
{
unsafe {
::core::mem::transmute(self.0)
}
}
}
impl<'lt> From<char_p_ref<'lt>>
for char_p_raw
{
#[inline]
fn from (it: char_p_ref<'lt>)
-> char_p_raw
{
unsafe {
mem::transmute(it)
}
}
}
impl fmt::Debug
for char_p_raw
{
fn fmt (self: &'_ Self, fmt: &'_ mut fmt::Formatter<'_>)
-> fmt::Result
{
fmt .debug_tuple("char_p_raw")
.field(&self.0)
.finish()
}
}
cfg_alloc! {
#[inline]
pub
fn new<Str> (s: Str)
-> char_p_boxed
where
char_p_boxed : hidden::__<Str>,
{
MyFrom::my_from(s)
}
ReprC! {
#[repr(transparent)]
pub
struct char_p_boxed (
ptr::NonNullOwned<c_char>,
);
}
unsafe
impl Send
for char_p_boxed
where
rust::Box<[u8]> : Send,
{}
unsafe
impl Sync
for char_p_boxed
where
rust::Box<[u8]> : Sync,
{}
impl fmt::Debug
for char_p_boxed
{
fn fmt (self: &'_ Self, fmt: &'_ mut fmt::Formatter<'_>)
-> fmt::Result
{
fmt::Debug::fmt(&self.as_ref(), fmt)
}
}
impl fmt::Display
for char_p_boxed
{
fn fmt (self: &'_ Self, fmt: &'_ mut fmt::Formatter<'_>)
-> fmt::Result
{
fmt::Display::fmt(&self.as_ref(), fmt)
}
}
static EMPTY_SENTINEL: u8 = NUL;
impl char_p_boxed {
#[inline]
pub
const
unsafe
fn from_ptr_unchecked (ptr: ptr::NonNull<u8>)
-> char_p_boxed
{
Self(
ptr::NonNullOwned(ptr.cast(), PhantomData),
)
}
#[inline]
pub
fn as_ref (self: &'_ char_p_boxed)
-> char_p_ref<'_>
{
unsafe {
mem::transmute(self.0.as_ref())
}
}
}
use hidden::__ as MyFrom; mod hidden {
pub
trait __<Orig> { fn my_from (it: Orig) -> Self; }
}
macro_rules! derive_MyFrom_from {(
$(
$(@for[$($generics:tt)*])?
$T:ty => $Intermediate:ty
),* $(,)?
) => ($(
impl$(<$($generics)*>)? MyFrom<$T>
for char_p_boxed
{
#[inline]
fn my_from (it: $T)
-> char_p_boxed
{
<Self as TryFrom<$Intermediate>>::try_from(it.into())
.unwrap_or_else(|s| panic!(concat!(
"Error, the string `{:?}` contains an inner nul byte",
" and can thus not be converted to a C string without ",
"truncating it.",
), s))
}
}
)*)}
derive_MyFrom_from! {
@for['lt] &'lt str => rust::String,
rust::String => rust::String,
String => rust::String,
}
cfg_std! {
derive_MyFrom_from! {
@for['lt] &'lt ::std::ffi::CStr => ::std::ffi::CString,
::std::ffi::CString => ::std::ffi::CString,
}
}
impl TryFrom<rust::String> for char_p_boxed {
type Error = InvalidNulTerminator<rust::String>;
fn try_from (s: rust::String)
-> Result<
char_p_boxed,
InvalidNulTerminator<rust::String>,
>
{
Ok(if let Some(len_minus_one) = s.len().checked_sub(1) {
unsafe {
if s.as_bytes()[.. len_minus_one].contains(&NUL) {
return Err(InvalidNulTerminator(s));
}
let mut s = s;
if s.as_bytes()[len_minus_one] != NUL {
s.reserve_exact(1);
s.push(NUL as _);
}
let s: rust::Box<[u8]> = s.into_boxed_str().into();
Self::from_ptr_unchecked(
ptr::NonNull::new(rust::Box::leak(s).as_mut_ptr())
.unwrap()
)
}
} else {
unsafe {
Self::from_ptr_unchecked(ptr::NonNull::new_unchecked(
(&EMPTY_SENTINEL) as *const _ as *mut _
))
}
})
}
}
impl Drop for char_p_boxed {
fn drop (self: &'_ mut char_p_boxed)
{
unsafe {
if ptr::eq(self.0.as_mut_ptr().cast(), &EMPTY_SENTINEL) {
return;
}
let num_bytes = self.to_bytes_with_null().len();
drop::<rust::Box<[u8]>>(
rust::Box::from_raw(slice::from_raw_parts_mut(
self.0.as_mut_ptr().cast(),
num_bytes,
))
);
}
}
}
impl char_p_boxed {
#[inline]
pub
fn bytes<'lt> (self: &'lt char_p_boxed)
-> impl Iterator<Item = ::core::num::NonZeroU8> + 'lt
{
self.as_ref().bytes()
}
#[inline]
pub
fn to_nonzero_bytes (self: &'_ char_p_boxed)
-> &'_ [::core::num::NonZeroU8]
{
self.as_ref().to_nonzero_bytes()
}
#[inline]
pub
fn to_bytes (self: &'_ char_p_boxed)
-> &'_ [u8]
{
self.as_ref().to_bytes()
}
#[inline]
pub
fn to_bytes_with_null (self: &'_ char_p_boxed)
-> &'_ [u8]
{
self.as_ref().to_bytes_with_null()
}
#[inline]
pub
fn to_str (self: &'_ char_p_boxed)
-> &'_ str
{
self.as_ref().to_str()
}
#[inline]
pub
fn to_str_with_null (self: &'_ char_p_boxed)
-> &'_ str
{
self.as_ref().to_str_with_null()
}
pub
fn into_vec (mut self: char_p_boxed)
-> rust::Vec<u8>
{
if ptr::eq(self.0.as_mut_ptr().cast(), &EMPTY_SENTINEL) {
return vec![];
}
let num_bytes = self.to_bytes_with_null().len();
let ptr = mem::ManuallyDrop::new(self).0.as_mut_ptr();
let boxed_bytes = unsafe {
rust::Box::from_raw(slice::from_raw_parts_mut(
ptr.cast(),
num_bytes,
))
};
let mut vec = rust::Vec::from(boxed_bytes);
vec.pop();
vec
}
#[inline]
pub
fn into_string (self: char_p_boxed)
-> rust::String
{
unsafe {
rust::String::from_utf8_unchecked(
self.into_vec()
)
}
}
#[inline]
pub
fn to_owned (self: &'_ char_p_boxed)
-> char_p_boxed
{
self.as_ref().to_owned()
}
}
impl Eq
for char_p_boxed
{}
impl PartialEq
for char_p_boxed {
#[inline]
fn eq (self: &'_ Self, other: &'_ Self)
-> bool
{
self.as_ref() == other.as_ref()
}
}
impl Clone
for char_p_boxed
{
#[inline]
fn clone (self: &'_ Self)
-> Self
{
self.to_owned()
}
}
}
cfg_std! {
impl From<::std::ffi::CString> for char_p_boxed {
fn from (s: ::std::ffi::CString)
-> char_p_boxed
{
let _assert_valid_utf8 =
::core::str::from_utf8(s.as_bytes())
.unwrap()
;
let s: rust::Box<[u8]> =
s .into_bytes_with_nul()
.into_boxed_slice()
;
unsafe {
Self::from_ptr_unchecked(
ptr::NonNull::new(rust::Box::leak(s).as_mut_ptr())
.unwrap()
)
}
}
}
}