use crate::actually_private::Private;
use crate::lossy;
#[cfg(feature = "alloc")]
use alloc::borrow::Cow;
#[cfg(feature = "alloc")]
use alloc::string::String;
use core::cell::UnsafeCell;
use core::cmp::Ordering;
use core::ffi::{CStr, c_char};
use core::fmt::{self, Debug, Display};
use core::panic::RefUnwindSafe;
use core::hash::{Hash, Hasher};
use core::marker::{PhantomData, PhantomPinned};
use core::mem::MaybeUninit;
use core::pin::Pin;
use core::slice;
use core::str::{self, Utf8Error};
unsafe extern "C" {
#[link_name = "cxxbridge1$cxx_string$init"]
fn string_init(this: &mut MaybeUninit<CxxString>, ptr: *const u8, len: usize);
#[link_name = "cxxbridge1$cxx_string$destroy"]
fn string_destroy(this: &mut MaybeUninit<CxxString>);
#[link_name = "cxxbridge1$cxx_string$data"]
fn string_data(this: &CxxString) -> *const u8;
#[link_name = "cxxbridge1$cxx_string$length"]
fn string_length(this: &CxxString) -> usize;
#[link_name = "cxxbridge1$cxx_string$clear"]
fn string_clear(this: Pin<&mut CxxString>);
#[link_name = "cxxbridge1$cxx_string$reserve_total"]
fn string_reserve_total(this: Pin<&mut CxxString>, new_cap: usize);
#[link_name = "cxxbridge1$cxx_string$push"]
fn string_push(this: Pin<&mut CxxString>, ptr: *const u8, len: usize);
}
#[repr(C)]
pub struct CxxString {
#[cfg(not(all(miri, feature = "alloc")))]
_private: [u8; 0],
#[cfg(all(miri, feature = "alloc"))]
_miri: miri::CxxStringRepr,
_pinned: PhantomData<PhantomPinned>,
}
#[macro_export]
macro_rules! let_cxx_string {
($var:ident = $value:expr $(,)?) => {
let cxx_stack_string = $crate::private::StackString::new();
#[allow(unused_mut, unused_unsafe)]
let mut $var = match $value {
let_cxx_string => unsafe { cxx_stack_string.init(let_cxx_string) },
};
#[allow(unused_unsafe)]
let _cxx_stack_string_drop_guard = unsafe { cxx_stack_string.drop_guard() };
};
}
impl CxxString {
pub fn new<T: Private>() -> Self {
unreachable!()
}
pub fn len(&self) -> usize {
unsafe { string_length(self) }
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn as_bytes(&self) -> &[u8] {
let data = self.as_ptr();
let len = self.len();
unsafe { slice::from_raw_parts(data, len) }
}
pub fn as_ptr(&self) -> *const u8 {
unsafe { string_data(self) }
}
pub fn as_c_str(&self) -> &CStr {
unsafe { CStr::from_ptr(self.as_ptr().cast::<c_char>()) }
}
pub fn to_str(&self) -> Result<&str, Utf8Error> {
str::from_utf8(self.as_bytes())
}
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn to_string_lossy(&self) -> Cow<str> {
String::from_utf8_lossy(self.as_bytes())
}
pub fn clear(self: Pin<&mut Self>) {
unsafe { string_clear(self) }
}
pub fn reserve(self: Pin<&mut Self>, additional: usize) {
let new_cap = self
.len()
.checked_add(additional)
.expect("CxxString capacity overflow");
unsafe { string_reserve_total(self, new_cap) }
}
pub fn push_str(self: Pin<&mut Self>, s: &str) {
self.push_bytes(s.as_bytes());
}
pub fn push_bytes(self: Pin<&mut Self>, bytes: &[u8]) {
unsafe { string_push(self, bytes.as_ptr(), bytes.len()) }
}
}
impl Display for CxxString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
lossy::display(self.as_bytes(), f)
}
}
impl Debug for CxxString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
lossy::debug(self.as_bytes(), f)
}
}
impl PartialEq for CxxString {
fn eq(&self, other: &Self) -> bool {
self.as_bytes() == other.as_bytes()
}
}
impl PartialEq<CxxString> for str {
fn eq(&self, other: &CxxString) -> bool {
self.as_bytes() == other.as_bytes()
}
}
impl PartialEq<str> for CxxString {
fn eq(&self, other: &str) -> bool {
self.as_bytes() == other.as_bytes()
}
}
impl Eq for CxxString {}
impl PartialOrd for CxxString {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for CxxString {
fn cmp(&self, other: &Self) -> Ordering {
self.as_bytes().cmp(other.as_bytes())
}
}
impl Hash for CxxString {
fn hash<H: Hasher>(&self, state: &mut H) {
self.as_bytes().hash(state);
}
}
impl fmt::Write for Pin<&mut CxxString> {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.as_mut().push_str(s);
Ok(())
}
}
#[cfg(feature = "std")]
impl std::io::Write for Pin<&mut CxxString> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.as_mut().push_bytes(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[doc(hidden)]
#[repr(C)]
pub struct StackString {
space: UnsafeCell<MaybeUninit<[usize; 8]>>,
}
unsafe impl Sync for StackString {}
impl RefUnwindSafe for StackString {}
impl StackString {
pub fn new() -> Self {
StackString {
space: UnsafeCell::new(MaybeUninit::uninit()),
}
}
#[allow(clippy::mut_from_ref)]
pub unsafe fn init(&self, value: impl AsRef<[u8]>) -> Pin<&mut CxxString> {
let value = value.as_ref();
unsafe {
let this = &mut *self.space.get().cast::<MaybeUninit<CxxString>>();
string_init(this, value.as_ptr(), value.len());
Pin::new_unchecked(&mut *this.as_mut_ptr())
}
}
pub unsafe fn drop_guard(&self) -> impl Drop + '_ {
struct StackStringDropGuard<'a>(&'a StackString);
impl<'a> Drop for StackStringDropGuard<'a> {
fn drop(&mut self) {
unsafe {
let this = &mut *self.0.space.get().cast::<MaybeUninit<CxxString>>();
string_destroy(this);
}
}
}
StackStringDropGuard(self)
}
}
#[cfg(all(miri, feature = "alloc"))]
mod miri {
use super::CxxString;
use alloc::vec::Vec;
use core::mem;
use core::mem::MaybeUninit;
use core::pin::Pin;
use core::ptr;
use core::slice;
pub(super) type CxxStringRepr = [MaybeUninit<u8>; mem::size_of::<Vec<u8>>()];
#[unsafe(export_name = "cxxbridge1$cxx_string$init")]
unsafe extern "C" fn string_init(
this: &mut MaybeUninit<CxxString>,
ptr: *const u8,
len: usize,
) {
unsafe {
this.as_mut_ptr()
.cast::<Vec<u8>>()
.write(slice::from_raw_parts(ptr, len).to_vec());
}
}
#[unsafe(export_name = "cxxbridge1$cxx_string$destroy")]
unsafe extern "C" fn string_destroy(this: &mut MaybeUninit<CxxString>) {
unsafe {
ptr::drop_in_place(this.as_mut_ptr().cast::<Vec<u8>>());
}
}
#[unsafe(export_name = "cxxbridge1$cxx_string$data")]
unsafe extern "C" fn string_data(this: &CxxString) -> *const u8 {
let vec = unsafe { &*ptr::from_ref(this).cast::<Vec<u8>>() };
vec.as_ptr()
}
#[unsafe(export_name = "cxxbridge1$cxx_string$length")]
unsafe extern "C" fn string_length(this: &CxxString) -> usize {
let vec = unsafe { &*ptr::from_ref(this).cast::<Vec<u8>>() };
vec.len()
}
#[unsafe(export_name = "cxxbridge1$cxx_string$clear")]
unsafe extern "C" fn string_clear(this: Pin<&mut CxxString>) {
let vec = unsafe { &mut *ptr::from_mut(this.get_unchecked_mut()).cast::<Vec<u8>>() };
vec.clear();
}
#[unsafe(export_name = "cxxbridge1$cxx_string$reserve_total")]
unsafe extern "C" fn string_reserve_total(this: Pin<&mut CxxString>, new_cap: usize) {
let vec = unsafe { &mut *ptr::from_mut(this.get_unchecked_mut()).cast::<Vec<u8>>() };
vec.reserve(new_cap.saturating_sub(vec.len()));
}
#[unsafe(export_name = "cxxbridge1$cxx_string$push")]
unsafe extern "C" fn string_push(this: Pin<&mut CxxString>, ptr: *const u8, len: usize) {
let vec = unsafe { &mut *ptr::from_mut(this.get_unchecked_mut()).cast::<Vec<u8>>() };
vec.extend_from_slice(unsafe { slice::from_raw_parts(ptr, len) });
}
}