blob: dce7053dda3c9cf91ca5b471b568cbca625cfa9e [file] [log] [blame]
David Tolnaybb3ff5d2020-11-15 19:45:11 -08001use crate::actually_private::Private;
David Tolnay3384c142020-09-14 00:26:47 -04002use alloc::borrow::Cow;
David Tolnayc5a52f92020-09-14 00:43:29 -04003use alloc::string::String;
David Tolnay05db2fb2021-03-18 13:33:27 -07004use core::cmp::Ordering;
David Tolnay3384c142020-09-14 00:26:47 -04005use core::fmt::{self, Debug, Display};
David Tolnay05db2fb2021-03-18 13:33:27 -07006use core::hash::{Hash, Hasher};
David Tolnay95dab1d2020-11-15 14:32:37 -08007use core::marker::{PhantomData, PhantomPinned};
David Tolnaybb3ff5d2020-11-15 19:45:11 -08008use core::mem::MaybeUninit;
David Tolnaya7525d32020-11-15 19:13:26 -08009use core::pin::Pin;
David Tolnay3384c142020-09-14 00:26:47 -040010use core::slice;
11use core::str::{self, Utf8Error};
David Tolnay7db73692019-10-20 14:51:12 -040012
13extern "C" {
David Tolnay0f0162f2020-11-16 23:43:37 -080014 #[link_name = "cxxbridge1$cxx_string$init"]
David Tolnaybb3ff5d2020-11-15 19:45:11 -080015 fn string_init(this: &mut MaybeUninit<CxxString>, ptr: *const u8, len: usize);
David Tolnay0f0162f2020-11-16 23:43:37 -080016 #[link_name = "cxxbridge1$cxx_string$destroy"]
David Tolnaybb3ff5d2020-11-15 19:45:11 -080017 fn string_destroy(this: &mut MaybeUninit<CxxString>);
David Tolnay0f0162f2020-11-16 23:43:37 -080018 #[link_name = "cxxbridge1$cxx_string$data"]
David Tolnay90691f42020-11-14 20:01:46 -080019 fn string_data(this: &CxxString) -> *const u8;
David Tolnay0f0162f2020-11-16 23:43:37 -080020 #[link_name = "cxxbridge1$cxx_string$length"]
David Tolnay90691f42020-11-14 20:01:46 -080021 fn string_length(this: &CxxString) -> usize;
David Tolnay0f0162f2020-11-16 23:43:37 -080022 #[link_name = "cxxbridge1$cxx_string$push"]
David Tolnayde1335f2020-11-15 19:47:02 -080023 fn string_push(this: Pin<&mut CxxString>, ptr: *const u8, len: usize);
David Tolnay7db73692019-10-20 14:51:12 -040024}
25
26/// Binding to C++ `std::string`.
27///
28/// # Invariants
29///
30/// As an invariant of this API and the static analysis of the cxx::bridge
31/// macro, in Rust code we can never obtain a `CxxString` by value. C++'s string
32/// requires a move constructor and may hold internal pointers, which is not
33/// compatible with Rust's move behavior. Instead in Rust code we will only ever
34/// look at a CxxString through a reference or smart pointer, as in `&CxxString`
35/// or `UniquePtr<CxxString>`.
36#[repr(C)]
37pub struct CxxString {
38 _private: [u8; 0],
David Tolnay95dab1d2020-11-15 14:32:37 -080039 _pinned: PhantomData<PhantomPinned>,
David Tolnay7db73692019-10-20 14:51:12 -040040}
41
David Tolnaybb3ff5d2020-11-15 19:45:11 -080042/// Construct a C++ std::string on the Rust stack.
43///
44/// # Syntax
45///
46/// In statement position:
47///
48/// ```
49/// # use cxx::let_cxx_string;
50/// # let expression = "";
51/// let_cxx_string!(var = expression);
52/// ```
53///
54/// The `expression` may have any type that implements `AsRef<[u8]>`. Commonly
55/// it will be a string literal, but for example `&[u8]` and `String` would work
56/// as well.
57///
58/// The macro expands to something resembling `let $var: Pin<&mut CxxString> =
59/// /*???*/;`. The resulting [`Pin`] can be deref'd to `&CxxString` as needed.
60///
61/// # Example
62///
63/// ```
64/// use cxx::{let_cxx_string, CxxString};
65///
66/// fn f(s: &CxxString) {/* ... */}
67///
68/// fn main() {
69/// let_cxx_string!(s = "example");
70/// f(&s);
71/// }
72/// ```
73#[macro_export]
74macro_rules! let_cxx_string {
75 ($var:ident = $value:expr $(,)?) => {
David Tolnayaa153ee2021-02-03 21:15:05 -080076 let mut cxx_stack_string = $crate::private::StackString::new();
David Tolnaybb3ff5d2020-11-15 19:45:11 -080077 #[allow(unused_mut, unused_unsafe)]
David Tolnayc4a3ede2020-12-27 21:45:33 -080078 let mut $var = match $value {
David Tolnayaa153ee2021-02-03 21:15:05 -080079 let_cxx_string => unsafe { cxx_stack_string.init(let_cxx_string) },
David Tolnayc4a3ede2020-12-27 21:45:33 -080080 };
David Tolnaybb3ff5d2020-11-15 19:45:11 -080081 };
82}
83
David Tolnay7db73692019-10-20 14:51:12 -040084impl CxxString {
David Tolnaybb3ff5d2020-11-15 19:45:11 -080085 /// `CxxString` is not constructible via `new`. Instead, use the
86 /// [`let_cxx_string!`] macro.
87 pub fn new<T: Private>() -> Self {
88 unreachable!()
89 }
90
David Tolnay7db73692019-10-20 14:51:12 -040091 /// Returns the length of the string in bytes.
92 ///
93 /// Matches the behavior of C++ [std::string::size][size].
94 ///
95 /// [size]: https://en.cppreference.com/w/cpp/string/basic_string/size
96 pub fn len(&self) -> usize {
97 unsafe { string_length(self) }
98 }
99
100 /// Returns true if `self` has a length of zero bytes.
David Tolnayd7b8a6e2020-04-24 16:22:55 -0700101 ///
102 /// Matches the behavior of C++ [std::string::empty][empty].
103 ///
104 /// [empty]: https://en.cppreference.com/w/cpp/string/basic_string/empty
David Tolnay7db73692019-10-20 14:51:12 -0400105 pub fn is_empty(&self) -> bool {
106 self.len() == 0
107 }
108
109 /// Returns a byte slice of this string's contents.
110 pub fn as_bytes(&self) -> &[u8] {
111 let data = self.as_ptr();
112 let len = self.len();
113 unsafe { slice::from_raw_parts(data, len) }
114 }
115
116 /// Produces a pointer to the first character of the string.
117 ///
118 /// Matches the behavior of C++ [std::string::data][data].
119 ///
120 /// Note that the return type may look like `const char *` but is not a
121 /// `const char *` in the typical C sense, as C++ strings may contain
122 /// internal null bytes. As such, the returned pointer only makes sense as a
David Tolnay3cd990f2020-04-24 16:24:26 -0700123 /// string in combination with the length returned by [`len()`][len].
David Tolnay7db73692019-10-20 14:51:12 -0400124 ///
125 /// [data]: https://en.cppreference.com/w/cpp/string/basic_string/data
David Tolnay3cd990f2020-04-24 16:24:26 -0700126 /// [len]: #method.len
David Tolnay7db73692019-10-20 14:51:12 -0400127 pub fn as_ptr(&self) -> *const u8 {
128 unsafe { string_data(self) }
129 }
130
131 /// Validates that the C++ string contains UTF-8 data and produces a view of
132 /// it as a Rust &amp;str, otherwise an error.
133 pub fn to_str(&self) -> Result<&str, Utf8Error> {
134 str::from_utf8(self.as_bytes())
135 }
136
137 /// If the contents of the C++ string are valid UTF-8, this function returns
138 /// a view as a Cow::Borrowed &amp;str. Otherwise replaces any invalid UTF-8
139 /// sequences with the U+FFFD [replacement character] and returns a
140 /// Cow::Owned String.
141 ///
142 /// [replacement character]: https://doc.rust-lang.org/std/char/constant.REPLACEMENT_CHARACTER.html
143 pub fn to_string_lossy(&self) -> Cow<str> {
144 String::from_utf8_lossy(self.as_bytes())
145 }
David Tolnay90691f42020-11-14 20:01:46 -0800146
147 /// Appends a given string slice onto the end of this C++ string.
David Tolnaya7525d32020-11-15 19:13:26 -0800148 pub fn push_str(self: Pin<&mut Self>, s: &str) {
David Tolnay95e74b32020-11-14 20:16:22 -0800149 self.push_bytes(s.as_bytes());
150 }
151
152 /// Appends arbitrary bytes onto the end of this C++ string.
David Tolnaya7525d32020-11-15 19:13:26 -0800153 pub fn push_bytes(self: Pin<&mut Self>, bytes: &[u8]) {
David Tolnayde1335f2020-11-15 19:47:02 -0800154 unsafe { string_push(self, bytes.as_ptr(), bytes.len()) }
David Tolnay90691f42020-11-14 20:01:46 -0800155 }
David Tolnay7db73692019-10-20 14:51:12 -0400156}
157
158impl Display for CxxString {
159 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
David Tolnayd930a792020-03-25 12:24:40 -0700160 Display::fmt(self.to_string_lossy().as_ref(), f)
David Tolnay7db73692019-10-20 14:51:12 -0400161 }
162}
163
164impl Debug for CxxString {
165 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
David Tolnayd930a792020-03-25 12:24:40 -0700166 Debug::fmt(self.to_string_lossy().as_ref(), f)
David Tolnay7db73692019-10-20 14:51:12 -0400167 }
168}
David Tolnay42ebfa22020-03-25 12:26:22 -0700169
170impl PartialEq for CxxString {
David Tolnay2e43b512021-03-18 13:35:38 -0700171 fn eq(&self, other: &Self) -> bool {
David Tolnay42ebfa22020-03-25 12:26:22 -0700172 self.as_bytes() == other.as_bytes()
173 }
174}
175
176impl PartialEq<CxxString> for str {
177 fn eq(&self, other: &CxxString) -> bool {
178 self.as_bytes() == other.as_bytes()
179 }
180}
181
182impl PartialEq<str> for CxxString {
183 fn eq(&self, other: &str) -> bool {
184 self.as_bytes() == other.as_bytes()
185 }
186}
David Tolnaybb3ff5d2020-11-15 19:45:11 -0800187
b059021327b783f92021-03-19 01:48:36 +0800188impl Eq for CxxString {}
189
190impl PartialOrd for CxxString {
David Tolnay05db2fb2021-03-18 13:33:27 -0700191 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
b059021327b783f92021-03-19 01:48:36 +0800192 self.as_bytes().partial_cmp(other.as_bytes())
193 }
194}
195
b059021327b783f92021-03-19 01:48:36 +0800196impl Ord for CxxString {
David Tolnay05db2fb2021-03-18 13:33:27 -0700197 fn cmp(&self, other: &Self) -> Ordering {
b059021327b783f92021-03-19 01:48:36 +0800198 self.as_bytes().cmp(other.as_bytes())
199 }
200}
201
David Tolnay05db2fb2021-03-18 13:33:27 -0700202impl Hash for CxxString {
203 fn hash<H: Hasher>(&self, state: &mut H) {
204 self.as_bytes().hash(state);
b059021327b783f92021-03-19 01:48:36 +0800205 }
206}
207
David Tolnaybb3ff5d2020-11-15 19:45:11 -0800208#[doc(hidden)]
209#[repr(C)]
210pub struct StackString {
211 // Static assertions in cxx.cc validate that this is large enough and
212 // aligned enough.
David Tolnay0df1fdb2021-01-27 11:26:36 -0800213 space: MaybeUninit<[usize; 8]>,
David Tolnaybb3ff5d2020-11-15 19:45:11 -0800214}
215
216impl StackString {
217 pub fn new() -> Self {
218 StackString {
219 space: MaybeUninit::uninit(),
220 }
221 }
222
223 pub unsafe fn init(&mut self, value: impl AsRef<[u8]>) -> Pin<&mut CxxString> {
224 let value = value.as_ref();
225 let this = &mut *self.space.as_mut_ptr().cast::<MaybeUninit<CxxString>>();
226 string_init(this, value.as_ptr(), value.len());
227 Pin::new_unchecked(&mut *this.as_mut_ptr())
228 }
229}
230
231impl Drop for StackString {
232 fn drop(&mut self) {
233 unsafe {
234 let this = &mut *self.space.as_mut_ptr().cast::<MaybeUninit<CxxString>>();
235 string_destroy(this);
236 }
237 }
238}