-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathstring.rs
More file actions
306 lines (267 loc) · 10.5 KB
/
string.rs
File metadata and controls
306 lines (267 loc) · 10.5 KB
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
// Part of the Crubit project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
extern crate alloc;
extern crate std;
use crate::crubit_cc_std_internal::conversion_function_helpers;
use crate::lossy_utf8::LossyUtf8Display;
use alloc::string::String;
use alloc::vec::Vec;
use bridge_rust::{transmute_abi, CrubitAbi, Decoder, Encoder};
use core::clone::Clone;
use core::cmp::Eq;
use core::cmp::PartialEq;
use core::ffi::c_void;
use core::mem::{ManuallyDrop, MaybeUninit};
use core::ops::Deref;
use core::ptr::NonNull;
use std::fmt::Display;
#[cfg(unix)]
use std::os::unix::ffi::OsStrExt;
/// An owned C++ string. The pointer is guaranteed to be a non-null C++
/// allocated pointer to std::string.
///
/// We make sure that conversion between `string` and `std::string` is O(1), but
/// conversion between `string` and other types like `&str` or `String` can be
/// O(n).
// TODO: Make it mutable?.
// TODO: add a depedency on `crubit_annotate` to use that directly rather than doc attributes.
#[doc = "CRUBIT_ANNOTATE: cpp_type=std::string"]
#[doc = "CRUBIT_ANNOTATE: include_path=<string>"]
#[doc = "CRUBIT_ANNOTATE: cpp_to_rust_converter=cpp_string_to_rust_string"]
#[doc = "CRUBIT_ANNOTATE: rust_to_cpp_converter=rust_string_to_cpp_string"]
#[allow(non_snake_case)]
#[repr(C)]
pub struct string_wrapper {
owned_cpp_string: NonNull<c_void>,
}
pub type string = string_wrapper;
// We have no reason to restrict access to the string data to particular threads.
unsafe impl Send for string_wrapper {}
unsafe impl Sync for string_wrapper {}
impl string_wrapper {
pub fn as_slice(&self) -> &[u8] {
self.as_ref()
}
pub fn to_vec(&self) -> Vec<u8> {
self.as_slice().into()
}
#[cfg(unix)]
pub fn as_os_str(&self) -> &std::ffi::OsStr {
std::ffi::OsStr::from_bytes(&self)
}
#[cfg(unix)]
pub fn to_os_string(&self) -> std::ffi::OsString {
self.as_os_str().into()
}
/// Returns a `*const c_void` pointing to the underlying C++
/// `std::string` object.
///
/// The caller must ensure that the `string` outlives the pointer.
///
/// This method guarantees that for the purpose of the aliasing
/// model, this method does not materialize a reference to the
/// underlying data the string owns, and thus the returned
/// pointer will remain valid when mixed with other calls to
/// `as_void_ptr` and `as_mut_void_ptr`.
pub fn as_void_ptr(&self) -> *const c_void {
self.owned_cpp_string.as_ptr() as *const _
}
/// Returns a `*mut c_void` pointing to the underlying C++
/// `std::string` object.
///
/// The caller must ensure that the `string` outlives the pointer.
///
/// This method guarantees that for the purpose of the aliasing
/// model, this method does not materialize a reference to the
/// underlying data the string owns, and thus the returned
/// pointer will remain valid when mixed with other calls to
/// `as_void_ptr` and `as_mut_void_ptr`.
///
/// However, note that writing to the pointer will invalidate references to
/// the underlying data. For example, the behavior is undefined if the
/// underlying string is mutated through this pointer during the lifetime
/// of a slice as returned by `as_slice`.
pub fn as_mut_void_ptr(&mut self) -> *mut c_void {
self.owned_cpp_string.as_ptr()
}
/// Returns an object that implements `Display` for safely printing strings that may contain
/// non-Unicode data. The Display implementation replaces invalid UTF-8 with the Unicode
/// replacement character (�), and is potentially lossy.
pub fn display(&self) -> impl Display + use<'_> {
LossyUtf8Display(self.as_slice())
}
}
impl PartialEq for string_wrapper {
fn eq(&self, other: &Self) -> bool {
unsafe {
// SAFETY: `owned_cpp_string` is guaranteed to be a non-null C++ allocated
// pointer to std::string.
conversion_function_helpers::StringEqual(
self.owned_cpp_string.as_ptr(),
other.owned_cpp_string.as_ptr(),
)
}
}
}
impl Eq for string_wrapper {}
impl Default for string_wrapper {
fn default() -> Self {
"".into()
}
}
impl Clone for string_wrapper {
fn clone(&self) -> Self {
// SAFETY: `owned_cpp_string` is guaranteed to be a non-null C++ allocated
// pointer to std::string.
let raw_string = unsafe {
conversion_function_helpers::StringCopyOwnedPtr(self.owned_cpp_string.as_ptr())
};
if let Some(ptr) = NonNull::new(raw_string) {
Self { owned_cpp_string: ptr }
} else {
panic!("Failed to copy string");
}
}
}
impl Drop for string_wrapper {
fn drop(&mut self) {
unsafe {
// SAFETY: `owned_cpp_string` is guaranteed to be a non-null C++ allocated
// pointer to std::string.
conversion_function_helpers::StringDelete(self.owned_cpp_string.as_ptr());
}
}
}
impl From<String> for string_wrapper {
fn from(s: String) -> Self {
s.as_bytes().into()
}
}
impl From<&String> for string_wrapper {
fn from(s: &String) -> Self {
s.as_bytes().into()
}
}
impl From<&Vec<u8>> for string_wrapper {
fn from(s: &Vec<u8>) -> Self {
s.as_slice().into()
}
}
impl From<&str> for string_wrapper {
fn from(s: &str) -> Self {
s.as_bytes().into()
}
}
impl From<&[u8]> for string_wrapper {
fn from(s: &[u8]) -> Self {
// SAFETY: Rust slice returns a valid pointer to a buffer of bytes.
let raw_string = unsafe {
conversion_function_helpers::StringCreateFromBuffer(s.as_ptr() as _, s.len())
};
if let Some(ptr) = NonNull::new(raw_string) {
Self { owned_cpp_string: ptr }
} else {
panic!("Failed to create string");
}
}
}
impl Deref for string_wrapper {
type Target = [u8];
fn deref(&self) -> &Self::Target {
let ptr = self.owned_cpp_string.as_ptr();
// SAFETY:
//
// * `owned_cpp_string` is guaranteed to be a non-null C++ allocated pointer to
// std::string so `ptr` is non-null.
// * `StringGetData` returns the pointer of the C++ `std::string::data()`, which
// is guaranteed to be non-null and point to a continuous memory region. Every
// byte in [ptr, ptr + len)) is intialized. (See https://en.cppreference.com/w/cpp/string/basic_string/data)
// * The data is guaranteed to be not mutated because we don't ever mutate
// data() except when accessed via &mut self, which is blocked by Rust borrow
// checker.
// * `len` is guaranteed to be less than `isize::MAX` because C++
// implementations guarantee in practice that the object won't go past the end
// of the address space.
unsafe {
let len = conversion_function_helpers::StringGetSize(ptr);
core::slice::from_raw_parts(conversion_function_helpers::StringGetData(ptr) as _, len)
}
}
}
impl core::convert::AsRef<[u8]> for string_wrapper {
fn as_ref(&self) -> &[u8] {
&*self
}
}
impl core::fmt::Debug for string_wrapper {
// TODO(b/351976622): Make a pretty Debug like std::string(b"\xffhello\xde") or
// similar.
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "cc_std::string_wrapper({:?})", self.as_slice())
}
}
// Allow converting a cc_std::std::string_wrapper reference to a "real" C++ string pointer.
type StringSymbol = forward_declare::symbol!(
"std :: basic_string < char , std :: char_traits < char >, std :: allocator < char >>"
);
impl<'a, Crate> forward_declare::CppCast<*const forward_declare::Incomplete<StringSymbol, Crate>>
for &'a string_wrapper
{
fn cpp_cast(self) -> *const forward_declare::Incomplete<StringSymbol, Crate> {
self.owned_cpp_string.as_ptr() as *const _ as *const _
}
}
impl<'a, Crate> forward_declare::CppCast<*mut forward_declare::Incomplete<StringSymbol, Crate>>
for &'a mut string_wrapper
{
fn cpp_cast(self) -> *mut forward_declare::Incomplete<StringSymbol, Crate> {
self.owned_cpp_string.as_ptr() as *mut _
}
}
/// The Crubit ABI for C++ `std::string`. It is specified as one pointer.
///
/// This pointer should point to a heap allocated `std::string` object, where the pointer is the
/// owner of the allocation. Alternatively, the pointer can be null if and only if the allocation
/// failed, in which case it's okay to panic.
#[derive(Clone, Default)]
pub struct BoxedCppStringAbi;
unsafe impl CrubitAbi for BoxedCppStringAbi {
type Value = string_wrapper;
const SIZE: usize = core::mem::size_of::<*mut c_void>();
fn encode(self, value: Self::Value, encoder: &mut Encoder) {
transmute_abi().encode(ManuallyDrop::new(value).as_mut_void_ptr(), encoder);
}
unsafe fn decode(self, decoder: &mut Decoder) -> Self::Value {
// SAFETY: the caller guarantees that the buffer contains an allocated or null pointer to a
// C++ `std::string` object.
let ptr: *mut c_void = unsafe { transmute_abi().decode(decoder) };
Self::Value {
owned_cpp_string: NonNull::new(ptr).expect("Boxing a std::string shouldn't fail"),
}
}
}
// Void pointer converters are needed for cc_bindings_from_rs.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_string_to_cpp_string(input: *const c_void, output: *mut c_void) {
// SAFETY:
// * `input` is a valid `string_wrapper`.
// * `input.owned_cpp_string` is guaranteed to be a non-null C++ allocated
// pointer to std::string.
// * `output` is a valid C++ `std::string`.
unsafe {
let input = &*(input as *const string_wrapper);
conversion_function_helpers::StringCreateInPlace(output, input.owned_cpp_string.as_ptr());
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn cpp_string_to_rust_string(input: *mut c_void, output: *mut c_void) {
// SAFETY: `input` is a valid `std::string` so it can be safely moved.
let owned_cpp_string = unsafe { conversion_function_helpers::StringMoveOwnedPtr(input) };
if let Some(ptr) = NonNull::new(owned_cpp_string) {
let output = &mut *(output as *mut MaybeUninit<string_wrapper>);
output.as_mut_ptr().write(string_wrapper { owned_cpp_string: ptr });
} else {
panic!("Failed to create owned string");
}
}