Debian Codegraph @

third_party/rust/ffi-support/src/string.rs

raw
1 /* Copyright 2018-2019 Mozilla Foundation
2 *
3 * Licensed under the Apache License (Version 2.0), or the MIT license,
4 * (the "Licenses") at your option. You may not use this file except in
5 * compliance with one of the Licenses. You may obtain copies of the
6 * Licenses at:
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 * http://opensource.org/licenses/MIT
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the Licenses is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the Licenses for the specific language governing permissions and
15 * limitations under the Licenses. */
16
17 use crate::FfiStr;
18 use std::ffi::CString;
19 use std::os::raw::c_char;
20 use std::ptr;
21
22 /// Convert a rust string into a NUL-terminated utf-8 string suitable for passing to C, or to things
23 /// ABI-compatible with C.
24 ///
25 /// Important: This string must eventually be freed. You may either do that using the
26 /// [`destroy_c_string`] method (or, if you must, by dropping the underlying [`std::ffi::CString`]
27 /// after recovering it via [`std::ffi::CString::from_raw`]).
28 ///
29 /// It's common to want to allow the consumer (e.g. on the "C" side of the FFI) to be allowed to
30 /// free this memory, and the macro [`define_string_destructor!`] may be used to do so.
31 ///
32 /// ## Panics
33 ///
34 /// This function may panic if the argument has an interior null byte. This is fairly rare, but
35 /// is possible in theory.
36 #[inline]
37 pub fn rust_string_to_c(rust_string: impl Into<String>) -> *mut c_char {
38 CString::new(rust_string.into())
39 .expect("Error: Rust string contained an interior null byte.")
40 .into_raw()
41 }
42
43 /// Variant of [`rust_string_to_c`] which takes an Option, and returns null for None.
44 #[inline]
45 pub fn opt_rust_string_to_c(opt_rust_string: Option<impl Into<String>>) -> *mut c_char {
46 if let Some(s) = opt_rust_string {
47 rust_string_to_c(s)
48 } else {
49 ptr::null_mut()
50 }
51 }
52
53 /// Free the memory of a string created by [`rust_string_to_c`] on the rust heap. If `c_string` is
54 /// null, this is a no-op.
55 ///
56 /// See the [`define_string_destructor!`] macro which may be used for exposing this function over
57 /// the FFI.
58 ///
59 /// ## Safety
60 ///
61 /// This is inherently unsafe, since we're deallocating memory. Be sure
62 ///
63 /// - Nobody can use the memory after it's deallocated.
64 /// - The memory was actually allocated on this heap (and it's not a string from the other side of
65 /// the FFI which was allocated on e.g. the C heap).
66 /// - If multiple separate rust libraries are in use (for example, as DLLs) in a single program,
67 /// you must also make sure that the rust library that allocated the memory is also the one
68 /// that frees it.
69 ///
70 /// See documentation for [`define_string_destructor!`], which gives a more complete overview of the
71 /// potential issues.
72 #[inline]
73 pub unsafe fn destroy_c_string(cstring: *mut c_char) {
74 // we're not guaranteed to be in a place where we can complain about this beyond logging,
75 // and there's an obvious way to handle it.
76 if !cstring.is_null() {
77 drop(CString::from_raw(cstring))
78 }
79 }
80
81 /// Convert a null-terminated C string to a rust `str`. This does not take ownership of the string,
82 /// and you should be careful about the lifetime of the resulting string. Note that strings
83 /// containing invalid UTF-8 are replaced with the empty string (for many cases, you will want to
84 /// use [`rust_string_from_c`] instead, which will do a lossy conversion).
85 ///
86 /// If you actually need an owned rust `String`, you're encouraged to use [`rust_string_from_c`],
87 /// which, as mentioned, also behaves better in the face of invalid UTF-8.
88 ///
89 /// ## Safety
90 ///
91 /// This is unsafe because we read from a raw pointer, which may or may not be valid.
92 ///
93 /// We also assume `c_string` is a null terminated string, and have no way of knowing if that's
94 /// actually true. If it's not, we'll read arbitrary memory from the heap until we see a '\0', which
95 /// can result in a enormous number of problems.
96 ///
97 /// ## Panics
98 ///
99 /// Panics if it's argument is null, see [`opt_rust_str_from_c`] for a variant that returns None in
100 /// this case instead.
101 ///
102 /// Note: This means it's forbidden to call this outside of a `call_with_result` (or something else
103 /// that uses [`std::panic::catch_unwind`]), as it is UB to panic across the FFI boundary.
104 #[inline]
105 #[deprecated(since = "0.3.0", note = "Please use FfiStr::as_str instead")]
106 pub unsafe fn rust_str_from_c<'a>(c_string: *const c_char) -> &'a str {
107 FfiStr::from_raw(c_string).as_str()
108 }
109
110 /// Same as `rust_string_from_c`, but returns None if `c_string` is null instead of asserting.
111 ///
112 /// ## Safety
113 ///
114 /// This is unsafe because we read from a raw pointer, which may or may not be valid.
115 ///
116 /// We also assume `c_string` is a null terminated string, and have no way of knowing if that's
117 /// actually true. If it's not, we'll read arbitrary memory from the heap until we see a '\0', which
118 /// can result in a enormous number of problems.
119 #[inline]
120 #[deprecated(since = "0.3.0", note = "Please use FfiStr::as_opt_str instead")]
121 pub unsafe fn opt_rust_str_from_c<'a>(c_string: *const c_char) -> Option<&'a str> {
122 FfiStr::from_raw(c_string).as_opt_str()
123 }
124
125 /// Convert a null-terminated C into an owned rust string, replacing invalid UTF-8 with the
126 /// unicode replacement character.
127 ///
128 /// ## Safety
129 ///
130 /// This is unsafe because we dereference a raw pointer, which may or may not be valid.
131 ///
132 /// We also assume `c_string` is a null terminated string, and have no way of knowing if that's
133 /// actually true. If it's not, we'll read arbitrary memory from the heap until we see a '\0', which
134 /// can result in a enormous number of problems.
135 ///
136 /// ## Panics
137 ///
138 /// Panics if it's argument is null. See also [`opt_rust_string_from_c`], which returns None
139 /// instead.
140 ///
141 /// Note: This means it's forbidden to call this outside of a `call_with_result` (or something else
142 /// that uses `std::panic::catch_unwind`), as it is UB to panic across the FFI boundary.
143 #[inline]
144 #[deprecated(since = "0.3.0", note = "Please use FfiStr::into_string instead")]
145 pub unsafe fn rust_string_from_c(c_string: *const c_char) -> String {
146 FfiStr::from_raw(c_string).into_string()
147 }
148
149 /// Same as `rust_string_from_c`, but returns None if `c_string` is null instead of asserting.
150 ///
151 /// ## Safety
152 ///
153 /// This is unsafe because we dereference a raw pointer, which may or may not be valid.
154 ///
155 /// We also assume `c_string` is a null terminated string, and have no way of knowing if that's
156 /// actually true. If it's not, we'll read arbitrary memory from the heap until we see a '\0', which
157 /// can result in a enormous number of problems.
158 #[inline]
159 #[deprecated(since = "0.3.0", note = "Please use FfiStr::into_opt_string instead")]
160 pub unsafe fn opt_rust_string_from_c(c_string: *const c_char) -> Option<String> {
161 FfiStr::from_raw(c_string).into_opt_string()
162 }