foreign 0.4.0

Conversion between foreign and Rust types
Documentation
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
use std::alloc::Layout;
use std::ffi::{c_char, c_void, CStr, CString};
use std::mem::ManuallyDrop;
use std::ptr;

use crate::foreign::*;
use crate::r#impl::alloc;

impl FreeForeign for str {
    type Foreign = c_char;

    unsafe fn free_foreign(ptr: *mut c_char) {
        libc::free(ptr.cast::<c_void>());
    }
}

impl CloneToForeign for str {
    /// Return a NUL-terminated copy of `self`, allocated with `malloc`.
    ///
    /// # Panics
    ///
    /// Panics if `self` contains a NUL byte, because C code would see a
    /// string truncated at that byte.  This matches the behaviour of
    /// [`into_foreign`](IntoForeign::into_foreign).
    fn clone_to_foreign(&self) -> OwnedPointer<Self> {
        assert!(
            !self.as_bytes().contains(&0),
            "cannot convert a string with an interior NUL byte to a C string"
        );

        let layout = Layout::array::<c_char>(self.len() + 1)
            .expect("string is too large to convert to a C string");
        // SAFETY: self.as_ptr() is guaranteed to point to self.len() bytes;
        // the destination is freshly allocated
        unsafe {
            let p = alloc::<Self::Foreign>(layout);
            ptr::copy_nonoverlapping(self.as_ptr().cast::<c_char>(), p, self.len());
            *p.add(self.len()) = 0;
            OwnedPointer::new(p)
        }
    }
}

impl FreeForeign for CStr {
    type Foreign = c_char;

    unsafe fn free_foreign(ptr: *mut c_char) {
        libc::free(ptr.cast::<c_void>());
    }
}

impl CloneToForeign for CStr {
    fn clone_to_foreign(&self) -> OwnedPointer<Self> {
        let slice = self.to_bytes_with_nul();
        let layout = Layout::array::<c_char>(slice.len())
            .expect("string is too large to convert to a C string");
        // SAFETY: self.as_ptr() is guaranteed to point to self.len() bytes;
        // the destination is freshly allocated
        unsafe {
            let p = alloc::<Self::Foreign>(layout);
            ptr::copy_nonoverlapping(self.as_ptr().cast::<c_char>(), p, slice.len());
            OwnedPointer::new(p)
        }
    }
}

impl BorrowForeign for CStr {
    type Storage<'a> = &'a CStr;

    fn borrow_foreign(&self) -> BorrowedPointer<Self, Self::Storage<'_>> {
        // SAFETY: a CStr is a stable pointer
        unsafe { BorrowedPointer::new_borrowed(self, |raw| (*raw).as_ptr()) }
    }
}

impl FreeForeign for String {
    type Foreign = c_char;

    unsafe fn free_foreign(ptr: *mut c_char) {
        libc::free(ptr.cast::<c_void>());
    }
}

impl CloneToForeign for String {
    /// Return a NUL-terminated copy of `self`, allocated with `malloc`.
    ///
    /// # Panics
    ///
    /// Panics if `self` contains a NUL byte, as for [`str`].
    fn clone_to_foreign(&self) -> OwnedPointer<Self> {
        self.as_str().clone_to_foreign().into()
    }
}

impl FromForeign for String {
    /// Copy the contents of the C string at `p` into a `String`.
    ///
    /// Byte sequences that are not valid UTF-8
    /// are replaced with U+FFFD REPLACEMENT CHARACTER, as in
    /// [`String::from_utf8_lossy`].  (This may change to a
    /// panic in the future).
    unsafe fn cloned_from_foreign(p: *const c_char) -> Self {
        let cstr = CStr::from_ptr(p);
        String::from_utf8_lossy(cstr.to_bytes()).into_owned()
    }
}

impl IntoForeign for String {
    type Storage = Vec<c_char>;

    /// Convert `self` into a NUL-terminated C string, reusing its
    /// allocation instead of copying.
    ///
    /// # Panics
    ///
    /// Panics if `self` contains a NUL byte, because the result would be
    /// truncated when read from C.
    fn into_foreign(self) -> BorrowedMutPointer<Self, Vec<c_char>> {
        CString::new(self).unwrap().into_foreign().into()
    }
}

impl IntoForeign for CString {
    type Storage = Vec<c_char>;

    fn into_foreign(self) -> BorrowedMutPointer<Self, Vec<c_char>> {
        let bytes = self.into_bytes_with_nul();

        // Change u8 to c_char.
        let mut bytes = ManuallyDrop::new(bytes);
        let (ptr, length, capacity) = (bytes.as_mut_ptr(), bytes.len(), bytes.capacity());
        // SAFETY: c_char has the same size and alignment as u8, therefore
        // Vec<u8> and Vec<c_char>'s allocations have the same layout; the
        // original `Vec` is wrapped in a ManuallyDrop to avoid double-free
        // of the storage.
        let bytes: Vec<c_char> = unsafe { Vec::from_raw_parts(ptr.cast(), length, capacity) };
        bytes.into_foreign().into()
    }
}

impl FreeForeign for CString {
    type Foreign = c_char;

    unsafe fn free_foreign(ptr: *mut c_char) {
        libc::free(ptr.cast::<c_void>());
    }
}

impl CloneToForeign for CString {
    fn clone_to_foreign(&self) -> OwnedPointer<Self> {
        self.as_c_str().clone_to_foreign().into()
    }
}

impl FromForeign for CString {
    unsafe fn cloned_from_foreign(p: *const c_char) -> Self {
        CStr::from_ptr(p).to_owned()
    }
}

#[allow(clippy::undocumented_unsafe_blocks)]
#[cfg(test)]
mod tests {
    use std::ffi::{c_char, c_void, CStr, CString};

    use crate::c_str::c_str;
    use crate::foreign::*;

    #[test]
    fn test_cloned_from_foreign_string() {
        let s = "Hello, world!".to_string();
        let cstr = c_str!("Hello, world!");
        let cloned = unsafe { String::cloned_from_foreign(cstr.as_ptr()) };
        assert_eq!(s, cloned);
    }

    #[test]
    fn test_cloned_from_foreign_cstring() {
        let s = CString::new("Hello, world!").unwrap();
        let cloned = s.clone_to_foreign();
        let copy = unsafe { CString::cloned_from_foreign(cloned.as_ptr()) };
        assert_ne!(copy.as_ptr(), cloned.as_ptr());
        assert_ne!(copy.as_ptr(), s.as_ptr());
        assert_eq!(copy, s);
    }

    #[test]
    fn test_from_foreign_string() {
        let s = "Hello, world!".to_string();
        let cloned = s.clone_to_foreign_ptr();
        let copy = unsafe { String::from_foreign(cloned) };
        assert_eq!(s, copy);
    }

    #[test]
    fn test_owned_pointer_into() {
        let s = "Hello, world!";
        let cloned: OwnedPointer<String> = s.clone_to_foreign().into();
        let copy = cloned.into_native();
        assert_eq!(s, copy);
    }

    #[test]
    fn test_owned_pointer_into_unsized() {
        // The target of into() need not be Sized.  Only from() used to
        // accept an unsized type, so the two spellings disagreed.
        let s = "Hello, world!";
        let via_into: OwnedPointer<CStr> = s.clone_to_foreign().into();
        let via_from = OwnedPointer::<CStr>::from(s.clone_to_foreign());
        unsafe {
            assert_eq!(libc::strlen(via_into.as_ptr()), s.len());
            assert_eq!(libc::strlen(via_from.as_ptr()), s.len());
        }
    }

    #[test]
    fn test_owned_pointer_into_native() {
        let s = "Hello, world!".to_string();
        let cloned = s.clone_to_foreign();
        let copy = cloned.into_native();
        assert_eq!(s, copy);
    }

    #[test]
    fn test_ptr_into_native() {
        let s = "Hello, world!".to_string();
        let cloned = s.clone_to_foreign_ptr();
        let copy: String = unsafe { cloned.into_native() };
        assert_eq!(s, copy);

        // This is why type bounds are needed... they aren't for
        // OwnedPointer::into_native
        let cloned = s.clone_to_foreign_ptr();
        let copy: c_char = unsafe { cloned.into_native() };
        assert_eq!(s.as_bytes()[0], copy as u8);
    }

    #[test]
    #[should_panic(expected = "interior NUL")]
    fn test_clone_to_foreign_str_interior_nul() {
        let _ = "Hello\0world!".clone_to_foreign();
    }

    #[test]
    #[should_panic(expected = "interior NUL")]
    fn test_clone_to_foreign_string_interior_nul() {
        let _ = "Hello\0world!".to_string().clone_to_foreign();
    }

    #[test]
    fn test_clone_to_foreign_str() {
        let s = "Hello, world!";
        let p = c_str!("Hello, world!").as_ptr();
        let cloned = s.clone_to_foreign();
        unsafe {
            let len = libc::strlen(cloned.as_ptr());
            assert_eq!(len, s.len());
            assert_eq!(
                libc::memcmp(
                    cloned.as_ptr().cast::<c_void>(),
                    p.cast::<c_void>(),
                    len + 1
                ),
                0
            );
        }
    }

    #[test]
    fn test_into_foreign_cstring() {
        let s = c_str!("Hello, world!").to_owned();
        let p = c_str!("Hello, world!");
        let mut consumed = s.into_foreign();
        unsafe {
            let len = libc::strlen(consumed.as_ptr());
            assert_eq!(len, p.to_bytes().len());
            assert_eq!(
                libc::memcmp(
                    consumed.as_ptr().cast::<c_void>(),
                    p.as_ptr().cast::<c_void>(),
                    len + 1
                ),
                0
            );

            *consumed.as_mut_ptr().offset(5) = 0;
            assert_eq!(String::cloned_from_foreign(consumed.as_ptr()), "Hello");
        }
    }

    #[test]
    fn test_into_foreign_string() {
        let s = "Hello, world!".to_string();
        let p = c_str!("Hello, world!");
        let mut consumed = s.into_foreign();
        unsafe {
            let len = libc::strlen(consumed.as_ptr());
            assert_eq!(len, p.to_bytes().len());
            assert_eq!(
                libc::memcmp(
                    consumed.as_ptr().cast::<c_void>(),
                    p.as_ptr().cast::<c_void>(),
                    len + 1
                ),
                0
            );

            *consumed.as_mut_ptr().offset(5) = 0;
            assert_eq!(String::cloned_from_foreign(consumed.as_ptr()), "Hello");
        }
    }

    #[test]
    fn test_borrowed_pointer_clone_to_foreign() {
        let s = CString::new("Hello, world!").unwrap();

        // the result is an OwnedPointer<BorrowedPointer<..>>, but its Foreign
        // is the same, so it never has to be named or converted
        let cloned = s.borrow_foreign().clone_to_foreign();
        assert_ne!(cloned.as_ptr(), s.as_ptr());
        unsafe { assert_eq!(libc::strlen(cloned.as_ptr()), s.to_bytes().len()) };

        // ...and converting is available when it does have to be named
        let cloned: OwnedPointer<CStr> = s.borrow_foreign().clone_to_foreign().into();
        unsafe { assert_eq!(libc::strlen(cloned.as_ptr()), s.to_bytes().len()) };

        // the handoff case: a *mut, with no conversion at all
        let p = s.borrow_foreign().clone_to_foreign_ptr();
        unsafe {
            assert_eq!(libc::strlen(p), s.to_bytes().len());
            libc::free(p.cast::<c_void>());
        }
    }

    #[test]
    fn test_clone_to_foreign_cstr() {
        let s: &CStr = c_str!("Hello, world!");
        let cloned = s.clone_to_foreign();
        unsafe {
            let len = libc::strlen(cloned.as_ptr());
            assert_eq!(len, s.to_bytes().len());
            assert_eq!(
                libc::memcmp(
                    cloned.as_ptr().cast::<c_void>(),
                    s.as_ptr().cast::<c_void>(),
                    len + 1
                ),
                0
            );
        }
    }

    #[test]
    fn test_clone_to_foreign_bytes() {
        let s = b"Hello, world!\0";
        let cloned = s.clone_to_foreign();
        unsafe {
            let len = libc::strlen(cloned.as_ptr().cast::<c_char>());
            assert_eq!(len, s.len() - 1);
            assert_eq!(
                libc::memcmp(
                    cloned.as_ptr().cast::<c_void>(),
                    s.as_ptr().cast::<c_void>(),
                    len + 1
                ),
                0
            );
        }
    }

    #[test]
    fn test_clone_to_foreign_cstring() {
        let s = CString::new("Hello, world!").unwrap();
        let cloned = s.clone_to_foreign();
        unsafe {
            let len = libc::strlen(cloned.as_ptr());
            assert_eq!(len, s.to_bytes().len());
            assert_ne!(s.as_ptr(), cloned.as_ptr());
            assert_eq!(
                libc::memcmp(
                    cloned.as_ptr().cast::<c_void>(),
                    s.as_ptr().cast::<c_void>(),
                    len + 1
                ),
                0
            );
        }
    }

    #[test]
    fn test_clone_to_foreign_string() {
        let s = "Hello, world!".to_string();
        let cstr = c_str!("Hello, world!");
        let cloned = s.clone_to_foreign();
        unsafe {
            let len = libc::strlen(cloned.as_ptr());
            assert_eq!(len, s.len());
            assert_eq!(
                libc::memcmp(
                    cloned.as_ptr().cast::<c_void>(),
                    cstr.as_ptr().cast::<c_void>(),
                    len + 1
                ),
                0
            );
        }
    }
}