diff options
Diffstat (limited to 'vendor/cxx/src')
35 files changed, 0 insertions, 4289 deletions
diff --git a/vendor/cxx/src/c_char.rs b/vendor/cxx/src/c_char.rs deleted file mode 100644 index 333d8491c..000000000 --- a/vendor/cxx/src/c_char.rs +++ /dev/null @@ -1,69 +0,0 @@ -#[allow(missing_docs)] -pub type c_char = c_char_definition::c_char; - -// Validate that our definition is consistent with libstd's definition, without -// introducing a dependency on libstd in ordinary builds. -#[cfg(all(test, feature = "std"))] -const _: self::c_char = 0 as std::os::raw::c_char; - -#[allow(dead_code)] -mod c_char_definition { - // These are the targets on which c_char is unsigned. - #[cfg(any( - all( - target_os = "linux", - any( - target_arch = "aarch64", - target_arch = "arm", - target_arch = "hexagon", - target_arch = "powerpc", - target_arch = "powerpc64", - target_arch = "s390x", - target_arch = "riscv64", - target_arch = "riscv32" - ) - ), - all( - target_os = "android", - any(target_arch = "aarch64", target_arch = "arm") - ), - all(target_os = "l4re", target_arch = "x86_64"), - all( - target_os = "freebsd", - any( - target_arch = "aarch64", - target_arch = "arm", - target_arch = "powerpc", - target_arch = "powerpc64", - target_arch = "riscv64" - ) - ), - all( - target_os = "netbsd", - any(target_arch = "aarch64", target_arch = "arm", target_arch = "powerpc") - ), - all(target_os = "openbsd", target_arch = "aarch64"), - all( - target_os = "vxworks", - any( - target_arch = "aarch64", - target_arch = "arm", - target_arch = "powerpc64", - target_arch = "powerpc" - ) - ), - all(target_os = "fuchsia", target_arch = "aarch64") - ))] - pub use self::unsigned::c_char; - - // On every other target, c_char is signed. - pub use self::signed::*; - - mod unsigned { - pub type c_char = u8; - } - - mod signed { - pub type c_char = i8; - } -} diff --git a/vendor/cxx/src/cxx.cc b/vendor/cxx/src/cxx.cc deleted file mode 100644 index 4958eb08b..000000000 --- a/vendor/cxx/src/cxx.cc +++ /dev/null @@ -1,793 +0,0 @@ -#include "../include/cxx.h" -#include <cstring> -#include <iostream> -#include <memory> - -extern "C" { -void cxxbridge1$cxx_string$init(std::string *s, const std::uint8_t *ptr, - std::size_t len) noexcept { - new (s) std::string(reinterpret_cast<const char *>(ptr), len); -} - -void cxxbridge1$cxx_string$destroy(std::string *s) noexcept { - using std::string; - s->~string(); -} - -const char *cxxbridge1$cxx_string$data(const std::string &s) noexcept { - return s.data(); -} - -std::size_t cxxbridge1$cxx_string$length(const std::string &s) noexcept { - return s.length(); -} - -void cxxbridge1$cxx_string$clear(std::string &s) noexcept { s.clear(); } - -void cxxbridge1$cxx_string$reserve_total(std::string &s, - size_t new_cap) noexcept { - s.reserve(new_cap); -} - -void cxxbridge1$cxx_string$push(std::string &s, const std::uint8_t *ptr, - std::size_t len) noexcept { - s.append(reinterpret_cast<const char *>(ptr), len); -} - -// rust::String -void cxxbridge1$string$new(rust::String *self) noexcept; -void cxxbridge1$string$clone(rust::String *self, - const rust::String &other) noexcept; -bool cxxbridge1$string$from_utf8(rust::String *self, const char *ptr, - std::size_t len) noexcept; -void cxxbridge1$string$from_utf8_lossy(rust::String *self, const char *ptr, - std::size_t len) noexcept; -bool cxxbridge1$string$from_utf16(rust::String *self, const char16_t *ptr, - std::size_t len) noexcept; -void cxxbridge1$string$from_utf16_lossy(rust::String *self, const char16_t *ptr, - std::size_t len) noexcept; -void cxxbridge1$string$drop(rust::String *self) noexcept; -const char *cxxbridge1$string$ptr(const rust::String *self) noexcept; -std::size_t cxxbridge1$string$len(const rust::String *self) noexcept; -std::size_t cxxbridge1$string$capacity(const rust::String *self) noexcept; -void cxxbridge1$string$reserve_additional(rust::String *self, - size_t additional) noexcept; -void cxxbridge1$string$reserve_total(rust::String *self, - size_t new_cap) noexcept; - -// rust::Str -void cxxbridge1$str$new(rust::Str *self) noexcept; -void cxxbridge1$str$ref(rust::Str *self, const rust::String *string) noexcept; -bool cxxbridge1$str$from(rust::Str *self, const char *ptr, - std::size_t len) noexcept; -const char *cxxbridge1$str$ptr(const rust::Str *self) noexcept; -std::size_t cxxbridge1$str$len(const rust::Str *self) noexcept; - -// rust::Slice -void cxxbridge1$slice$new(void *self, const void *ptr, - std::size_t len) noexcept; -void *cxxbridge1$slice$ptr(const void *self) noexcept; -std::size_t cxxbridge1$slice$len(const void *self) noexcept; -} // extern "C" - -namespace rust { -inline namespace cxxbridge1 { - -template <typename Exception> -void panic [[noreturn]] (const char *msg) { -#if defined(RUST_CXX_NO_EXCEPTIONS) - std::cerr << "Error: " << msg << ". Aborting." << std::endl; - std::terminate(); -#else - throw Exception(msg); -#endif -} - -template void panic<std::out_of_range> [[noreturn]] (const char *msg); - -template <typename T> -static bool is_aligned(const void *ptr) noexcept { - auto iptr = reinterpret_cast<std::uintptr_t>(ptr); - return !(iptr % alignof(T)); -} - -String::String() noexcept { cxxbridge1$string$new(this); } - -String::String(const String &other) noexcept { - cxxbridge1$string$clone(this, other); -} - -String::String(String &&other) noexcept : repr(other.repr) { - cxxbridge1$string$new(&other); -} - -String::~String() noexcept { cxxbridge1$string$drop(this); } - -static void initString(String *self, const char *s, std::size_t len) { - if (!cxxbridge1$string$from_utf8(self, s, len)) { - panic<std::invalid_argument>("data for rust::String is not utf-8"); - } -} - -static void initString(String *self, const char16_t *s, std::size_t len) { - if (!cxxbridge1$string$from_utf16(self, s, len)) { - panic<std::invalid_argument>("data for rust::String is not utf-16"); - } -} - -String::String(const std::string &s) { initString(this, s.data(), s.length()); } - -String::String(const char *s) { - assert(s != nullptr); - initString(this, s, std::strlen(s)); -} - -String::String(const char *s, std::size_t len) { - assert(s != nullptr || len == 0); - initString(this, - s == nullptr && len == 0 ? reinterpret_cast<const char *>(1) : s, - len); -} - -String::String(const char16_t *s) { - assert(s != nullptr); - assert(is_aligned<char16_t>(s)); - initString(this, s, std::char_traits<char16_t>::length(s)); -} - -String::String(const char16_t *s, std::size_t len) { - assert(s != nullptr || len == 0); - assert(is_aligned<char16_t>(s)); - initString(this, - s == nullptr && len == 0 ? reinterpret_cast<const char16_t *>(2) - : s, - len); -} - -struct String::lossy_t {}; - -String::String(lossy_t, const char *s, std::size_t len) noexcept { - cxxbridge1$string$from_utf8_lossy( - this, s == nullptr && len == 0 ? reinterpret_cast<const char *>(1) : s, - len); -} - -String::String(lossy_t, const char16_t *s, std::size_t len) noexcept { - cxxbridge1$string$from_utf16_lossy( - this, - s == nullptr && len == 0 ? reinterpret_cast<const char16_t *>(2) : s, - len); -} - -String String::lossy(const std::string &s) noexcept { - return String::lossy(s.data(), s.length()); -} - -String String::lossy(const char *s) noexcept { - assert(s != nullptr); - return String::lossy(s, std::strlen(s)); -} - -String String::lossy(const char *s, std::size_t len) noexcept { - assert(s != nullptr || len == 0); - return String(lossy_t{}, s, len); -} - -String String::lossy(const char16_t *s) noexcept { - assert(s != nullptr); - assert(is_aligned<char16_t>(s)); - return String(lossy_t{}, s, std::char_traits<char16_t>::length(s)); -} - -String String::lossy(const char16_t *s, std::size_t len) noexcept { - assert(s != nullptr || len == 0); - assert(is_aligned<char16_t>(s)); - return String(lossy_t{}, s, len); -} - -String &String::operator=(const String &other) &noexcept { - if (this != &other) { - cxxbridge1$string$drop(this); - cxxbridge1$string$clone(this, other); - } - return *this; -} - -String &String::operator=(String &&other) &noexcept { - cxxbridge1$string$drop(this); - this->repr = other.repr; - cxxbridge1$string$new(&other); - return *this; -} - -String::operator std::string() const { - return std::string(this->data(), this->size()); -} - -const char *String::data() const noexcept { - return cxxbridge1$string$ptr(this); -} - -std::size_t String::size() const noexcept { - return cxxbridge1$string$len(this); -} - -std::size_t String::length() const noexcept { - return cxxbridge1$string$len(this); -} - -bool String::empty() const noexcept { return this->size() == 0; } - -const char *String::c_str() noexcept { - auto len = this->length(); - cxxbridge1$string$reserve_additional(this, 1); - auto ptr = this->data(); - const_cast<char *>(ptr)[len] = '\0'; - return ptr; -} - -std::size_t String::capacity() const noexcept { - return cxxbridge1$string$capacity(this); -} - -void String::reserve(std::size_t new_cap) noexcept { - cxxbridge1$string$reserve_total(this, new_cap); -} - -String::iterator String::begin() noexcept { - return const_cast<char *>(this->data()); -} - -String::iterator String::end() noexcept { - return const_cast<char *>(this->data()) + this->size(); -} - -String::const_iterator String::begin() const noexcept { return this->cbegin(); } - -String::const_iterator String::end() const noexcept { return this->cend(); } - -String::const_iterator String::cbegin() const noexcept { return this->data(); } - -String::const_iterator String::cend() const noexcept { - return this->data() + this->size(); -} - -bool String::operator==(const String &rhs) const noexcept { - return rust::Str(*this) == rust::Str(rhs); -} - -bool String::operator!=(const String &rhs) const noexcept { - return rust::Str(*this) != rust::Str(rhs); -} - -bool String::operator<(const String &rhs) const noexcept { - return rust::Str(*this) < rust::Str(rhs); -} - -bool String::operator<=(const String &rhs) const noexcept { - return rust::Str(*this) <= rust::Str(rhs); -} - -bool String::operator>(const String &rhs) const noexcept { - return rust::Str(*this) > rust::Str(rhs); -} - -bool String::operator>=(const String &rhs) const noexcept { - return rust::Str(*this) >= rust::Str(rhs); -} - -void String::swap(String &rhs) noexcept { - using std::swap; - swap(this->repr, rhs.repr); -} - -String::String(unsafe_bitcopy_t, const String &bits) noexcept - : repr(bits.repr) {} - -std::ostream &operator<<(std::ostream &os, const String &s) { - os.write(s.data(), s.size()); - return os; -} - -Str::Str() noexcept { cxxbridge1$str$new(this); } - -Str::Str(const String &s) noexcept { cxxbridge1$str$ref(this, &s); } - -static void initStr(Str *self, const char *ptr, std::size_t len) { - if (!cxxbridge1$str$from(self, ptr, len)) { - panic<std::invalid_argument>("data for rust::Str is not utf-8"); - } -} - -Str::Str(const std::string &s) { initStr(this, s.data(), s.length()); } - -Str::Str(const char *s) { - assert(s != nullptr); - initStr(this, s, std::strlen(s)); -} - -Str::Str(const char *s, std::size_t len) { - assert(s != nullptr || len == 0); - initStr(this, - s == nullptr && len == 0 ? reinterpret_cast<const char *>(1) : s, - len); -} - -Str::operator std::string() const { - return std::string(this->data(), this->size()); -} - -const char *Str::data() const noexcept { return cxxbridge1$str$ptr(this); } - -std::size_t Str::size() const noexcept { return cxxbridge1$str$len(this); } - -std::size_t Str::length() const noexcept { return this->size(); } - -bool Str::empty() const noexcept { return this->size() == 0; } - -Str::const_iterator Str::begin() const noexcept { return this->cbegin(); } - -Str::const_iterator Str::end() const noexcept { return this->cend(); } - -Str::const_iterator Str::cbegin() const noexcept { return this->data(); } - -Str::const_iterator Str::cend() const noexcept { - return this->data() + this->size(); -} - -bool Str::operator==(const Str &rhs) const noexcept { - return this->size() == rhs.size() && - std::equal(this->begin(), this->end(), rhs.begin()); -} - -bool Str::operator!=(const Str &rhs) const noexcept { return !(*this == rhs); } - -bool Str::operator<(const Str &rhs) const noexcept { - return std::lexicographical_compare(this->begin(), this->end(), rhs.begin(), - rhs.end()); -} - -bool Str::operator<=(const Str &rhs) const noexcept { - // std::mismatch(this->begin(), this->end(), rhs.begin(), rhs.end()), except - // without Undefined Behavior on C++11 if rhs is shorter than *this. - const_iterator liter = this->begin(), lend = this->end(), riter = rhs.begin(), - rend = rhs.end(); - while (liter != lend && riter != rend && *liter == *riter) { - ++liter, ++riter; - } - if (liter == lend) { - return true; // equal or *this is a prefix of rhs - } else if (riter == rend) { - return false; // rhs is a prefix of *this - } else { - return *liter <= *riter; - } -} - -bool Str::operator>(const Str &rhs) const noexcept { return rhs < *this; } - -bool Str::operator>=(const Str &rhs) const noexcept { return rhs <= *this; } - -void Str::swap(Str &rhs) noexcept { - using std::swap; - swap(this->repr, rhs.repr); -} - -std::ostream &operator<<(std::ostream &os, const Str &s) { - os.write(s.data(), s.size()); - return os; -} - -void sliceInit(void *self, const void *ptr, std::size_t len) noexcept { - cxxbridge1$slice$new(self, ptr, len); -} - -void *slicePtr(const void *self) noexcept { return cxxbridge1$slice$ptr(self); } - -std::size_t sliceLen(const void *self) noexcept { - return cxxbridge1$slice$len(self); -} - -// Rust specifies that usize is ABI compatible with C's uintptr_t. -// https://rust-lang.github.io/unsafe-code-guidelines/layout/scalars.html#isize-and-usize -// However there is no direct Rust equivalent for size_t. C does not guarantee -// that size_t and uintptr_t are compatible. In practice though, on all -// platforms supported by Rust, they are identical for ABI purposes. See the -// libc crate which unconditionally defines libc::size_t = usize. We expect the -// same here and these assertions are just here to explicitly document that. -// *Note that no assumption is made about C++ name mangling of signatures -// containing these types, not here nor anywhere in CXX.* -static_assert(sizeof(std::size_t) == sizeof(std::uintptr_t), - "unsupported size_t size"); -static_assert(alignof(std::size_t) == alignof(std::uintptr_t), - "unsupported size_t alignment"); -static_assert(sizeof(rust::isize) == sizeof(std::intptr_t), - "unsupported ssize_t size"); -static_assert(alignof(rust::isize) == alignof(std::intptr_t), - "unsupported ssize_t alignment"); - -static_assert(std::is_trivially_copy_constructible<Str>::value, - "trivial Str(const Str &)"); -static_assert(std::is_trivially_copy_assignable<Str>::value, - "trivial operator=(const Str &)"); -static_assert(std::is_trivially_destructible<Str>::value, "trivial ~Str()"); - -static_assert( - std::is_trivially_copy_constructible<Slice<const std::uint8_t>>::value, - "trivial Slice(const Slice &)"); -static_assert( - std::is_trivially_move_constructible<Slice<const std::uint8_t>>::value, - "trivial Slice(Slice &&)"); -static_assert( - std::is_trivially_copy_assignable<Slice<const std::uint8_t>>::value, - "trivial Slice::operator=(const Slice &) for const slices"); -static_assert( - std::is_trivially_move_assignable<Slice<const std::uint8_t>>::value, - "trivial Slice::operator=(Slice &&)"); -static_assert(std::is_trivially_destructible<Slice<const std::uint8_t>>::value, - "trivial ~Slice()"); - -static_assert(std::is_trivially_copy_constructible<Slice<std::uint8_t>>::value, - "trivial Slice(const Slice &)"); -static_assert(std::is_trivially_move_constructible<Slice<std::uint8_t>>::value, - "trivial Slice(Slice &&)"); -static_assert(!std::is_copy_assignable<Slice<std::uint8_t>>::value, - "delete Slice::operator=(const Slice &) for mut slices"); -static_assert(std::is_trivially_move_assignable<Slice<std::uint8_t>>::value, - "trivial Slice::operator=(Slice &&)"); -static_assert(std::is_trivially_destructible<Slice<std::uint8_t>>::value, - "trivial ~Slice()"); - -static_assert(std::is_same<Vec<std::uint8_t>::const_iterator, - Vec<const std::uint8_t>::iterator>::value, - "Vec<T>::const_iterator == Vec<const T>::iterator"); -static_assert(std::is_same<Vec<const std::uint8_t>::const_iterator, - Vec<const std::uint8_t>::iterator>::value, - "Vec<const T>::const_iterator == Vec<const T>::iterator"); -static_assert(!std::is_same<Vec<std::uint8_t>::const_iterator, - Vec<std::uint8_t>::iterator>::value, - "Vec<T>::const_iterator != Vec<T>::iterator"); - -static const char *errorCopy(const char *ptr, std::size_t len) { - char *copy = new char[len]; - std::memcpy(copy, ptr, len); - return copy; -} - -extern "C" { -const char *cxxbridge1$error(const char *ptr, std::size_t len) noexcept { - return errorCopy(ptr, len); -} -} // extern "C" - -Error::Error(const Error &other) - : std::exception(other), - msg(other.msg ? errorCopy(other.msg, other.len) : nullptr), - len(other.len) {} - -Error::Error(Error &&other) noexcept - : std::exception(std::move(other)), msg(other.msg), len(other.len) { - other.msg = nullptr; - other.len = 0; -} - -Error::~Error() noexcept { delete[] this->msg; } - -Error &Error::operator=(const Error &other) & { - if (this != &other) { - std::exception::operator=(other); - delete[] this->msg; - this->msg = nullptr; - if (other.msg) { - this->msg = errorCopy(other.msg, other.len); - this->len = other.len; - } - } - return *this; -} - -Error &Error::operator=(Error &&other) &noexcept { - std::exception::operator=(std::move(other)); - delete[] this->msg; - this->msg = other.msg; - this->len = other.len; - other.msg = nullptr; - other.len = 0; - return *this; -} - -const char *Error::what() const noexcept { return this->msg; } - -namespace { -template <typename T> -union MaybeUninit { - T value; - MaybeUninit() {} - ~MaybeUninit() {} -}; -} // namespace - -namespace repr { -struct PtrLen final { - void *ptr; - std::size_t len; -}; -} // namespace repr - -extern "C" { -repr::PtrLen cxxbridge1$exception(const char *, std::size_t len) noexcept; -} - -namespace detail { -// On some platforms size_t is the same C++ type as one of the sized integer -// types; on others it is a distinct type. Only in the latter case do we need to -// define a specialized impl of rust::Vec<size_t>, because in the former case it -// would collide with one of the other specializations. -using usize_if_unique = - typename std::conditional<std::is_same<size_t, uint64_t>::value || - std::is_same<size_t, uint32_t>::value, - struct usize_ignore, size_t>::type; -using isize_if_unique = - typename std::conditional<std::is_same<rust::isize, int64_t>::value || - std::is_same<rust::isize, int32_t>::value, - struct isize_ignore, rust::isize>::type; - -class Fail final { - repr::PtrLen &throw$; - -public: - Fail(repr::PtrLen &throw$) noexcept : throw$(throw$) {} - void operator()(const char *) noexcept; - void operator()(const std::string &) noexcept; -}; - -void Fail::operator()(const char *catch$) noexcept { - throw$ = cxxbridge1$exception(catch$, std::strlen(catch$)); -} - -void Fail::operator()(const std::string &catch$) noexcept { - throw$ = cxxbridge1$exception(catch$.data(), catch$.length()); -} -} // namespace detail - -} // namespace cxxbridge1 -} // namespace rust - -namespace { -template <typename T> -void destroy(T *ptr) { - ptr->~T(); -} -} // namespace - -extern "C" { -void cxxbridge1$unique_ptr$std$string$null( - std::unique_ptr<std::string> *ptr) noexcept { - new (ptr) std::unique_ptr<std::string>(); -} -void cxxbridge1$unique_ptr$std$string$raw(std::unique_ptr<std::string> *ptr, - std::string *raw) noexcept { - new (ptr) std::unique_ptr<std::string>(raw); -} -const std::string *cxxbridge1$unique_ptr$std$string$get( - const std::unique_ptr<std::string> &ptr) noexcept { - return ptr.get(); -} -std::string *cxxbridge1$unique_ptr$std$string$release( - std::unique_ptr<std::string> &ptr) noexcept { - return ptr.release(); -} -void cxxbridge1$unique_ptr$std$string$drop( - std::unique_ptr<std::string> *ptr) noexcept { - ptr->~unique_ptr(); -} -} // extern "C" - -namespace { -const std::size_t kMaxExpectedWordsInString = 8; -static_assert(alignof(std::string) <= alignof(void *), - "unexpectedly large std::string alignment"); -static_assert(sizeof(std::string) <= kMaxExpectedWordsInString * sizeof(void *), - "unexpectedly large std::string size"); -} // namespace - -#define STD_VECTOR_OPS(RUST_TYPE, CXX_TYPE) \ - std::size_t cxxbridge1$std$vector$##RUST_TYPE##$size( \ - const std::vector<CXX_TYPE> &s) noexcept { \ - return s.size(); \ - } \ - CXX_TYPE *cxxbridge1$std$vector$##RUST_TYPE##$get_unchecked( \ - std::vector<CXX_TYPE> *s, std::size_t pos) noexcept { \ - return &(*s)[pos]; \ - } \ - void cxxbridge1$unique_ptr$std$vector$##RUST_TYPE##$null( \ - std::unique_ptr<std::vector<CXX_TYPE>> *ptr) noexcept { \ - new (ptr) std::unique_ptr<std::vector<CXX_TYPE>>(); \ - } \ - void cxxbridge1$unique_ptr$std$vector$##RUST_TYPE##$raw( \ - std::unique_ptr<std::vector<CXX_TYPE>> *ptr, \ - std::vector<CXX_TYPE> *raw) noexcept { \ - new (ptr) std::unique_ptr<std::vector<CXX_TYPE>>(raw); \ - } \ - const std::vector<CXX_TYPE> \ - *cxxbridge1$unique_ptr$std$vector$##RUST_TYPE##$get( \ - const std::unique_ptr<std::vector<CXX_TYPE>> &ptr) noexcept { \ - return ptr.get(); \ - } \ - std::vector<CXX_TYPE> \ - *cxxbridge1$unique_ptr$std$vector$##RUST_TYPE##$release( \ - std::unique_ptr<std::vector<CXX_TYPE>> &ptr) noexcept { \ - return ptr.release(); \ - } \ - void cxxbridge1$unique_ptr$std$vector$##RUST_TYPE##$drop( \ - std::unique_ptr<std::vector<CXX_TYPE>> *ptr) noexcept { \ - ptr->~unique_ptr(); \ - } - -#define STD_VECTOR_TRIVIAL_OPS(RUST_TYPE, CXX_TYPE) \ - void cxxbridge1$std$vector$##RUST_TYPE##$push_back( \ - std::vector<CXX_TYPE> *v, CXX_TYPE *value) noexcept { \ - v->push_back(std::move(*value)); \ - destroy(value); \ - } \ - void cxxbridge1$std$vector$##RUST_TYPE##$pop_back(std::vector<CXX_TYPE> *v, \ - CXX_TYPE *out) noexcept { \ - new (out) CXX_TYPE(std::move(v->back())); \ - v->pop_back(); \ - } - -#define RUST_VEC_EXTERNS(RUST_TYPE, CXX_TYPE) \ - void cxxbridge1$rust_vec$##RUST_TYPE##$new( \ - rust::Vec<CXX_TYPE> *ptr) noexcept; \ - void cxxbridge1$rust_vec$##RUST_TYPE##$drop( \ - rust::Vec<CXX_TYPE> *ptr) noexcept; \ - std::size_t cxxbridge1$rust_vec$##RUST_TYPE##$len( \ - const rust::Vec<CXX_TYPE> *ptr) noexcept; \ - std::size_t cxxbridge1$rust_vec$##RUST_TYPE##$capacity( \ - const rust::Vec<CXX_TYPE> *ptr) noexcept; \ - const CXX_TYPE *cxxbridge1$rust_vec$##RUST_TYPE##$data( \ - const rust::Vec<CXX_TYPE> *ptr) noexcept; \ - void cxxbridge1$rust_vec$##RUST_TYPE##$reserve_total( \ - rust::Vec<CXX_TYPE> *ptr, std::size_t new_cap) noexcept; \ - void cxxbridge1$rust_vec$##RUST_TYPE##$set_len(rust::Vec<CXX_TYPE> *ptr, \ - std::size_t len) noexcept; \ - void cxxbridge1$rust_vec$##RUST_TYPE##$truncate(rust::Vec<CXX_TYPE> *ptr, \ - std::size_t len) noexcept; - -#define RUST_VEC_OPS(RUST_TYPE, CXX_TYPE) \ - template <> \ - Vec<CXX_TYPE>::Vec() noexcept { \ - cxxbridge1$rust_vec$##RUST_TYPE##$new(this); \ - } \ - template <> \ - void Vec<CXX_TYPE>::drop() noexcept { \ - return cxxbridge1$rust_vec$##RUST_TYPE##$drop(this); \ - } \ - template <> \ - std::size_t Vec<CXX_TYPE>::size() const noexcept { \ - return cxxbridge1$rust_vec$##RUST_TYPE##$len(this); \ - } \ - template <> \ - std::size_t Vec<CXX_TYPE>::capacity() const noexcept { \ - return cxxbridge1$rust_vec$##RUST_TYPE##$capacity(this); \ - } \ - template <> \ - const CXX_TYPE *Vec<CXX_TYPE>::data() const noexcept { \ - return cxxbridge1$rust_vec$##RUST_TYPE##$data(this); \ - } \ - template <> \ - void Vec<CXX_TYPE>::reserve_total(std::size_t new_cap) noexcept { \ - cxxbridge1$rust_vec$##RUST_TYPE##$reserve_total(this, new_cap); \ - } \ - template <> \ - void Vec<CXX_TYPE>::set_len(std::size_t len) noexcept { \ - cxxbridge1$rust_vec$##RUST_TYPE##$set_len(this, len); \ - } \ - template <> \ - void Vec<CXX_TYPE>::truncate(std::size_t len) { \ - cxxbridge1$rust_vec$##RUST_TYPE##$truncate(this, len); \ - } - -#define SHARED_PTR_OPS(RUST_TYPE, CXX_TYPE) \ - static_assert(sizeof(std::shared_ptr<CXX_TYPE>) == 2 * sizeof(void *), ""); \ - static_assert(alignof(std::shared_ptr<CXX_TYPE>) == alignof(void *), ""); \ - void cxxbridge1$std$shared_ptr$##RUST_TYPE##$null( \ - std::shared_ptr<CXX_TYPE> *ptr) noexcept { \ - new (ptr) std::shared_ptr<CXX_TYPE>(); \ - } \ - CXX_TYPE *cxxbridge1$std$shared_ptr$##RUST_TYPE##$uninit( \ - std::shared_ptr<CXX_TYPE> *ptr) noexcept { \ - CXX_TYPE *uninit = \ - reinterpret_cast<CXX_TYPE *>(new rust::MaybeUninit<CXX_TYPE>); \ - new (ptr) std::shared_ptr<CXX_TYPE>(uninit); \ - return uninit; \ - } \ - void cxxbridge1$std$shared_ptr$##RUST_TYPE##$clone( \ - const std::shared_ptr<CXX_TYPE> &self, \ - std::shared_ptr<CXX_TYPE> *ptr) noexcept { \ - new (ptr) std::shared_ptr<CXX_TYPE>(self); \ - } \ - const CXX_TYPE *cxxbridge1$std$shared_ptr$##RUST_TYPE##$get( \ - const std::shared_ptr<CXX_TYPE> &self) noexcept { \ - return self.get(); \ - } \ - void cxxbridge1$std$shared_ptr$##RUST_TYPE##$drop( \ - const std::shared_ptr<CXX_TYPE> *self) noexcept { \ - self->~shared_ptr(); \ - } \ - static_assert(sizeof(std::weak_ptr<CXX_TYPE>) == 2 * sizeof(void *), ""); \ - static_assert(alignof(std::weak_ptr<CXX_TYPE>) == alignof(void *), ""); \ - void cxxbridge1$std$weak_ptr$##RUST_TYPE##$null( \ - std::weak_ptr<CXX_TYPE> *ptr) noexcept { \ - new (ptr) std::weak_ptr<CXX_TYPE>(); \ - } \ - void cxxbridge1$std$weak_ptr$##RUST_TYPE##$clone( \ - const std::weak_ptr<CXX_TYPE> &self, \ - std::weak_ptr<CXX_TYPE> *ptr) noexcept { \ - new (ptr) std::weak_ptr<CXX_TYPE>(self); \ - } \ - void cxxbridge1$std$weak_ptr$##RUST_TYPE##$downgrade( \ - const std::shared_ptr<CXX_TYPE> &shared, \ - std::weak_ptr<CXX_TYPE> *weak) noexcept { \ - new (weak) std::weak_ptr<CXX_TYPE>(shared); \ - } \ - void cxxbridge1$std$weak_ptr$##RUST_TYPE##$upgrade( \ - const std::weak_ptr<CXX_TYPE> &weak, \ - std::shared_ptr<CXX_TYPE> *shared) noexcept { \ - new (shared) std::shared_ptr<CXX_TYPE>(weak.lock()); \ - } \ - void cxxbridge1$std$weak_ptr$##RUST_TYPE##$drop( \ - const std::weak_ptr<CXX_TYPE> *self) noexcept { \ - self->~weak_ptr(); \ - } - -// Usize and isize are the same type as one of the below. -#define FOR_EACH_NUMERIC(MACRO) \ - MACRO(u8, std::uint8_t) \ - MACRO(u16, std::uint16_t) \ - MACRO(u32, std::uint32_t) \ - MACRO(u64, std::uint64_t) \ - MACRO(i8, std::int8_t) \ - MACRO(i16, std::int16_t) \ - MACRO(i32, std::int32_t) \ - MACRO(i64, std::int64_t) \ - MACRO(f32, float) \ - MACRO(f64, double) - -#define FOR_EACH_TRIVIAL_STD_VECTOR(MACRO) \ - FOR_EACH_NUMERIC(MACRO) \ - MACRO(usize, std::size_t) \ - MACRO(isize, rust::isize) - -#define FOR_EACH_STD_VECTOR(MACRO) \ - FOR_EACH_TRIVIAL_STD_VECTOR(MACRO) \ - MACRO(string, std::string) - -#define FOR_EACH_RUST_VEC(MACRO) \ - FOR_EACH_NUMERIC(MACRO) \ - MACRO(bool, bool) \ - MACRO(char, char) \ - MACRO(usize, rust::detail::usize_if_unique) \ - MACRO(isize, rust::detail::isize_if_unique) \ - MACRO(string, rust::String) \ - MACRO(str, rust::Str) - -#define FOR_EACH_SHARED_PTR(MACRO) \ - FOR_EACH_NUMERIC(MACRO) \ - MACRO(bool, bool) \ - MACRO(usize, std::size_t) \ - MACRO(isize, rust::isize) \ - MACRO(string, std::string) - -extern "C" { -FOR_EACH_STD_VECTOR(STD_VECTOR_OPS) -FOR_EACH_TRIVIAL_STD_VECTOR(STD_VECTOR_TRIVIAL_OPS) -FOR_EACH_RUST_VEC(RUST_VEC_EXTERNS) -FOR_EACH_SHARED_PTR(SHARED_PTR_OPS) -} // extern "C" - -namespace rust { -inline namespace cxxbridge1 { -FOR_EACH_RUST_VEC(RUST_VEC_OPS) -} // namespace cxxbridge1 -} // namespace rust diff --git a/vendor/cxx/src/cxx_string.rs b/vendor/cxx/src/cxx_string.rs deleted file mode 100644 index d5d0af4a4..000000000 --- a/vendor/cxx/src/cxx_string.rs +++ /dev/null @@ -1,312 +0,0 @@ -use crate::actually_private::Private; -use crate::lossy; -#[cfg(feature = "alloc")] -use alloc::borrow::Cow; -#[cfg(feature = "alloc")] -use alloc::string::String; -use core::cmp::Ordering; -use core::fmt::{self, Debug, Display}; -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}; - -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); -} - -/// Binding to C++ `std::string`. -/// -/// # Invariants -/// -/// As an invariant of this API and the static analysis of the cxx::bridge -/// macro, in Rust code we can never obtain a `CxxString` by value. C++'s string -/// requires a move constructor and may hold internal pointers, which is not -/// compatible with Rust's move behavior. Instead in Rust code we will only ever -/// look at a CxxString through a reference or smart pointer, as in `&CxxString` -/// or `UniquePtr<CxxString>`. -#[repr(C)] -pub struct CxxString { - _private: [u8; 0], - _pinned: PhantomData<PhantomPinned>, -} - -/// Construct a C++ std::string on the Rust stack. -/// -/// # Syntax -/// -/// In statement position: -/// -/// ``` -/// # use cxx::let_cxx_string; -/// # let expression = ""; -/// let_cxx_string!(var = expression); -/// ``` -/// -/// The `expression` may have any type that implements `AsRef<[u8]>`. Commonly -/// it will be a string literal, but for example `&[u8]` and `String` would work -/// as well. -/// -/// The macro expands to something resembling `let $var: Pin<&mut CxxString> = -/// /*???*/;`. The resulting [`Pin`] can be deref'd to `&CxxString` as needed. -/// -/// # Example -/// -/// ``` -/// use cxx::{let_cxx_string, CxxString}; -/// -/// fn f(s: &CxxString) {/* ... */} -/// -/// fn main() { -/// let_cxx_string!(s = "example"); -/// f(&s); -/// } -/// ``` -#[macro_export] -macro_rules! let_cxx_string { - ($var:ident = $value:expr $(,)?) => { - let mut 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) }, - }; - }; -} - -impl CxxString { - /// `CxxString` is not constructible via `new`. Instead, use the - /// [`let_cxx_string!`] macro. - pub fn new<T: Private>() -> Self { - unreachable!() - } - - /// Returns the length of the string in bytes. - /// - /// Matches the behavior of C++ [std::string::size][size]. - /// - /// [size]: https://en.cppreference.com/w/cpp/string/basic_string/size - pub fn len(&self) -> usize { - unsafe { string_length(self) } - } - - /// Returns true if `self` has a length of zero bytes. - /// - /// Matches the behavior of C++ [std::string::empty][empty]. - /// - /// [empty]: https://en.cppreference.com/w/cpp/string/basic_string/empty - pub fn is_empty(&self) -> bool { - self.len() == 0 - } - - /// Returns a byte slice of this string's contents. - pub fn as_bytes(&self) -> &[u8] { - let data = self.as_ptr(); - let len = self.len(); - unsafe { slice::from_raw_parts(data, len) } - } - - /// Produces a pointer to the first character of the string. - /// - /// Matches the behavior of C++ [std::string::data][data]. - /// - /// Note that the return type may look like `const char *` but is not a - /// `const char *` in the typical C sense, as C++ strings may contain - /// internal null bytes. As such, the returned pointer only makes sense as a - /// string in combination with the length returned by [`len()`][len]. - /// - /// [data]: https://en.cppreference.com/w/cpp/string/basic_string/data - /// [len]: #method.len - pub fn as_ptr(&self) -> *const u8 { - unsafe { string_data(self) } - } - - /// Validates that the C++ string contains UTF-8 data and produces a view of - /// it as a Rust &str, otherwise an error. - pub fn to_str(&self) -> Result<&str, Utf8Error> { - str::from_utf8(self.as_bytes()) - } - - /// If the contents of the C++ string are valid UTF-8, this function returns - /// a view as a Cow::Borrowed &str. Otherwise replaces any invalid UTF-8 - /// sequences with the U+FFFD [replacement character] and returns a - /// Cow::Owned String. - /// - /// [replacement character]: https://doc.rust-lang.org/std/char/constant.REPLACEMENT_CHARACTER.html - #[cfg(feature = "alloc")] - #[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))] - pub fn to_string_lossy(&self) -> Cow<str> { - String::from_utf8_lossy(self.as_bytes()) - } - - /// Removes all characters from the string. - /// - /// Matches the behavior of C++ [std::string::clear][clear]. - /// - /// Note: **unlike** the guarantee of Rust's `std::string::String::clear`, - /// the C++ standard does not require that capacity is unchanged by this - /// operation. In practice existing implementations do not change the - /// capacity but all pointers, references, and iterators into the string - /// contents are nevertheless invalidated. - /// - /// [clear]: https://en.cppreference.com/w/cpp/string/basic_string/clear - pub fn clear(self: Pin<&mut Self>) { - unsafe { string_clear(self) } - } - - /// Ensures that this string's capacity is at least `additional` bytes - /// larger than its length. - /// - /// The capacity may be increased by more than `additional` bytes if it - /// chooses, to amortize the cost of frequent reallocations. - /// - /// **The meaning of the argument is not the same as - /// [std::string::reserve][reserve] in C++.** The C++ standard library and - /// Rust standard library both have a `reserve` method on strings, but in - /// C++ code the argument always refers to total capacity, whereas in Rust - /// code it always refers to additional capacity. This API on `CxxString` - /// follows the Rust convention, the same way that for the length accessor - /// we use the Rust conventional `len()` naming and not C++ `size()` or - /// `length()`. - /// - /// # Panics - /// - /// Panics if the new capacity overflows usize. - /// - /// [reserve]: https://en.cppreference.com/w/cpp/string/basic_string/reserve - 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) } - } - - /// Appends a given string slice onto the end of this C++ string. - pub fn push_str(self: Pin<&mut Self>, s: &str) { - self.push_bytes(s.as_bytes()); - } - - /// Appends arbitrary bytes onto the end of this C++ string. - 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> { - self.as_bytes().partial_cmp(other.as_bytes()) - } -} - -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 { - // Static assertions in cxx.cc validate that this is large enough and - // aligned enough. - space: MaybeUninit<[usize; 8]>, -} - -#[allow(missing_docs)] -impl StackString { - pub fn new() -> Self { - StackString { - space: MaybeUninit::uninit(), - } - } - - pub unsafe fn init(&mut self, value: impl AsRef<[u8]>) -> Pin<&mut CxxString> { - let value = value.as_ref(); - unsafe { - let this = &mut *self.space.as_mut_ptr().cast::<MaybeUninit<CxxString>>(); - string_init(this, value.as_ptr(), value.len()); - Pin::new_unchecked(&mut *this.as_mut_ptr()) - } - } -} - -impl Drop for StackString { - fn drop(&mut self) { - unsafe { - let this = &mut *self.space.as_mut_ptr().cast::<MaybeUninit<CxxString>>(); - string_destroy(this); - } - } -} diff --git a/vendor/cxx/src/cxx_vector.rs b/vendor/cxx/src/cxx_vector.rs deleted file mode 100644 index abf9297a8..000000000 --- a/vendor/cxx/src/cxx_vector.rs +++ /dev/null @@ -1,492 +0,0 @@ -//! Less used details of `CxxVector` are exposed in this module. `CxxVector` -//! itself is exposed at the crate root. - -use crate::extern_type::ExternType; -use crate::kind::Trivial; -use crate::string::CxxString; -use core::ffi::c_void; -use core::fmt::{self, Debug}; -use core::iter::FusedIterator; -use core::marker::{PhantomData, PhantomPinned}; -use core::mem::{self, ManuallyDrop, MaybeUninit}; -use core::pin::Pin; -use core::slice; - -/// Binding to C++ `std::vector<T, std::allocator<T>>`. -/// -/// # Invariants -/// -/// As an invariant of this API and the static analysis of the cxx::bridge -/// macro, in Rust code we can never obtain a `CxxVector` by value. Instead in -/// Rust code we will only ever look at a vector behind a reference or smart -/// pointer, as in `&CxxVector<T>` or `UniquePtr<CxxVector<T>>`. -#[repr(C, packed)] -pub struct CxxVector<T> { - // A thing, because repr(C) structs are not allowed to consist exclusively - // of PhantomData fields. - _void: [c_void; 0], - // The conceptual vector elements to ensure that autotraits are propagated - // correctly, e.g. CxxVector is UnwindSafe iff T is. - _elements: PhantomData<[T]>, - // Prevent unpin operation from Pin<&mut CxxVector<T>> to &mut CxxVector<T>. - _pinned: PhantomData<PhantomPinned>, -} - -impl<T> CxxVector<T> -where - T: VectorElement, -{ - /// Returns the number of elements in the vector. - /// - /// Matches the behavior of C++ [std::vector\<T\>::size][size]. - /// - /// [size]: https://en.cppreference.com/w/cpp/container/vector/size - pub fn len(&self) -> usize { - T::__vector_size(self) - } - - /// Returns true if the vector contains no elements. - /// - /// Matches the behavior of C++ [std::vector\<T\>::empty][empty]. - /// - /// [empty]: https://en.cppreference.com/w/cpp/container/vector/empty - pub fn is_empty(&self) -> bool { - self.len() == 0 - } - - /// Returns a reference to an element at the given position, or `None` if - /// out of bounds. - pub fn get(&self, pos: usize) -> Option<&T> { - if pos < self.len() { - Some(unsafe { self.get_unchecked(pos) }) - } else { - None - } - } - - /// Returns a pinned mutable reference to an element at the given position, - /// or `None` if out of bounds. - pub fn index_mut(self: Pin<&mut Self>, pos: usize) -> Option<Pin<&mut T>> { - if pos < self.len() { - Some(unsafe { self.index_unchecked_mut(pos) }) - } else { - None - } - } - - /// Returns a reference to an element without doing bounds checking. - /// - /// This is generally not recommended, use with caution! Calling this method - /// with an out-of-bounds index is undefined behavior even if the resulting - /// reference is not used. - /// - /// Matches the behavior of C++ - /// [std::vector\<T\>::operator\[\] const][operator_at]. - /// - /// [operator_at]: https://en.cppreference.com/w/cpp/container/vector/operator_at - pub unsafe fn get_unchecked(&self, pos: usize) -> &T { - let this = self as *const CxxVector<T> as *mut CxxVector<T>; - unsafe { - let ptr = T::__get_unchecked(this, pos) as *const T; - &*ptr - } - } - - /// Returns a pinned mutable reference to an element without doing bounds - /// checking. - /// - /// This is generally not recommended, use with caution! Calling this method - /// with an out-of-bounds index is undefined behavior even if the resulting - /// reference is not used. - /// - /// Matches the behavior of C++ - /// [std::vector\<T\>::operator\[\]][operator_at]. - /// - /// [operator_at]: https://en.cppreference.com/w/cpp/container/vector/operator_at - pub unsafe fn index_unchecked_mut(self: Pin<&mut Self>, pos: usize) -> Pin<&mut T> { - unsafe { - let ptr = T::__get_unchecked(self.get_unchecked_mut(), pos); - Pin::new_unchecked(&mut *ptr) - } - } - - /// Returns a slice to the underlying contiguous array of elements. - pub fn as_slice(&self) -> &[T] - where - T: ExternType<Kind = Trivial>, - { - let len = self.len(); - if len == 0 { - // The slice::from_raw_parts in the other branch requires a nonnull - // and properly aligned data ptr. C++ standard does not guarantee - // that data() on a vector with size 0 would return a nonnull - // pointer or sufficiently aligned pointer, so using it would be - // undefined behavior. Create our own empty slice in Rust instead - // which upholds the invariants. - &[] - } else { - let this = self as *const CxxVector<T> as *mut CxxVector<T>; - let ptr = unsafe { T::__get_unchecked(this, 0) }; - unsafe { slice::from_raw_parts(ptr, len) } - } - } - - /// Returns a slice to the underlying contiguous array of elements by - /// mutable reference. - pub fn as_mut_slice(self: Pin<&mut Self>) -> &mut [T] - where - T: ExternType<Kind = Trivial>, - { - let len = self.len(); - if len == 0 { - &mut [] - } else { - let ptr = unsafe { T::__get_unchecked(self.get_unchecked_mut(), 0) }; - unsafe { slice::from_raw_parts_mut(ptr, len) } - } - } - - /// Returns an iterator over elements of type `&T`. - pub fn iter(&self) -> Iter<T> { - Iter { v: self, index: 0 } - } - - /// Returns an iterator over elements of type `Pin<&mut T>`. - pub fn iter_mut(self: Pin<&mut Self>) -> IterMut<T> { - IterMut { v: self, index: 0 } - } - - /// Appends an element to the back of the vector. - /// - /// Matches the behavior of C++ [std::vector\<T\>::push_back][push_back]. - /// - /// [push_back]: https://en.cppreference.com/w/cpp/container/vector/push_back - pub fn push(self: Pin<&mut Self>, value: T) - where - T: ExternType<Kind = Trivial>, - { - let mut value = ManuallyDrop::new(value); - unsafe { - // C++ calls move constructor followed by destructor on `value`. - T::__push_back(self, &mut value); - } - } - - /// Removes the last element from a vector and returns it, or `None` if the - /// vector is empty. - pub fn pop(self: Pin<&mut Self>) -> Option<T> - where - T: ExternType<Kind = Trivial>, - { - if self.is_empty() { - None - } else { - let mut value = MaybeUninit::uninit(); - Some(unsafe { - T::__pop_back(self, &mut value); - value.assume_init() - }) - } - } -} - -/// Iterator over elements of a `CxxVector` by shared reference. -/// -/// The iterator element type is `&'a T`. -pub struct Iter<'a, T> { - v: &'a CxxVector<T>, - index: usize, -} - -impl<'a, T> IntoIterator for &'a CxxVector<T> -where - T: VectorElement, -{ - type Item = &'a T; - type IntoIter = Iter<'a, T>; - - fn into_iter(self) -> Self::IntoIter { - self.iter() - } -} - -impl<'a, T> Iterator for Iter<'a, T> -where - T: VectorElement, -{ - type Item = &'a T; - - fn next(&mut self) -> Option<Self::Item> { - let next = self.v.get(self.index)?; - self.index += 1; - Some(next) - } - - fn size_hint(&self) -> (usize, Option<usize>) { - let len = self.len(); - (len, Some(len)) - } -} - -impl<'a, T> ExactSizeIterator for Iter<'a, T> -where - T: VectorElement, -{ - fn len(&self) -> usize { - self.v.len() - self.index - } -} - -impl<'a, T> FusedIterator for Iter<'a, T> where T: VectorElement {} - -/// Iterator over elements of a `CxxVector` by pinned mutable reference. -/// -/// The iterator element type is `Pin<&'a mut T>`. -pub struct IterMut<'a, T> { - v: Pin<&'a mut CxxVector<T>>, - index: usize, -} - -impl<'a, T> IntoIterator for Pin<&'a mut CxxVector<T>> -where - T: VectorElement, -{ - type Item = Pin<&'a mut T>; - type IntoIter = IterMut<'a, T>; - - fn into_iter(self) -> Self::IntoIter { - self.iter_mut() - } -} - -impl<'a, T> Iterator for IterMut<'a, T> -where - T: VectorElement, -{ - type Item = Pin<&'a mut T>; - - fn next(&mut self) -> Option<Self::Item> { - let next = self.v.as_mut().index_mut(self.index)?; - self.index += 1; - // Extend lifetime to allow simultaneous holding of nonoverlapping - // elements, analogous to slice::split_first_mut. - unsafe { - let ptr = Pin::into_inner_unchecked(next) as *mut T; - Some(Pin::new_unchecked(&mut *ptr)) - } - } - - fn size_hint(&self) -> (usize, Option<usize>) { - let len = self.len(); - (len, Some(len)) - } -} - -impl<'a, T> ExactSizeIterator for IterMut<'a, T> -where - T: VectorElement, -{ - fn len(&self) -> usize { - self.v.len() - self.index - } -} - -impl<'a, T> FusedIterator for IterMut<'a, T> where T: VectorElement {} - -impl<T> Debug for CxxVector<T> -where - T: VectorElement + Debug, -{ - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.debug_list().entries(self).finish() - } -} - -/// Trait bound for types which may be used as the `T` inside of a -/// `CxxVector<T>` in generic code. -/// -/// This trait has no publicly callable or implementable methods. Implementing -/// it outside of the CXX codebase is not supported. -/// -/// # Example -/// -/// A bound `T: VectorElement` may be necessary when manipulating [`CxxVector`] -/// in generic code. -/// -/// ``` -/// use cxx::vector::{CxxVector, VectorElement}; -/// use std::fmt::Display; -/// -/// pub fn take_generic_vector<T>(vector: &CxxVector<T>) -/// where -/// T: VectorElement + Display, -/// { -/// println!("the vector elements are:"); -/// for element in vector { -/// println!(" • {}", element); -/// } -/// } -/// ``` -/// -/// Writing the same generic function without a `VectorElement` trait bound -/// would not compile. -pub unsafe trait VectorElement: Sized { - #[doc(hidden)] - fn __typename(f: &mut fmt::Formatter) -> fmt::Result; - #[doc(hidden)] - fn __vector_size(v: &CxxVector<Self>) -> usize; - #[doc(hidden)] - unsafe fn __get_unchecked(v: *mut CxxVector<Self>, pos: usize) -> *mut Self; - #[doc(hidden)] - unsafe fn __push_back(v: Pin<&mut CxxVector<Self>>, value: &mut ManuallyDrop<Self>) { - // Opaque C type vector elements do not get this method because they can - // never exist by value on the Rust side of the bridge. - let _ = v; - let _ = value; - unreachable!() - } - #[doc(hidden)] - unsafe fn __pop_back(v: Pin<&mut CxxVector<Self>>, out: &mut MaybeUninit<Self>) { - // Opaque C type vector elements do not get this method because they can - // never exist by value on the Rust side of the bridge. - let _ = v; - let _ = out; - unreachable!() - } - #[doc(hidden)] - fn __unique_ptr_null() -> MaybeUninit<*mut c_void>; - #[doc(hidden)] - unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> MaybeUninit<*mut c_void>; - #[doc(hidden)] - unsafe fn __unique_ptr_get(repr: MaybeUninit<*mut c_void>) -> *const CxxVector<Self>; - #[doc(hidden)] - unsafe fn __unique_ptr_release(repr: MaybeUninit<*mut c_void>) -> *mut CxxVector<Self>; - #[doc(hidden)] - unsafe fn __unique_ptr_drop(repr: MaybeUninit<*mut c_void>); -} - -macro_rules! vector_element_by_value_methods { - (opaque, $segment:expr, $ty:ty) => {}; - (trivial, $segment:expr, $ty:ty) => { - unsafe fn __push_back(v: Pin<&mut CxxVector<$ty>>, value: &mut ManuallyDrop<$ty>) { - extern "C" { - attr! { - #[link_name = concat!("cxxbridge1$std$vector$", $segment, "$push_back")] - fn __push_back(_: Pin<&mut CxxVector<$ty>>, _: &mut ManuallyDrop<$ty>); - } - } - unsafe { __push_back(v, value) } - } - unsafe fn __pop_back(v: Pin<&mut CxxVector<$ty>>, out: &mut MaybeUninit<$ty>) { - extern "C" { - attr! { - #[link_name = concat!("cxxbridge1$std$vector$", $segment, "$pop_back")] - fn __pop_back(_: Pin<&mut CxxVector<$ty>>, _: &mut MaybeUninit<$ty>); - } - } - unsafe { __pop_back(v, out) } - } - }; -} - -macro_rules! impl_vector_element { - ($kind:ident, $segment:expr, $name:expr, $ty:ty) => { - const_assert_eq!(0, mem::size_of::<CxxVector<$ty>>()); - const_assert_eq!(1, mem::align_of::<CxxVector<$ty>>()); - - unsafe impl VectorElement for $ty { - fn __typename(f: &mut fmt::Formatter) -> fmt::Result { - f.write_str($name) - } - fn __vector_size(v: &CxxVector<$ty>) -> usize { - extern "C" { - attr! { - #[link_name = concat!("cxxbridge1$std$vector$", $segment, "$size")] - fn __vector_size(_: &CxxVector<$ty>) -> usize; - } - } - unsafe { __vector_size(v) } - } - unsafe fn __get_unchecked(v: *mut CxxVector<$ty>, pos: usize) -> *mut $ty { - extern "C" { - attr! { - #[link_name = concat!("cxxbridge1$std$vector$", $segment, "$get_unchecked")] - fn __get_unchecked(_: *mut CxxVector<$ty>, _: usize) -> *mut $ty; - } - } - unsafe { __get_unchecked(v, pos) } - } - vector_element_by_value_methods!($kind, $segment, $ty); - fn __unique_ptr_null() -> MaybeUninit<*mut c_void> { - extern "C" { - attr! { - #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$null")] - fn __unique_ptr_null(this: *mut MaybeUninit<*mut c_void>); - } - } - let mut repr = MaybeUninit::uninit(); - unsafe { __unique_ptr_null(&mut repr) } - repr - } - unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> MaybeUninit<*mut c_void> { - extern "C" { - attr! { - #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$raw")] - fn __unique_ptr_raw(this: *mut MaybeUninit<*mut c_void>, raw: *mut CxxVector<$ty>); - } - } - let mut repr = MaybeUninit::uninit(); - unsafe { __unique_ptr_raw(&mut repr, raw) } - repr - } - unsafe fn __unique_ptr_get(repr: MaybeUninit<*mut c_void>) -> *const CxxVector<Self> { - extern "C" { - attr! { - #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$get")] - fn __unique_ptr_get(this: *const MaybeUninit<*mut c_void>) -> *const CxxVector<$ty>; - } - } - unsafe { __unique_ptr_get(&repr) } - } - unsafe fn __unique_ptr_release(mut repr: MaybeUninit<*mut c_void>) -> *mut CxxVector<Self> { - extern "C" { - attr! { - #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$release")] - fn __unique_ptr_release(this: *mut MaybeUninit<*mut c_void>) -> *mut CxxVector<$ty>; - } - } - unsafe { __unique_ptr_release(&mut repr) } - } - unsafe fn __unique_ptr_drop(mut repr: MaybeUninit<*mut c_void>) { - extern "C" { - attr! { - #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$drop")] - fn __unique_ptr_drop(this: *mut MaybeUninit<*mut c_void>); - } - } - unsafe { __unique_ptr_drop(&mut repr) } - } - } - }; -} - -macro_rules! impl_vector_element_for_primitive { - ($ty:ident) => { - impl_vector_element!(trivial, stringify!($ty), stringify!($ty), $ty); - }; -} - -impl_vector_element_for_primitive!(u8); -impl_vector_element_for_primitive!(u16); -impl_vector_element_for_primitive!(u32); -impl_vector_element_for_primitive!(u64); -impl_vector_element_for_primitive!(usize); -impl_vector_element_for_primitive!(i8); -impl_vector_element_for_primitive!(i16); -impl_vector_element_for_primitive!(i32); -impl_vector_element_for_primitive!(i64); -impl_vector_element_for_primitive!(isize); -impl_vector_element_for_primitive!(f32); -impl_vector_element_for_primitive!(f64); - -impl_vector_element!(opaque, "string", "CxxString", CxxString); diff --git a/vendor/cxx/src/exception.rs b/vendor/cxx/src/exception.rs deleted file mode 100644 index 259b27d4d..000000000 --- a/vendor/cxx/src/exception.rs +++ /dev/null @@ -1,28 +0,0 @@ -#![cfg(feature = "alloc")] - -use alloc::boxed::Box; -use core::fmt::{self, Display}; - -/// Exception thrown from an `extern "C++"` function. -#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))] -#[derive(Debug)] -pub struct Exception { - pub(crate) what: Box<str>, -} - -impl Display for Exception { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.write_str(&self.what) - } -} - -#[cfg(feature = "std")] -#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))] -impl std::error::Error for Exception {} - -impl Exception { - #[allow(missing_docs)] - pub fn what(&self) -> &str { - &self.what - } -} diff --git a/vendor/cxx/src/extern_type.rs b/vendor/cxx/src/extern_type.rs deleted file mode 100644 index d131ae127..000000000 --- a/vendor/cxx/src/extern_type.rs +++ /dev/null @@ -1,225 +0,0 @@ -use self::kind::{Kind, Opaque, Trivial}; -use crate::CxxString; -#[cfg(feature = "alloc")] -use alloc::string::String; - -/// A type for which the layout is determined by its C++ definition. -/// -/// This trait serves the following two related purposes. -/// -/// <br> -/// -/// ## Safely unifying occurrences of the same extern type -/// -/// `ExternType` makes it possible for CXX to safely share a consistent Rust -/// type across multiple #\[cxx::bridge\] invocations that refer to a common -/// extern C++ type. -/// -/// In the following snippet, two #\[cxx::bridge\] invocations in different -/// files (possibly different crates) both contain function signatures involving -/// the same C++ type `example::Demo`. If both were written just containing -/// `type Demo;`, then both macro expansions would produce their own separate -/// Rust type called `Demo` and thus the compiler wouldn't allow us to take the -/// `Demo` returned by `file1::ffi::create_demo` and pass it as the `Demo` -/// argument accepted by `file2::ffi::take_ref_demo`. Instead, one of the two -/// `Demo`s has been defined as an extern type alias of the other, making them -/// the same type in Rust. The CXX code generator will use an automatically -/// generated `ExternType` impl emitted in file1 to statically verify that in -/// file2 `crate::file1::ffi::Demo` really does refer to the C++ type -/// `example::Demo` as expected in file2. -/// -/// ```no_run -/// // file1.rs -/// # mod file1 { -/// #[cxx::bridge(namespace = "example")] -/// pub mod ffi { -/// unsafe extern "C++" { -/// type Demo; -/// -/// fn create_demo() -> UniquePtr<Demo>; -/// } -/// } -/// # } -/// -/// // file2.rs -/// #[cxx::bridge(namespace = "example")] -/// pub mod ffi { -/// unsafe extern "C++" { -/// type Demo = crate::file1::ffi::Demo; -/// -/// fn take_ref_demo(demo: &Demo); -/// } -/// } -/// # -/// # fn main() {} -/// ``` -/// -/// <br><br> -/// -/// ## Integrating with bindgen-generated types -/// -/// Handwritten `ExternType` impls make it possible to plug in a data structure -/// emitted by bindgen as the definition of a C++ type emitted by CXX. -/// -/// By writing the unsafe `ExternType` impl, the programmer asserts that the C++ -/// namespace and type name given in the type id refers to a C++ type that is -/// equivalent to Rust type that is the `Self` type of the impl. -/// -/// ```no_run -/// # const _: &str = stringify! { -/// mod folly_sys; // the bindgen-generated bindings -/// # }; -/// # mod folly_sys { -/// # #[repr(transparent)] -/// # pub struct StringPiece([usize; 2]); -/// # } -/// -/// use cxx::{type_id, ExternType}; -/// -/// unsafe impl ExternType for folly_sys::StringPiece { -/// type Id = type_id!("folly::StringPiece"); -/// type Kind = cxx::kind::Opaque; -/// } -/// -/// #[cxx::bridge(namespace = "folly")] -/// pub mod ffi { -/// unsafe extern "C++" { -/// include!("rust_cxx_bindings.h"); -/// -/// type StringPiece = crate::folly_sys::StringPiece; -/// -/// fn print_string_piece(s: &StringPiece); -/// } -/// } -/// -/// // Now if we construct a StringPiece or obtain one through one -/// // of the bindgen-generated signatures, we are able to pass it -/// // along to ffi::print_string_piece. -/// # -/// # fn main() {} -/// ``` -pub unsafe trait ExternType { - /// A type-level representation of the type's C++ namespace and type name. - /// - /// This will always be defined using `type_id!` in the following form: - /// - /// ``` - /// # struct TypeName; - /// # unsafe impl cxx::ExternType for TypeName { - /// type Id = cxx::type_id!("name::space::of::TypeName"); - /// # type Kind = cxx::kind::Opaque; - /// # } - /// ``` - type Id; - - /// Either [`cxx::kind::Opaque`] or [`cxx::kind::Trivial`]. - /// - /// [`cxx::kind::Opaque`]: kind::Opaque - /// [`cxx::kind::Trivial`]: kind::Trivial - /// - /// A C++ type is only okay to hold and pass around by value in Rust if its - /// [move constructor is trivial] and it has no destructor. In CXX, these - /// are called Trivial extern C++ types, while types with nontrivial move - /// behavior or a destructor must be considered Opaque and handled by Rust - /// only behind an indirection, such as a reference or UniquePtr. - /// - /// [move constructor is trivial]: https://en.cppreference.com/w/cpp/types/is_move_constructible - /// - /// If you believe your C++ type reflected by this ExternType impl is indeed - /// fine to hold by value and move in Rust, you can specify: - /// - /// ``` - /// # struct TypeName; - /// # unsafe impl cxx::ExternType for TypeName { - /// # type Id = cxx::type_id!("name::space::of::TypeName"); - /// type Kind = cxx::kind::Trivial; - /// # } - /// ``` - /// - /// which will enable you to pass it into C++ functions by value, return it - /// by value, and include it in `struct`s that you have declared to - /// `cxx::bridge`. Your claim about the triviality of the C++ type will be - /// checked by a `static_assert` in the generated C++ side of the binding. - type Kind: Kind; -} - -/// Marker types identifying Rust's knowledge about an extern C++ type. -/// -/// These markers are used in the [`Kind`][ExternType::Kind] associated type in -/// impls of the `ExternType` trait. Refer to the documentation of `Kind` for an -/// overview of their purpose. -pub mod kind { - use super::private; - - /// An opaque type which cannot be passed or held by value within Rust. - /// - /// Rust's move semantics are such that every move is equivalent to a - /// memcpy. This is incompatible in general with C++'s constructor-based - /// move semantics, so a C++ type which has a destructor or nontrivial move - /// constructor must never exist by value in Rust. In CXX, such types are - /// called opaque C++ types. - /// - /// When passed across an FFI boundary, an opaque C++ type must be behind an - /// indirection such as a reference or UniquePtr. - pub enum Opaque {} - - /// A type with trivial move constructor and no destructor, which can - /// therefore be owned and moved around in Rust code without requiring - /// indirection. - pub enum Trivial {} - - #[allow(missing_docs)] - pub trait Kind: private::Sealed {} - impl Kind for Opaque {} - impl Kind for Trivial {} -} - -mod private { - pub trait Sealed {} - impl Sealed for super::Opaque {} - impl Sealed for super::Trivial {} -} - -#[doc(hidden)] -pub fn verify_extern_type<T: ExternType<Id = Id>, Id>() {} - -#[doc(hidden)] -pub fn verify_extern_kind<T: ExternType<Kind = Kind>, Kind: self::Kind>() {} - -macro_rules! impl_extern_type { - ($([$kind:ident] $($(#[$($attr:tt)*])* $ty:path = $cxxpath:literal)*)*) => { - $($( - $(#[$($attr)*])* - unsafe impl ExternType for $ty { - #[allow(unused_attributes)] // incorrect lint; this doc(hidden) attr *is* respected by rustdoc - #[doc(hidden)] - type Id = crate::type_id!($cxxpath); - type Kind = $kind; - } - )*)* - }; -} - -impl_extern_type! { - [Trivial] - bool = "bool" - u8 = "std::uint8_t" - u16 = "std::uint16_t" - u32 = "std::uint32_t" - u64 = "std::uint64_t" - usize = "size_t" - i8 = "std::int8_t" - i16 = "std::int16_t" - i32 = "std::int32_t" - i64 = "std::int64_t" - isize = "rust::isize" - f32 = "float" - f64 = "double" - - #[cfg(feature = "alloc")] - #[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))] - String = "rust::String" - - [Opaque] - CxxString = "std::string" -} diff --git a/vendor/cxx/src/fmt.rs b/vendor/cxx/src/fmt.rs deleted file mode 100644 index 69614f806..000000000 --- a/vendor/cxx/src/fmt.rs +++ /dev/null @@ -1,16 +0,0 @@ -use core::fmt::{self, Display}; - -pub(crate) fn display(fmt: impl Fn(&mut fmt::Formatter) -> fmt::Result) -> impl Display { - DisplayInvoke(fmt) -} - -struct DisplayInvoke<T>(T); - -impl<T> Display for DisplayInvoke<T> -where - T: Fn(&mut fmt::Formatter) -> fmt::Result, -{ - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - (self.0)(formatter) - } -} diff --git a/vendor/cxx/src/function.rs b/vendor/cxx/src/function.rs deleted file mode 100644 index f0a201008..000000000 --- a/vendor/cxx/src/function.rs +++ /dev/null @@ -1,9 +0,0 @@ -#![allow(missing_docs)] - -use core::ffi::c_void; - -#[repr(C)] -pub struct FatFunction { - pub trampoline: *const c_void, - pub ptr: *const c_void, -} diff --git a/vendor/cxx/src/hash.rs b/vendor/cxx/src/hash.rs deleted file mode 100644 index 4c92173f7..000000000 --- a/vendor/cxx/src/hash.rs +++ /dev/null @@ -1,12 +0,0 @@ -use core::hash::{Hash, Hasher}; - -#[doc(hidden)] -pub fn hash<V: Hash>(value: &V) -> usize { - #[cfg(feature = "std")] - let mut hasher = std::collections::hash_map::DefaultHasher::new(); - #[cfg(not(feature = "std"))] - let mut hasher = crate::sip::SipHasher13::new(); - - Hash::hash(value, &mut hasher); - Hasher::finish(&hasher) as usize -} diff --git a/vendor/cxx/src/lib.rs b/vendor/cxx/src/lib.rs deleted file mode 100644 index a0b175a7a..000000000 --- a/vendor/cxx/src/lib.rs +++ /dev/null @@ -1,542 +0,0 @@ -//! [![github]](https://github.com/dtolnay/cxx) [![crates-io]](https://crates.io/crates/cxx) [![docs-rs]](https://docs.rs/cxx) -//! -//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github -//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust -//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs -//! -//! <br> -//! -//! This library provides a **safe** mechanism for calling C++ code from Rust -//! and Rust code from C++, not subject to the many ways that things can go -//! wrong when using bindgen or cbindgen to generate unsafe C-style bindings. -//! -//! This doesn't change the fact that 100% of C++ code is unsafe. When auditing -//! a project, you would be on the hook for auditing all the unsafe Rust code -//! and *all* the C++ code. The core safety claim under this new model is that -//! auditing just the C++ side would be sufficient to catch all problems, i.e. -//! the Rust side can be 100% safe. -//! -//! <br> -//! -//! *Compiler support: requires rustc 1.60+ and c++11 or newer*<br> -//! *[Release notes](https://github.com/dtolnay/cxx/releases)* -//! -//! <br> -//! -//! # Guide -//! -//! Please see **<https://cxx.rs>** for a tutorial, reference material, and -//! example code. -//! -//! <br> -//! -//! # Overview -//! -//! The idea is that we define the signatures of both sides of our FFI boundary -//! embedded together in one Rust module (the next section shows an example). -//! From this, CXX receives a complete picture of the boundary to perform static -//! analyses against the types and function signatures to uphold both Rust's and -//! C++'s invariants and requirements. -//! -//! If everything checks out statically, then CXX uses a pair of code generators -//! to emit the relevant `extern "C"` signatures on both sides together with any -//! necessary static assertions for later in the build process to verify -//! correctness. On the Rust side this code generator is simply an attribute -//! procedural macro. On the C++ side it can be a small Cargo build script if -//! your build is managed by Cargo, or for other build systems like Bazel or -//! Buck we provide a command line tool which generates the header and source -//! file and should be easy to integrate. -//! -//! The resulting FFI bridge operates at zero or negligible overhead, i.e. no -//! copying, no serialization, no memory allocation, no runtime checks needed. -//! -//! The FFI signatures are able to use native types from whichever side they -//! please, such as Rust's `String` or C++'s `std::string`, Rust's `Box` or -//! C++'s `std::unique_ptr`, Rust's `Vec` or C++'s `std::vector`, etc in any -//! combination. CXX guarantees an ABI-compatible signature that both sides -//! understand, based on builtin bindings for key standard library types to -//! expose an idiomatic API on those types to the other language. For example -//! when manipulating a C++ string from Rust, its `len()` method becomes a call -//! of the `size()` member function defined by C++; when manipulation a Rust -//! string from C++, its `size()` member function calls Rust's `len()`. -//! -//! <br> -//! -//! # Example -//! -//! In this example we are writing a Rust application that wishes to take -//! advantage of an existing C++ client for a large-file blobstore service. The -//! blobstore supports a `put` operation for a discontiguous buffer upload. For -//! example we might be uploading snapshots of a circular buffer which would -//! tend to consist of 2 chunks, or fragments of a file spread across memory for -//! some other reason. -//! -//! A runnable version of this example is provided under the *demo* directory of -//! <https://github.com/dtolnay/cxx>. To try it out, run `cargo run` from that -//! directory. -//! -//! ```no_run -//! #[cxx::bridge] -//! mod ffi { -//! // Any shared structs, whose fields will be visible to both languages. -//! struct BlobMetadata { -//! size: usize, -//! tags: Vec<String>, -//! } -//! -//! extern "Rust" { -//! // Zero or more opaque types which both languages can pass around but -//! // only Rust can see the fields. -//! type MultiBuf; -//! -//! // Functions implemented in Rust. -//! fn next_chunk(buf: &mut MultiBuf) -> &[u8]; -//! } -//! -//! unsafe extern "C++" { -//! // One or more headers with the matching C++ declarations. Our code -//! // generators don't read it but it gets #include'd and used in static -//! // assertions to ensure our picture of the FFI boundary is accurate. -//! include!("demo/include/blobstore.h"); -//! -//! // Zero or more opaque types which both languages can pass around but -//! // only C++ can see the fields. -//! type BlobstoreClient; -//! -//! // Functions implemented in C++. -//! fn new_blobstore_client() -> UniquePtr<BlobstoreClient>; -//! fn put(&self, parts: &mut MultiBuf) -> u64; -//! fn tag(&self, blobid: u64, tag: &str); -//! fn metadata(&self, blobid: u64) -> BlobMetadata; -//! } -//! } -//! # -//! # pub struct MultiBuf; -//! # -//! # fn next_chunk(_buf: &mut MultiBuf) -> &[u8] { -//! # unimplemented!() -//! # } -//! # -//! # fn main() {} -//! ``` -//! -//! Now we simply provide Rust definitions of all the things in the `extern -//! "Rust"` block and C++ definitions of all the things in the `extern "C++"` -//! block, and get to call back and forth safely. -//! -//! Here are links to the complete set of source files involved in the demo: -//! -//! - [demo/src/main.rs](https://github.com/dtolnay/cxx/blob/master/demo/src/main.rs) -//! - [demo/build.rs](https://github.com/dtolnay/cxx/blob/master/demo/build.rs) -//! - [demo/include/blobstore.h](https://github.com/dtolnay/cxx/blob/master/demo/include/blobstore.h) -//! - [demo/src/blobstore.cc](https://github.com/dtolnay/cxx/blob/master/demo/src/blobstore.cc) -//! -//! To look at the code generated in both languages for the example by the CXX -//! code generators: -//! -//! ```console -//! # run Rust code generator and print to stdout -//! # (requires https://github.com/dtolnay/cargo-expand) -//! $ cargo expand --manifest-path demo/Cargo.toml -//! -//! # run C++ code generator and print to stdout -//! $ cargo run --manifest-path gen/cmd/Cargo.toml -- demo/src/main.rs -//! ``` -//! -//! <br> -//! -//! # Details -//! -//! As seen in the example, the language of the FFI boundary involves 3 kinds of -//! items: -//! -//! - **Shared structs** — their fields are made visible to both -//! languages. The definition written within cxx::bridge is the single source -//! of truth. -//! -//! - **Opaque types** — their fields are secret from the other language. -//! These cannot be passed across the FFI by value but only behind an -//! indirection, such as a reference `&`, a Rust `Box`, or a `UniquePtr`. Can -//! be a type alias for an arbitrarily complicated generic language-specific -//! type depending on your use case. -//! -//! - **Functions** — implemented in either language, callable from the -//! other language. -//! -//! Within the `extern "Rust"` part of the CXX bridge we list the types and -//! functions for which Rust is the source of truth. These all implicitly refer -//! to the `super` module, the parent module of the CXX bridge. You can think of -//! the two items listed in the example above as being like `use -//! super::MultiBuf` and `use super::next_chunk` except re-exported to C++. The -//! parent module will either contain the definitions directly for simple -//! things, or contain the relevant `use` statements to bring them into scope -//! from elsewhere. -//! -//! Within the `extern "C++"` part, we list types and functions for which C++ is -//! the source of truth, as well as the header(s) that declare those APIs. In -//! the future it's possible that this section could be generated bindgen-style -//! from the headers but for now we need the signatures written out; static -//! assertions will verify that they are accurate. -//! -//! Your function implementations themselves, whether in C++ or Rust, *do not* -//! need to be defined as `extern "C"` ABI or no\_mangle. CXX will put in the -//! right shims where necessary to make it all work. -//! -//! <br> -//! -//! # Comparison vs bindgen and cbindgen -//! -//! Notice that with CXX there is repetition of all the function signatures: -//! they are typed out once where the implementation is defined (in C++ or Rust) -//! and again inside the cxx::bridge module, though compile-time assertions -//! guarantee these are kept in sync. This is different from [bindgen] and -//! [cbindgen] where function signatures are typed by a human once and the tool -//! consumes them in one language and emits them in the other language. -//! -//! [bindgen]: https://github.com/rust-lang/rust-bindgen -//! [cbindgen]: https://github.com/eqrion/cbindgen/ -//! -//! This is because CXX fills a somewhat different role. It is a lower level -//! tool than bindgen or cbindgen in a sense; you can think of it as being a -//! replacement for the concept of `extern "C"` signatures as we know them, -//! rather than a replacement for a bindgen. It would be reasonable to build a -//! higher level bindgen-like tool on top of CXX which consumes a C++ header -//! and/or Rust module (and/or IDL like Thrift) as source of truth and generates -//! the cxx::bridge, eliminating the repetition while leveraging the static -//! analysis safety guarantees of CXX. -//! -//! But note in other ways CXX is higher level than the bindgens, with rich -//! support for common standard library types. Frequently with bindgen when we -//! are dealing with an idiomatic C++ API we would end up manually wrapping that -//! API in C-style raw pointer functions, applying bindgen to get unsafe raw -//! pointer Rust functions, and replicating the API again to expose those -//! idiomatically in Rust. That's a much worse form of repetition because it is -//! unsafe all the way through. -//! -//! By using a CXX bridge as the shared understanding between the languages, -//! rather than `extern "C"` C-style signatures as the shared understanding, -//! common FFI use cases become expressible using 100% safe code. -//! -//! It would also be reasonable to mix and match, using CXX bridge for the 95% -//! of your FFI that is straightforward and doing the remaining few oddball -//! signatures the old fashioned way with bindgen and cbindgen, if for some -//! reason CXX's static restrictions get in the way. Please file an issue if you -//! end up taking this approach so that we know what ways it would be worthwhile -//! to make the tool more expressive. -//! -//! <br> -//! -//! # Cargo-based setup -//! -//! For builds that are orchestrated by Cargo, you will use a build script that -//! runs CXX's C++ code generator and compiles the resulting C++ code along with -//! any other C++ code for your crate. -//! -//! The canonical build script is as follows. The indicated line returns a -//! [`cc::Build`] instance (from the usual widely used `cc` crate) on which you -//! can set up any additional source files and compiler flags as normal. -//! -//! [`cc::Build`]: https://docs.rs/cc/1.0/cc/struct.Build.html -//! -//! ```toml -//! # Cargo.toml -//! -//! [build-dependencies] -//! cxx-build = "1.0" -//! ``` -//! -//! ```no_run -//! // build.rs -//! -//! fn main() { -//! cxx_build::bridge("src/main.rs") // returns a cc::Build -//! .file("src/demo.cc") -//! .flag_if_supported("-std=c++11") -//! .compile("cxxbridge-demo"); -//! -//! println!("cargo:rerun-if-changed=src/main.rs"); -//! println!("cargo:rerun-if-changed=src/demo.cc"); -//! println!("cargo:rerun-if-changed=include/demo.h"); -//! } -//! ``` -//! -//! <br><br> -//! -//! # Non-Cargo setup -//! -//! For use in non-Cargo builds like Bazel or Buck, CXX provides an alternate -//! way of invoking the C++ code generator as a standalone command line tool. -//! The tool is packaged as the `cxxbridge-cmd` crate on crates.io or can be -//! built from the *gen/cmd* directory of <https://github.com/dtolnay/cxx>. -//! -//! ```bash -//! $ cargo install cxxbridge-cmd -//! -//! $ cxxbridge src/main.rs --header > path/to/mybridge.h -//! $ cxxbridge src/main.rs > path/to/mybridge.cc -//! ``` -//! -//! <br> -//! -//! # Safety -//! -//! Be aware that the design of this library is intentionally restrictive and -//! opinionated! It isn't a goal to be powerful enough to handle arbitrary -//! signatures in either language. Instead this project is about carving out a -//! reasonably expressive set of functionality about which we can make useful -//! safety guarantees today and maybe extend over time. You may find that it -//! takes some practice to use CXX bridge effectively as it won't work in all -//! the ways that you are used to. -//! -//! Some of the considerations that go into ensuring safety are: -//! -//! - By design, our paired code generators work together to control both sides -//! of the FFI boundary. Ordinarily in Rust writing your own `extern "C"` -//! blocks is unsafe because the Rust compiler has no way to know whether the -//! signatures you've written actually match the signatures implemented in the -//! other language. With CXX we achieve that visibility and know what's on the -//! other side. -//! -//! - Our static analysis detects and prevents passing types by value that -//! shouldn't be passed by value from C++ to Rust, for example because they -//! may contain internal pointers that would be screwed up by Rust's move -//! behavior. -//! -//! - To many people's surprise, it is possible to have a struct in Rust and a -//! struct in C++ with exactly the same layout / fields / alignment / -//! everything, and still not the same ABI when passed by value. This is a -//! longstanding bindgen bug that leads to segfaults in absolutely -//! correct-looking code ([rust-lang/rust-bindgen#778]). CXX knows about this -//! and can insert the necessary zero-cost workaround transparently where -//! needed, so go ahead and pass your structs by value without worries. This -//! is made possible by owning both sides of the boundary rather than just -//! one. -//! -//! - Template instantiations: for example in order to expose a UniquePtr\<T\> -//! type in Rust backed by a real C++ unique\_ptr, we have a way of using a -//! Rust trait to connect the behavior back to the template instantiations -//! performed by the other language. -//! -//! [rust-lang/rust-bindgen#778]: https://github.com/rust-lang/rust-bindgen/issues/778 -//! -//! <br> -//! -//! # Builtin types -//! -//! In addition to all the primitive types (i32 <=> int32_t), the -//! following common types may be used in the fields of shared structs and the -//! arguments and returns of functions. -//! -//! <table> -//! <tr><th>name in Rust</th><th>name in C++</th><th>restrictions</th></tr> -//! <tr><td>String</td><td>rust::String</td><td></td></tr> -//! <tr><td>&str</td><td>rust::Str</td><td></td></tr> -//! <tr><td>&[T]</td><td>rust::Slice<const T></td><td><sup><i>cannot hold opaque C++ type</i></sup></td></tr> -//! <tr><td>&mut [T]</td><td>rust::Slice<T></td><td><sup><i>cannot hold opaque C++ type</i></sup></td></tr> -//! <tr><td><a href="struct.CxxString.html">CxxString</a></td><td>std::string</td><td><sup><i>cannot be passed by value</i></sup></td></tr> -//! <tr><td>Box<T></td><td>rust::Box<T></td><td><sup><i>cannot hold opaque C++ type</i></sup></td></tr> -//! <tr><td><a href="struct.UniquePtr.html">UniquePtr<T></a></td><td>std::unique_ptr<T></td><td><sup><i>cannot hold opaque Rust type</i></sup></td></tr> -//! <tr><td><a href="struct.SharedPtr.html">SharedPtr<T></a></td><td>std::shared_ptr<T></td><td><sup><i>cannot hold opaque Rust type</i></sup></td></tr> -//! <tr><td>[T; N]</td><td>std::array<T, N></td><td><sup><i>cannot hold opaque C++ type</i></sup></td></tr> -//! <tr><td>Vec<T></td><td>rust::Vec<T></td><td><sup><i>cannot hold opaque C++ type</i></sup></td></tr> -//! <tr><td><a href="struct.CxxVector.html">CxxVector<T></a></td><td>std::vector<T></td><td><sup><i>cannot be passed by value, cannot hold opaque Rust type</i></sup></td></tr> -//! <tr><td>*mut T, *const T</td><td>T*, const T*</td><td><sup><i>fn with a raw pointer argument must be declared unsafe to call</i></sup></td></tr> -//! <tr><td>fn(T, U) -> V</td><td>rust::Fn<V(T, U)></td><td><sup><i>only passing from Rust to C++ is implemented so far</i></sup></td></tr> -//! <tr><td>Result<T></td><td>throw/catch</td><td><sup><i>allowed as return type only</i></sup></td></tr> -//! </table> -//! -//! The C++ API of the `rust` namespace is defined by the *include/cxx.h* file -//! in <https://github.com/dtolnay/cxx>. You will need to include this header in -//! your C++ code when working with those types. -//! -//! The following types are intended to be supported "soon" but are just not -//! implemented yet. I don't expect any of these to be hard to make work but -//! it's a matter of designing a nice API for each in its non-native language. -//! -//! <table> -//! <tr><th>name in Rust</th><th>name in C++</th></tr> -//! <tr><td>BTreeMap<K, V></td><td><sup><i>tbd</i></sup></td></tr> -//! <tr><td>HashMap<K, V></td><td><sup><i>tbd</i></sup></td></tr> -//! <tr><td>Arc<T></td><td><sup><i>tbd</i></sup></td></tr> -//! <tr><td>Option<T></td><td><sup><i>tbd</i></sup></td></tr> -//! <tr><td><sup><i>tbd</i></sup></td><td>std::map<K, V></td></tr> -//! <tr><td><sup><i>tbd</i></sup></td><td>std::unordered_map<K, V></td></tr> -//! </table> - -#![no_std] -#![doc(html_root_url = "https://docs.rs/cxx/1.0.94")] -#![deny( - improper_ctypes, - improper_ctypes_definitions, - missing_docs, - unsafe_op_in_unsafe_fn -)] -#![cfg_attr(doc_cfg, feature(doc_cfg))] -#![allow(non_camel_case_types)] -#![allow( - clippy::cognitive_complexity, - clippy::declare_interior_mutable_const, - clippy::doc_markdown, - clippy::empty_enum, - clippy::extra_unused_type_parameters, - clippy::inherent_to_string, - clippy::items_after_statements, - clippy::large_enum_variant, - clippy::len_without_is_empty, - clippy::missing_errors_doc, - clippy::missing_safety_doc, - clippy::module_inception, - clippy::module_name_repetitions, - clippy::must_use_candidate, - clippy::needless_doctest_main, - clippy::new_without_default, - clippy::or_fun_call, - clippy::ptr_arg, - clippy::toplevel_ref_arg, - clippy::transmute_undefined_repr, // clippy bug: https://github.com/rust-lang/rust-clippy/issues/8417 - clippy::useless_let_if_seq, - clippy::wrong_self_convention -)] - -#[cfg(built_with_cargo)] -extern crate link_cplusplus; - -extern crate self as cxx; - -#[doc(hidden)] -pub extern crate core; - -#[cfg(feature = "alloc")] -#[doc(hidden)] -pub extern crate alloc; - -#[cfg(not(feature = "alloc"))] -extern crate core as alloc; - -#[cfg(feature = "std")] -#[doc(hidden)] -pub extern crate std; - -// Block inadvertent use of items from libstd, which does not otherwise produce -// a compile-time error on edition 2018+. -#[cfg(not(feature = "std"))] -extern crate core as std; - -#[cfg(not(any(feature = "alloc", cxx_experimental_no_alloc)))] -compile_error! { - r#"cxx support for no_alloc is incomplete and semver exempt; you must build with at least one of feature="std", feature="alloc", or RUSTFLAGS='--cfg cxx_experimental_no_alloc'"# -} - -#[cfg(all(compile_error_if_alloc, feature = "alloc"))] -compile_error! { - r#"feature="alloc" is unexpectedly enabled"# -} - -#[cfg(all(compile_error_if_std, feature = "std"))] -compile_error! { - r#"feature="std" is unexpectedly enabled"# -} - -#[macro_use] -mod macros; - -mod c_char; -mod cxx_vector; -mod exception; -mod extern_type; -mod fmt; -mod function; -mod hash; -mod lossy; -pub mod memory; -mod opaque; -mod result; -mod rust_slice; -mod rust_str; -mod rust_string; -mod rust_type; -mod rust_vec; -mod shared_ptr; -mod sip; -#[path = "cxx_string.rs"] -mod string; -mod symbols; -mod type_id; -mod unique_ptr; -mod unwind; -pub mod vector; -mod weak_ptr; - -pub use crate::cxx_vector::CxxVector; -#[cfg(feature = "alloc")] -pub use crate::exception::Exception; -pub use crate::extern_type::{kind, ExternType}; -pub use crate::shared_ptr::SharedPtr; -pub use crate::string::CxxString; -pub use crate::unique_ptr::UniquePtr; -pub use crate::weak_ptr::WeakPtr; -pub use cxxbridge_macro::bridge; - -/// Synonym for `CxxString`. -/// -/// To avoid confusion with Rust's standard library string you probably -/// shouldn't import this type with `use`. Instead, write `cxx::String`, or -/// import and use `CxxString`. -pub type String = CxxString; - -/// Synonym for `CxxVector`. -/// -/// To avoid confusion with Rust's standard library vector you probably -/// shouldn't import this type with `use`. Instead, write `cxx::Vector<T>`, or -/// import and use `CxxVector`. -pub type Vector<T> = CxxVector<T>; - -// Not public API. -#[doc(hidden)] -pub mod private { - pub use crate::c_char::c_char; - pub use crate::cxx_vector::VectorElement; - pub use crate::extern_type::{verify_extern_kind, verify_extern_type}; - pub use crate::function::FatFunction; - pub use crate::hash::hash; - pub use crate::opaque::Opaque; - #[cfg(feature = "alloc")] - pub use crate::result::{r#try, Result}; - pub use crate::rust_slice::RustSlice; - pub use crate::rust_str::RustStr; - #[cfg(feature = "alloc")] - pub use crate::rust_string::RustString; - pub use crate::rust_type::{ImplBox, ImplVec, RustType}; - #[cfg(feature = "alloc")] - pub use crate::rust_vec::RustVec; - pub use crate::shared_ptr::SharedPtrTarget; - pub use crate::string::StackString; - pub use crate::unique_ptr::UniquePtrTarget; - pub use crate::unwind::prevent_unwind; - pub use crate::weak_ptr::WeakPtrTarget; - pub use core::{concat, module_path}; - pub use cxxbridge_macro::type_id; -} - -mod actually_private { - pub trait Private {} -} - -macro_rules! chars { - ($($ch:ident)*) => { - $( - #[doc(hidden)] - pub enum $ch {} - )* - }; -} - -chars! { - _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 - A B C D E F G H I J K L M N O P Q R S T U V W X Y Z - a b c d e f g h i j k l m n o p q r s t u v w x y z - __ // underscore -} - -#[repr(transparent)] -struct void(core::ffi::c_void); diff --git a/vendor/cxx/src/lossy.rs b/vendor/cxx/src/lossy.rs deleted file mode 100644 index 8ccf0f93b..000000000 --- a/vendor/cxx/src/lossy.rs +++ /dev/null @@ -1,67 +0,0 @@ -use core::char; -use core::fmt::{self, Write as _}; -use core::str; - -pub fn display(mut bytes: &[u8], f: &mut fmt::Formatter) -> fmt::Result { - loop { - match str::from_utf8(bytes) { - Ok(valid) => return f.write_str(valid), - Err(utf8_error) => { - let valid_up_to = utf8_error.valid_up_to(); - let valid = unsafe { str::from_utf8_unchecked(&bytes[..valid_up_to]) }; - f.write_str(valid)?; - f.write_char(char::REPLACEMENT_CHARACTER)?; - if let Some(error_len) = utf8_error.error_len() { - bytes = &bytes[valid_up_to + error_len..]; - } else { - return Ok(()); - } - } - } - } -} - -pub fn debug(mut bytes: &[u8], f: &mut fmt::Formatter) -> fmt::Result { - f.write_char('"')?; - - while !bytes.is_empty() { - let from_utf8_result = str::from_utf8(bytes); - let valid = match from_utf8_result { - Ok(valid) => valid, - Err(utf8_error) => { - let valid_up_to = utf8_error.valid_up_to(); - unsafe { str::from_utf8_unchecked(&bytes[..valid_up_to]) } - } - }; - - let mut written = 0; - for (i, ch) in valid.char_indices() { - let esc = ch.escape_debug(); - if esc.len() != 1 && ch != '\'' { - f.write_str(&valid[written..i])?; - for ch in esc { - f.write_char(ch)?; - } - written = i + ch.len_utf8(); - } - } - f.write_str(&valid[written..])?; - - match from_utf8_result { - Ok(_valid) => break, - Err(utf8_error) => { - let end_of_broken = if let Some(error_len) = utf8_error.error_len() { - valid.len() + error_len - } else { - bytes.len() - }; - for b in &bytes[valid.len()..end_of_broken] { - write!(f, "\\x{:02x}", b)?; - } - bytes = &bytes[end_of_broken..]; - } - } - } - - f.write_char('"') -} diff --git a/vendor/cxx/src/macros/assert.rs b/vendor/cxx/src/macros/assert.rs deleted file mode 100644 index 5d5ea9e35..000000000 --- a/vendor/cxx/src/macros/assert.rs +++ /dev/null @@ -1,7 +0,0 @@ -#[macro_export] -#[doc(hidden)] -macro_rules! const_assert_eq { - ($left:expr, $right:expr $(,)?) => { - const _: [(); $left] = [(); $right]; - }; -} diff --git a/vendor/cxx/src/macros/concat.rs b/vendor/cxx/src/macros/concat.rs deleted file mode 100644 index 5ee77c527..000000000 --- a/vendor/cxx/src/macros/concat.rs +++ /dev/null @@ -1,8 +0,0 @@ -#[macro_export] -#[doc(hidden)] -macro_rules! attr { - (#[$name:ident = $value:expr] $($rest:tt)*) => { - #[$name = $value] - $($rest)* - }; -} diff --git a/vendor/cxx/src/macros/mod.rs b/vendor/cxx/src/macros/mod.rs deleted file mode 100644 index d12d96bd4..000000000 --- a/vendor/cxx/src/macros/mod.rs +++ /dev/null @@ -1,4 +0,0 @@ -#[macro_use] -mod assert; -#[macro_use] -mod concat; diff --git a/vendor/cxx/src/memory.rs b/vendor/cxx/src/memory.rs deleted file mode 100644 index fd8df12a8..000000000 --- a/vendor/cxx/src/memory.rs +++ /dev/null @@ -1,9 +0,0 @@ -//! Less used details of `UniquePtr` and `SharedPtr`. -//! -//! The pointer types themselves are exposed at the crate root. - -pub use crate::shared_ptr::SharedPtrTarget; -pub use crate::unique_ptr::UniquePtrTarget; -pub use crate::weak_ptr::WeakPtrTarget; -#[doc(no_inline)] -pub use cxx::{SharedPtr, UniquePtr}; diff --git a/vendor/cxx/src/opaque.rs b/vendor/cxx/src/opaque.rs deleted file mode 100644 index e0f8ce2c2..000000000 --- a/vendor/cxx/src/opaque.rs +++ /dev/null @@ -1,20 +0,0 @@ -#![allow(missing_docs)] - -use crate::void; -use core::marker::{PhantomData, PhantomPinned}; -use core::mem; - -// . size = 0 -// . align = 1 -// . ffi-safe -// . !Send -// . !Sync -// . !Unpin -#[repr(C, packed)] -pub struct Opaque { - _private: [*const void; 0], - _pinned: PhantomData<PhantomPinned>, -} - -const_assert_eq!(0, mem::size_of::<Opaque>()); -const_assert_eq!(1, mem::align_of::<Opaque>()); diff --git a/vendor/cxx/src/result.rs b/vendor/cxx/src/result.rs deleted file mode 100644 index ba77858e3..000000000 --- a/vendor/cxx/src/result.rs +++ /dev/null @@ -1,70 +0,0 @@ -#![cfg(feature = "alloc")] -#![allow(missing_docs)] - -use crate::exception::Exception; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use core::fmt::Display; -use core::ptr::{self, NonNull}; -use core::result::Result as StdResult; -use core::slice; -use core::str; - -#[repr(C)] -#[derive(Copy, Clone)] -pub struct PtrLen { - pub ptr: NonNull<u8>, - pub len: usize, -} - -#[repr(C)] -pub union Result { - err: PtrLen, - ok: *const u8, // null -} - -pub unsafe fn r#try<T, E>(ret: *mut T, result: StdResult<T, E>) -> Result -where - E: Display, -{ - match result { - Ok(ok) => { - unsafe { ptr::write(ret, ok) } - Result { ok: ptr::null() } - } - Err(err) => unsafe { to_c_error(err.to_string()) }, - } -} - -unsafe fn to_c_error(msg: String) -> Result { - let mut msg = msg; - unsafe { msg.as_mut_vec() }.push(b'\0'); - let ptr = msg.as_ptr(); - let len = msg.len(); - - extern "C" { - #[link_name = "cxxbridge1$error"] - fn error(ptr: *const u8, len: usize) -> NonNull<u8>; - } - - let copy = unsafe { error(ptr, len) }; - let err = PtrLen { ptr: copy, len }; - Result { err } -} - -impl Result { - pub unsafe fn exception(self) -> StdResult<(), Exception> { - unsafe { - if self.ok.is_null() { - Ok(()) - } else { - let err = self.err; - let slice = slice::from_raw_parts_mut(err.ptr.as_ptr(), err.len); - let s = str::from_utf8_unchecked_mut(slice); - Err(Exception { - what: Box::from_raw(s), - }) - } - } - } -} diff --git a/vendor/cxx/src/rust_slice.rs b/vendor/cxx/src/rust_slice.rs deleted file mode 100644 index 069631176..000000000 --- a/vendor/cxx/src/rust_slice.rs +++ /dev/null @@ -1,66 +0,0 @@ -#![allow(missing_docs)] - -use core::mem::{self, MaybeUninit}; -use core::ptr::{self, NonNull}; -use core::slice; - -// ABI compatible with C++ rust::Slice<T> (not necessarily &[T]). -#[repr(C)] -pub struct RustSlice { - repr: [MaybeUninit<usize>; mem::size_of::<NonNull<[()]>>() / mem::size_of::<usize>()], -} - -impl RustSlice { - pub fn from_ref<T>(slice: &[T]) -> Self { - let ptr = NonNull::from(slice).cast::<T>(); - let len = slice.len(); - Self::from_raw_parts(ptr, len) - } - - pub fn from_mut<T>(slice: &mut [T]) -> Self { - let ptr = NonNull::from(&mut *slice).cast::<T>(); - let len = slice.len(); - Self::from_raw_parts(ptr, len) - } - - pub unsafe fn as_slice<'a, T>(self) -> &'a [T] { - let ptr = self.as_non_null_ptr().as_ptr(); - let len = self.len(); - unsafe { slice::from_raw_parts(ptr, len) } - } - - pub unsafe fn as_mut_slice<'a, T>(self) -> &'a mut [T] { - let ptr = self.as_non_null_ptr().as_ptr(); - let len = self.len(); - unsafe { slice::from_raw_parts_mut(ptr, len) } - } - - pub(crate) fn from_raw_parts<T>(ptr: NonNull<T>, len: usize) -> Self { - // TODO: use NonNull::from_raw_parts(ptr.cast(), len) when stable. - // https://doc.rust-lang.org/nightly/std/ptr/struct.NonNull.html#method.from_raw_parts - // https://github.com/rust-lang/rust/issues/81513 - let ptr = ptr::slice_from_raw_parts_mut(ptr.as_ptr().cast(), len); - unsafe { mem::transmute::<NonNull<[()]>, RustSlice>(NonNull::new_unchecked(ptr)) } - } - - pub(crate) fn as_non_null_ptr<T>(&self) -> NonNull<T> { - let rust_slice = RustSlice { repr: self.repr }; - let repr = unsafe { mem::transmute::<RustSlice, NonNull<[()]>>(rust_slice) }; - repr.cast() - } - - pub(crate) fn len(&self) -> usize { - let rust_slice = RustSlice { repr: self.repr }; - let repr = unsafe { mem::transmute::<RustSlice, NonNull<[()]>>(rust_slice) }; - // TODO: use repr.len() when stable. - // https://doc.rust-lang.org/nightly/std/ptr/struct.NonNull.html#method.len - // https://github.com/rust-lang/rust/issues/71146 - unsafe { repr.as_ref() }.len() - } -} - -const_assert_eq!(mem::size_of::<NonNull<[()]>>(), mem::size_of::<RustSlice>()); -const_assert_eq!( - mem::align_of::<NonNull<[()]>>(), - mem::align_of::<RustSlice>(), -); diff --git a/vendor/cxx/src/rust_str.rs b/vendor/cxx/src/rust_str.rs deleted file mode 100644 index b1b46e3e9..000000000 --- a/vendor/cxx/src/rust_str.rs +++ /dev/null @@ -1,28 +0,0 @@ -#![allow(missing_docs)] - -use core::mem::{self, MaybeUninit}; -use core::ptr::NonNull; -use core::str; - -// ABI compatible with C++ rust::Str (not necessarily &str). -#[repr(C)] -pub struct RustStr { - repr: [MaybeUninit<usize>; mem::size_of::<NonNull<str>>() / mem::size_of::<usize>()], -} - -impl RustStr { - pub fn from(repr: &str) -> Self { - let repr = NonNull::from(repr); - unsafe { mem::transmute::<NonNull<str>, RustStr>(repr) } - } - - pub unsafe fn as_str<'a>(self) -> &'a str { - unsafe { - let repr = mem::transmute::<RustStr, NonNull<str>>(self); - &*repr.as_ptr() - } - } -} - -const_assert_eq!(mem::size_of::<NonNull<str>>(), mem::size_of::<RustStr>()); -const_assert_eq!(mem::align_of::<NonNull<str>>(), mem::align_of::<RustStr>()); diff --git a/vendor/cxx/src/rust_string.rs b/vendor/cxx/src/rust_string.rs deleted file mode 100644 index 0e0c5a836..000000000 --- a/vendor/cxx/src/rust_string.rs +++ /dev/null @@ -1,48 +0,0 @@ -#![cfg(feature = "alloc")] -#![allow(missing_docs)] - -use alloc::string::String; -use core::mem::{self, MaybeUninit}; -use core::ptr; - -// ABI compatible with C++ rust::String (not necessarily alloc::string::String). -#[repr(C)] -pub struct RustString { - repr: [MaybeUninit<usize>; mem::size_of::<String>() / mem::size_of::<usize>()], -} - -impl RustString { - pub fn from(s: String) -> Self { - unsafe { mem::transmute::<String, RustString>(s) } - } - - pub fn from_ref(s: &String) -> &Self { - unsafe { &*(s as *const String as *const RustString) } - } - - pub fn from_mut(s: &mut String) -> &mut Self { - unsafe { &mut *(s as *mut String as *mut RustString) } - } - - pub fn into_string(self) -> String { - unsafe { mem::transmute::<RustString, String>(self) } - } - - pub fn as_string(&self) -> &String { - unsafe { &*(self as *const RustString as *const String) } - } - - pub fn as_mut_string(&mut self) -> &mut String { - unsafe { &mut *(self as *mut RustString as *mut String) } - } -} - -impl Drop for RustString { - fn drop(&mut self) { - unsafe { ptr::drop_in_place(self.as_mut_string()) } - } -} - -const_assert_eq!(mem::size_of::<[usize; 3]>(), mem::size_of::<RustString>()); -const_assert_eq!(mem::size_of::<String>(), mem::size_of::<RustString>()); -const_assert_eq!(mem::align_of::<String>(), mem::align_of::<RustString>()); diff --git a/vendor/cxx/src/rust_type.rs b/vendor/cxx/src/rust_type.rs deleted file mode 100644 index eacb5309f..000000000 --- a/vendor/cxx/src/rust_type.rs +++ /dev/null @@ -1,5 +0,0 @@ -#![allow(missing_docs)] - -pub unsafe trait RustType {} -pub unsafe trait ImplBox {} -pub unsafe trait ImplVec {} diff --git a/vendor/cxx/src/rust_vec.rs b/vendor/cxx/src/rust_vec.rs deleted file mode 100644 index acb7e8902..000000000 --- a/vendor/cxx/src/rust_vec.rs +++ /dev/null @@ -1,115 +0,0 @@ -#![cfg(feature = "alloc")] -#![allow(missing_docs)] - -use crate::rust_string::RustString; -use alloc::string::String; -use alloc::vec::Vec; -use core::ffi::c_void; -use core::marker::PhantomData; -use core::mem::{self, ManuallyDrop, MaybeUninit}; -use core::ptr; - -// ABI compatible with C++ rust::Vec<T> (not necessarily alloc::vec::Vec<T>). -#[repr(C)] -pub struct RustVec<T> { - repr: [MaybeUninit<usize>; mem::size_of::<Vec<c_void>>() / mem::size_of::<usize>()], - marker: PhantomData<Vec<T>>, -} - -impl<T> RustVec<T> { - pub fn new() -> Self { - Self::from(Vec::new()) - } - - pub fn from(v: Vec<T>) -> Self { - unsafe { mem::transmute::<Vec<T>, RustVec<T>>(v) } - } - - pub fn from_ref(v: &Vec<T>) -> &Self { - unsafe { &*(v as *const Vec<T> as *const RustVec<T>) } - } - - pub fn from_mut(v: &mut Vec<T>) -> &mut Self { - unsafe { &mut *(v as *mut Vec<T> as *mut RustVec<T>) } - } - - pub fn into_vec(self) -> Vec<T> { - unsafe { mem::transmute::<RustVec<T>, Vec<T>>(self) } - } - - pub fn as_vec(&self) -> &Vec<T> { - unsafe { &*(self as *const RustVec<T> as *const Vec<T>) } - } - - pub fn as_mut_vec(&mut self) -> &mut Vec<T> { - unsafe { &mut *(self as *mut RustVec<T> as *mut Vec<T>) } - } - - pub fn len(&self) -> usize { - self.as_vec().len() - } - - pub fn capacity(&self) -> usize { - self.as_vec().capacity() - } - - pub fn as_ptr(&self) -> *const T { - self.as_vec().as_ptr() - } - - pub fn reserve_total(&mut self, new_cap: usize) { - let vec = self.as_mut_vec(); - if new_cap > vec.capacity() { - let additional = new_cap - vec.len(); - vec.reserve(additional); - } - } - - pub unsafe fn set_len(&mut self, len: usize) { - unsafe { self.as_mut_vec().set_len(len) } - } - - pub fn truncate(&mut self, len: usize) { - self.as_mut_vec().truncate(len); - } -} - -impl RustVec<RustString> { - pub fn from_vec_string(v: Vec<String>) -> Self { - let mut v = ManuallyDrop::new(v); - let ptr = v.as_mut_ptr().cast::<RustString>(); - let len = v.len(); - let cap = v.capacity(); - Self::from(unsafe { Vec::from_raw_parts(ptr, len, cap) }) - } - - pub fn from_ref_vec_string(v: &Vec<String>) -> &Self { - Self::from_ref(unsafe { &*(v as *const Vec<String> as *const Vec<RustString>) }) - } - - pub fn from_mut_vec_string(v: &mut Vec<String>) -> &mut Self { - Self::from_mut(unsafe { &mut *(v as *mut Vec<String> as *mut Vec<RustString>) }) - } - - pub fn into_vec_string(self) -> Vec<String> { - let mut v = ManuallyDrop::new(self.into_vec()); - let ptr = v.as_mut_ptr().cast::<String>(); - let len = v.len(); - let cap = v.capacity(); - unsafe { Vec::from_raw_parts(ptr, len, cap) } - } - - pub fn as_vec_string(&self) -> &Vec<String> { - unsafe { &*(self as *const RustVec<RustString> as *const Vec<String>) } - } - - pub fn as_mut_vec_string(&mut self) -> &mut Vec<String> { - unsafe { &mut *(self as *mut RustVec<RustString> as *mut Vec<String>) } - } -} - -impl<T> Drop for RustVec<T> { - fn drop(&mut self) { - unsafe { ptr::drop_in_place(self.as_mut_vec()) } - } -} diff --git a/vendor/cxx/src/shared_ptr.rs b/vendor/cxx/src/shared_ptr.rs deleted file mode 100644 index 64c866196..000000000 --- a/vendor/cxx/src/shared_ptr.rs +++ /dev/null @@ -1,283 +0,0 @@ -use crate::fmt::display; -use crate::kind::Trivial; -use crate::string::CxxString; -use crate::weak_ptr::{WeakPtr, WeakPtrTarget}; -use crate::ExternType; -use core::ffi::c_void; -use core::fmt::{self, Debug, Display}; -use core::marker::PhantomData; -use core::mem::MaybeUninit; -use core::ops::Deref; - -/// Binding to C++ `std::shared_ptr<T>`. -#[repr(C)] -pub struct SharedPtr<T> -where - T: SharedPtrTarget, -{ - repr: [MaybeUninit<*mut c_void>; 2], - ty: PhantomData<T>, -} - -impl<T> SharedPtr<T> -where - T: SharedPtrTarget, -{ - /// Makes a new SharedPtr wrapping a null pointer. - /// - /// Matches the behavior of default-constructing a std::shared\_ptr. - pub fn null() -> Self { - let mut shared_ptr = MaybeUninit::<SharedPtr<T>>::uninit(); - let new = shared_ptr.as_mut_ptr().cast(); - unsafe { - T::__null(new); - shared_ptr.assume_init() - } - } - - /// Allocates memory on the heap and makes a SharedPtr owner for it. - pub fn new(value: T) -> Self - where - T: ExternType<Kind = Trivial>, - { - let mut shared_ptr = MaybeUninit::<SharedPtr<T>>::uninit(); - let new = shared_ptr.as_mut_ptr().cast(); - unsafe { - T::__new(value, new); - shared_ptr.assume_init() - } - } - - /// Checks whether the SharedPtr does not own an object. - /// - /// This is the opposite of [std::shared_ptr\<T\>::operator bool](https://en.cppreference.com/w/cpp/memory/shared_ptr/operator_bool). - pub fn is_null(&self) -> bool { - let this = self as *const Self as *const c_void; - let ptr = unsafe { T::__get(this) }; - ptr.is_null() - } - - /// Returns a reference to the object owned by this SharedPtr if any, - /// otherwise None. - pub fn as_ref(&self) -> Option<&T> { - let this = self as *const Self as *const c_void; - unsafe { T::__get(this).as_ref() } - } - - /// Constructs new WeakPtr as a non-owning reference to the object managed - /// by `self`. If `self` manages no object, the WeakPtr manages no object - /// too. - /// - /// Matches the behavior of [std::weak_ptr\<T\>::weak_ptr(const std::shared_ptr\<T\> \&)](https://en.cppreference.com/w/cpp/memory/weak_ptr/weak_ptr). - pub fn downgrade(self: &SharedPtr<T>) -> WeakPtr<T> - where - T: WeakPtrTarget, - { - let this = self as *const Self as *const c_void; - let mut weak_ptr = MaybeUninit::<WeakPtr<T>>::uninit(); - let new = weak_ptr.as_mut_ptr().cast(); - unsafe { - T::__downgrade(this, new); - weak_ptr.assume_init() - } - } -} - -unsafe impl<T> Send for SharedPtr<T> where T: Send + Sync + SharedPtrTarget {} -unsafe impl<T> Sync for SharedPtr<T> where T: Send + Sync + SharedPtrTarget {} - -impl<T> Clone for SharedPtr<T> -where - T: SharedPtrTarget, -{ - fn clone(&self) -> Self { - let mut shared_ptr = MaybeUninit::<SharedPtr<T>>::uninit(); - let new = shared_ptr.as_mut_ptr().cast(); - let this = self as *const Self as *mut c_void; - unsafe { - T::__clone(this, new); - shared_ptr.assume_init() - } - } -} - -// SharedPtr is not a self-referential type and is safe to move out of a Pin, -// regardless whether the pointer's target is Unpin. -impl<T> Unpin for SharedPtr<T> where T: SharedPtrTarget {} - -impl<T> Drop for SharedPtr<T> -where - T: SharedPtrTarget, -{ - fn drop(&mut self) { - let this = self as *mut Self as *mut c_void; - unsafe { T::__drop(this) } - } -} - -impl<T> Deref for SharedPtr<T> -where - T: SharedPtrTarget, -{ - type Target = T; - - fn deref(&self) -> &Self::Target { - match self.as_ref() { - Some(target) => target, - None => panic!( - "called deref on a null SharedPtr<{}>", - display(T::__typename), - ), - } - } -} - -impl<T> Debug for SharedPtr<T> -where - T: Debug + SharedPtrTarget, -{ - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - match self.as_ref() { - None => formatter.write_str("nullptr"), - Some(value) => Debug::fmt(value, formatter), - } - } -} - -impl<T> Display for SharedPtr<T> -where - T: Display + SharedPtrTarget, -{ - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - match self.as_ref() { - None => formatter.write_str("nullptr"), - Some(value) => Display::fmt(value, formatter), - } - } -} - -/// Trait bound for types which may be used as the `T` inside of a -/// `SharedPtr<T>` in generic code. -/// -/// This trait has no publicly callable or implementable methods. Implementing -/// it outside of the CXX codebase is not supported. -/// -/// # Example -/// -/// A bound `T: SharedPtrTarget` may be necessary when manipulating -/// [`SharedPtr`] in generic code. -/// -/// ``` -/// use cxx::memory::{SharedPtr, SharedPtrTarget}; -/// use std::fmt::Display; -/// -/// pub fn take_generic_ptr<T>(ptr: SharedPtr<T>) -/// where -/// T: SharedPtrTarget + Display, -/// { -/// println!("the shared_ptr points to: {}", *ptr); -/// } -/// ``` -/// -/// Writing the same generic function without a `SharedPtrTarget` trait bound -/// would not compile. -pub unsafe trait SharedPtrTarget { - #[doc(hidden)] - fn __typename(f: &mut fmt::Formatter) -> fmt::Result; - #[doc(hidden)] - unsafe fn __null(new: *mut c_void); - #[doc(hidden)] - unsafe fn __new(value: Self, new: *mut c_void) - where - Self: Sized, - { - // Opoaque C types do not get this method because they can never exist - // by value on the Rust side of the bridge. - let _ = value; - let _ = new; - unreachable!() - } - #[doc(hidden)] - unsafe fn __clone(this: *const c_void, new: *mut c_void); - #[doc(hidden)] - unsafe fn __get(this: *const c_void) -> *const Self; - #[doc(hidden)] - unsafe fn __drop(this: *mut c_void); -} - -macro_rules! impl_shared_ptr_target { - ($segment:expr, $name:expr, $ty:ty) => { - unsafe impl SharedPtrTarget for $ty { - fn __typename(f: &mut fmt::Formatter) -> fmt::Result { - f.write_str($name) - } - unsafe fn __null(new: *mut c_void) { - extern "C" { - attr! { - #[link_name = concat!("cxxbridge1$std$shared_ptr$", $segment, "$null")] - fn __null(new: *mut c_void); - } - } - unsafe { __null(new) } - } - unsafe fn __new(value: Self, new: *mut c_void) { - extern "C" { - attr! { - #[link_name = concat!("cxxbridge1$std$shared_ptr$", $segment, "$uninit")] - fn __uninit(new: *mut c_void) -> *mut c_void; - } - } - unsafe { __uninit(new).cast::<$ty>().write(value) } - } - unsafe fn __clone(this: *const c_void, new: *mut c_void) { - extern "C" { - attr! { - #[link_name = concat!("cxxbridge1$std$shared_ptr$", $segment, "$clone")] - fn __clone(this: *const c_void, new: *mut c_void); - } - } - unsafe { __clone(this, new) } - } - unsafe fn __get(this: *const c_void) -> *const Self { - extern "C" { - attr! { - #[link_name = concat!("cxxbridge1$std$shared_ptr$", $segment, "$get")] - fn __get(this: *const c_void) -> *const c_void; - } - } - unsafe { __get(this) }.cast() - } - unsafe fn __drop(this: *mut c_void) { - extern "C" { - attr! { - #[link_name = concat!("cxxbridge1$std$shared_ptr$", $segment, "$drop")] - fn __drop(this: *mut c_void); - } - } - unsafe { __drop(this) } - } - } - }; -} - -macro_rules! impl_shared_ptr_target_for_primitive { - ($ty:ident) => { - impl_shared_ptr_target!(stringify!($ty), stringify!($ty), $ty); - }; -} - -impl_shared_ptr_target_for_primitive!(bool); -impl_shared_ptr_target_for_primitive!(u8); -impl_shared_ptr_target_for_primitive!(u16); -impl_shared_ptr_target_for_primitive!(u32); -impl_shared_ptr_target_for_primitive!(u64); -impl_shared_ptr_target_for_primitive!(usize); -impl_shared_ptr_target_for_primitive!(i8); -impl_shared_ptr_target_for_primitive!(i16); -impl_shared_ptr_target_for_primitive!(i32); -impl_shared_ptr_target_for_primitive!(i64); -impl_shared_ptr_target_for_primitive!(isize); -impl_shared_ptr_target_for_primitive!(f32); -impl_shared_ptr_target_for_primitive!(f64); - -impl_shared_ptr_target!("string", "CxxString", CxxString); diff --git a/vendor/cxx/src/sip.rs b/vendor/cxx/src/sip.rs deleted file mode 100644 index 9e1d050a5..000000000 --- a/vendor/cxx/src/sip.rs +++ /dev/null @@ -1,228 +0,0 @@ -// Vendored from libstd: -// https://github.com/rust-lang/rust/blob/1.57.0/library/core/src/hash/sip.rs -// -// TODO: maybe depend on a hasher from crates.io if this becomes annoying to -// maintain, or change this to a simpler one. - -#![cfg(not(feature = "std"))] - -use core::cmp; -use core::hash::Hasher; -use core::mem; -use core::ptr; - -/// An implementation of SipHash 1-3. -/// -/// This is currently the default hashing function used by standard library -/// (e.g., `collections::HashMap` uses it by default). -/// -/// See: <https://131002.net/siphash> -pub struct SipHasher13 { - k0: u64, - k1: u64, - length: usize, // how many bytes we've processed - state: State, // hash State - tail: u64, // unprocessed bytes le - ntail: usize, // how many bytes in tail are valid -} - -#[derive(Clone, Copy)] -#[repr(C)] -struct State { - // v0, v2 and v1, v3 show up in pairs in the algorithm, - // and simd implementations of SipHash will use vectors - // of v02 and v13. By placing them in this order in the struct, - // the compiler can pick up on just a few simd optimizations by itself. - v0: u64, - v2: u64, - v1: u64, - v3: u64, -} - -macro_rules! compress { - ($state:expr) => { - compress!($state.v0, $state.v1, $state.v2, $state.v3) - }; - ($v0:expr, $v1:expr, $v2:expr, $v3:expr) => { - $v0 = $v0.wrapping_add($v1); - $v1 = $v1.rotate_left(13); - $v1 ^= $v0; - $v0 = $v0.rotate_left(32); - $v2 = $v2.wrapping_add($v3); - $v3 = $v3.rotate_left(16); - $v3 ^= $v2; - $v0 = $v0.wrapping_add($v3); - $v3 = $v3.rotate_left(21); - $v3 ^= $v0; - $v2 = $v2.wrapping_add($v1); - $v1 = $v1.rotate_left(17); - $v1 ^= $v2; - $v2 = $v2.rotate_left(32); - }; -} - -/// Loads an integer of the desired type from a byte stream, in LE order. Uses -/// `copy_nonoverlapping` to let the compiler generate the most efficient way -/// to load it from a possibly unaligned address. -/// -/// Unsafe because: unchecked indexing at i..i+size_of(int_ty) -macro_rules! load_int_le { - ($buf:expr, $i:expr, $int_ty:ident) => {{ - debug_assert!($i + mem::size_of::<$int_ty>() <= $buf.len()); - let mut data = 0 as $int_ty; - ptr::copy_nonoverlapping( - $buf.as_ptr().add($i), - &mut data as *mut _ as *mut u8, - mem::size_of::<$int_ty>(), - ); - data.to_le() - }}; -} - -/// Loads a u64 using up to 7 bytes of a byte slice. It looks clumsy but the -/// `copy_nonoverlapping` calls that occur (via `load_int_le!`) all have fixed -/// sizes and avoid calling `memcpy`, which is good for speed. -/// -/// Unsafe because: unchecked indexing at start..start+len -unsafe fn u8to64_le(buf: &[u8], start: usize, len: usize) -> u64 { - debug_assert!(len < 8); - let mut i = 0; // current byte index (from LSB) in the output u64 - let mut out = 0; - if i + 3 < len { - // SAFETY: `i` cannot be greater than `len`, and the caller must guarantee - // that the index start..start+len is in bounds. - out = unsafe { load_int_le!(buf, start + i, u32) } as u64; - i += 4; - } - if i + 1 < len { - // SAFETY: same as above. - out |= (unsafe { load_int_le!(buf, start + i, u16) } as u64) << (i * 8); - i += 2 - } - if i < len { - // SAFETY: same as above. - out |= (unsafe { *buf.get_unchecked(start + i) } as u64) << (i * 8); - i += 1; - } - debug_assert_eq!(i, len); - out -} - -impl SipHasher13 { - /// Creates a new `SipHasher13` with the two initial keys set to 0. - pub fn new() -> Self { - Self::new_with_keys(0, 0) - } - - /// Creates a `SipHasher13` that is keyed off the provided keys. - fn new_with_keys(key0: u64, key1: u64) -> Self { - let mut state = SipHasher13 { - k0: key0, - k1: key1, - length: 0, - state: State { - v0: 0, - v1: 0, - v2: 0, - v3: 0, - }, - tail: 0, - ntail: 0, - }; - state.reset(); - state - } - - fn reset(&mut self) { - self.length = 0; - self.state.v0 = self.k0 ^ 0x736f6d6570736575; - self.state.v1 = self.k1 ^ 0x646f72616e646f6d; - self.state.v2 = self.k0 ^ 0x6c7967656e657261; - self.state.v3 = self.k1 ^ 0x7465646279746573; - self.ntail = 0; - } -} - -impl Hasher for SipHasher13 { - // Note: no integer hashing methods (`write_u*`, `write_i*`) are defined - // for this type. We could add them, copy the `short_write` implementation - // in librustc_data_structures/sip128.rs, and add `write_u*`/`write_i*` - // methods to `SipHasher`, `SipHasher13`, and `DefaultHasher`. This would - // greatly speed up integer hashing by those hashers, at the cost of - // slightly slowing down compile speeds on some benchmarks. See #69152 for - // details. - fn write(&mut self, msg: &[u8]) { - let length = msg.len(); - self.length += length; - - let mut needed = 0; - - if self.ntail != 0 { - needed = 8 - self.ntail; - // SAFETY: `cmp::min(length, needed)` is guaranteed to not be over `length` - self.tail |= unsafe { u8to64_le(msg, 0, cmp::min(length, needed)) } << (8 * self.ntail); - if length < needed { - self.ntail += length; - return; - } else { - self.state.v3 ^= self.tail; - Sip13Rounds::c_rounds(&mut self.state); - self.state.v0 ^= self.tail; - self.ntail = 0; - } - } - - // Buffered tail is now flushed, process new input. - let len = length - needed; - let left = len & 0x7; // len % 8 - - let mut i = needed; - while i < len - left { - // SAFETY: because `len - left` is the biggest multiple of 8 under - // `len`, and because `i` starts at `needed` where `len` is `length - needed`, - // `i + 8` is guaranteed to be less than or equal to `length`. - let mi = unsafe { load_int_le!(msg, i, u64) }; - - self.state.v3 ^= mi; - Sip13Rounds::c_rounds(&mut self.state); - self.state.v0 ^= mi; - - i += 8; - } - - // SAFETY: `i` is now `needed + len.div_euclid(8) * 8`, - // so `i + left` = `needed + len` = `length`, which is by - // definition equal to `msg.len()`. - self.tail = unsafe { u8to64_le(msg, i, left) }; - self.ntail = left; - } - - fn finish(&self) -> u64 { - let mut state = self.state; - - let b: u64 = ((self.length as u64 & 0xff) << 56) | self.tail; - - state.v3 ^= b; - Sip13Rounds::c_rounds(&mut state); - state.v0 ^= b; - - state.v2 ^= 0xff; - Sip13Rounds::d_rounds(&mut state); - - state.v0 ^ state.v1 ^ state.v2 ^ state.v3 - } -} - -struct Sip13Rounds; - -impl Sip13Rounds { - fn c_rounds(state: &mut State) { - compress!(state); - } - - fn d_rounds(state: &mut State) { - compress!(state); - compress!(state); - compress!(state); - } -} diff --git a/vendor/cxx/src/symbols/exception.rs b/vendor/cxx/src/symbols/exception.rs deleted file mode 100644 index b8fe1b5da..000000000 --- a/vendor/cxx/src/symbols/exception.rs +++ /dev/null @@ -1,18 +0,0 @@ -#![cfg(feature = "alloc")] - -use crate::result::PtrLen; -use alloc::boxed::Box; -use alloc::string::String; -use core::ptr::NonNull; -use core::slice; - -#[export_name = "cxxbridge1$exception"] -unsafe extern "C" fn exception(ptr: *const u8, len: usize) -> PtrLen { - let slice = unsafe { slice::from_raw_parts(ptr, len) }; - let string = String::from_utf8_lossy(slice); - let len = string.len(); - let raw_str = Box::into_raw(string.into_owned().into_boxed_str()); - let raw_u8 = raw_str.cast::<u8>(); - let nonnull = unsafe { NonNull::new_unchecked(raw_u8) }; - PtrLen { ptr: nonnull, len } -} diff --git a/vendor/cxx/src/symbols/mod.rs b/vendor/cxx/src/symbols/mod.rs deleted file mode 100644 index e00bb550e..000000000 --- a/vendor/cxx/src/symbols/mod.rs +++ /dev/null @@ -1,5 +0,0 @@ -mod exception; -mod rust_slice; -mod rust_str; -mod rust_string; -mod rust_vec; diff --git a/vendor/cxx/src/symbols/rust_slice.rs b/vendor/cxx/src/symbols/rust_slice.rs deleted file mode 100644 index df215acf5..000000000 --- a/vendor/cxx/src/symbols/rust_slice.rs +++ /dev/null @@ -1,20 +0,0 @@ -use crate::rust_slice::RustSlice; -use core::mem::MaybeUninit; -use core::ptr::{self, NonNull}; - -#[export_name = "cxxbridge1$slice$new"] -unsafe extern "C" fn slice_new(this: &mut MaybeUninit<RustSlice>, ptr: NonNull<()>, len: usize) { - let this = this.as_mut_ptr(); - let rust_slice = RustSlice::from_raw_parts(ptr, len); - unsafe { ptr::write(this, rust_slice) } -} - -#[export_name = "cxxbridge1$slice$ptr"] -unsafe extern "C" fn slice_ptr(this: &RustSlice) -> NonNull<()> { - this.as_non_null_ptr() -} - -#[export_name = "cxxbridge1$slice$len"] -unsafe extern "C" fn slice_len(this: &RustSlice) -> usize { - this.len() -} diff --git a/vendor/cxx/src/symbols/rust_str.rs b/vendor/cxx/src/symbols/rust_str.rs deleted file mode 100644 index 3b33bc4a5..000000000 --- a/vendor/cxx/src/symbols/rust_str.rs +++ /dev/null @@ -1,43 +0,0 @@ -#[cfg(feature = "alloc")] -use alloc::string::String; -use core::mem::MaybeUninit; -use core::ptr; -use core::slice; -use core::str; - -#[export_name = "cxxbridge1$str$new"] -unsafe extern "C" fn str_new(this: &mut MaybeUninit<&str>) { - let this = this.as_mut_ptr(); - unsafe { ptr::write(this, "") } -} - -#[cfg(feature = "alloc")] -#[export_name = "cxxbridge1$str$ref"] -unsafe extern "C" fn str_ref<'a>(this: &mut MaybeUninit<&'a str>, string: &'a String) { - let this = this.as_mut_ptr(); - let s = string.as_str(); - unsafe { ptr::write(this, s) } -} - -#[export_name = "cxxbridge1$str$from"] -unsafe extern "C" fn str_from(this: &mut MaybeUninit<&str>, ptr: *const u8, len: usize) -> bool { - let slice = unsafe { slice::from_raw_parts(ptr, len) }; - match str::from_utf8(slice) { - Ok(s) => { - let this = this.as_mut_ptr(); - unsafe { ptr::write(this, s) } - true - } - Err(_) => false, - } -} - -#[export_name = "cxxbridge1$str$ptr"] -unsafe extern "C" fn str_ptr(this: &&str) -> *const u8 { - this.as_ptr() -} - -#[export_name = "cxxbridge1$str$len"] -unsafe extern "C" fn str_len(this: &&str) -> usize { - this.len() -} diff --git a/vendor/cxx/src/symbols/rust_string.rs b/vendor/cxx/src/symbols/rust_string.rs deleted file mode 100644 index 8b7c8c481..000000000 --- a/vendor/cxx/src/symbols/rust_string.rs +++ /dev/null @@ -1,114 +0,0 @@ -#![cfg(feature = "alloc")] - -use alloc::borrow::ToOwned; -use alloc::string::String; -use core::mem::{ManuallyDrop, MaybeUninit}; -use core::ptr; -use core::slice; -use core::str; - -#[export_name = "cxxbridge1$string$new"] -unsafe extern "C" fn string_new(this: &mut MaybeUninit<String>) { - let this = this.as_mut_ptr(); - let new = String::new(); - unsafe { ptr::write(this, new) } -} - -#[export_name = "cxxbridge1$string$clone"] -unsafe extern "C" fn string_clone(this: &mut MaybeUninit<String>, other: &String) { - let this = this.as_mut_ptr(); - let clone = other.clone(); - unsafe { ptr::write(this, clone) } -} - -#[export_name = "cxxbridge1$string$from_utf8"] -unsafe extern "C" fn string_from_utf8( - this: &mut MaybeUninit<String>, - ptr: *const u8, - len: usize, -) -> bool { - let slice = unsafe { slice::from_raw_parts(ptr, len) }; - match str::from_utf8(slice) { - Ok(s) => { - let this = this.as_mut_ptr(); - let owned = s.to_owned(); - unsafe { ptr::write(this, owned) } - true - } - Err(_) => false, - } -} - -#[export_name = "cxxbridge1$string$from_utf8_lossy"] -unsafe extern "C" fn string_from_utf8_lossy( - this: &mut MaybeUninit<String>, - ptr: *const u8, - len: usize, -) { - let slice = unsafe { slice::from_raw_parts(ptr, len) }; - let owned = String::from_utf8_lossy(slice).into_owned(); - let this = this.as_mut_ptr(); - unsafe { ptr::write(this, owned) } -} - -#[export_name = "cxxbridge1$string$from_utf16"] -unsafe extern "C" fn string_from_utf16( - this: &mut MaybeUninit<String>, - ptr: *const u16, - len: usize, -) -> bool { - let slice = unsafe { slice::from_raw_parts(ptr, len) }; - match String::from_utf16(slice) { - Ok(s) => { - let this = this.as_mut_ptr(); - unsafe { ptr::write(this, s) } - true - } - Err(_) => false, - } -} - -#[export_name = "cxxbridge1$string$from_utf16_lossy"] -unsafe extern "C" fn string_from_utf16_lossy( - this: &mut MaybeUninit<String>, - ptr: *const u16, - len: usize, -) { - let slice = unsafe { slice::from_raw_parts(ptr, len) }; - let owned = String::from_utf16_lossy(slice); - let this = this.as_mut_ptr(); - unsafe { ptr::write(this, owned) } -} - -#[export_name = "cxxbridge1$string$drop"] -unsafe extern "C" fn string_drop(this: &mut ManuallyDrop<String>) { - unsafe { ManuallyDrop::drop(this) } -} - -#[export_name = "cxxbridge1$string$ptr"] -unsafe extern "C" fn string_ptr(this: &String) -> *const u8 { - this.as_ptr() -} - -#[export_name = "cxxbridge1$string$len"] -unsafe extern "C" fn string_len(this: &String) -> usize { - this.len() -} - -#[export_name = "cxxbridge1$string$capacity"] -unsafe extern "C" fn string_capacity(this: &String) -> usize { - this.capacity() -} - -#[export_name = "cxxbridge1$string$reserve_additional"] -unsafe extern "C" fn string_reserve_additional(this: &mut String, additional: usize) { - this.reserve(additional); -} - -#[export_name = "cxxbridge1$string$reserve_total"] -unsafe extern "C" fn string_reserve_total(this: &mut String, new_cap: usize) { - if new_cap > this.capacity() { - let additional = new_cap - this.len(); - this.reserve(additional); - } -} diff --git a/vendor/cxx/src/symbols/rust_vec.rs b/vendor/cxx/src/symbols/rust_vec.rs deleted file mode 100644 index 89c7da44e..000000000 --- a/vendor/cxx/src/symbols/rust_vec.rs +++ /dev/null @@ -1,91 +0,0 @@ -#![cfg(feature = "alloc")] - -use crate::c_char::c_char; -use crate::rust_string::RustString; -use crate::rust_vec::RustVec; -use alloc::vec::Vec; -use core::mem; -use core::ptr; - -macro_rules! rust_vec_shims { - ($segment:expr, $ty:ty) => { - const_assert_eq!(mem::size_of::<[usize; 3]>(), mem::size_of::<RustVec<$ty>>()); - const_assert_eq!(mem::size_of::<Vec<$ty>>(), mem::size_of::<RustVec<$ty>>()); - const_assert_eq!(mem::align_of::<Vec<$ty>>(), mem::align_of::<RustVec<$ty>>()); - - const _: () = { - attr! { - #[export_name = concat!("cxxbridge1$rust_vec$", $segment, "$new")] - unsafe extern "C" fn __new(this: *mut RustVec<$ty>) { - unsafe { ptr::write(this, RustVec::new()) } - } - } - attr! { - #[export_name = concat!("cxxbridge1$rust_vec$", $segment, "$drop")] - unsafe extern "C" fn __drop(this: *mut RustVec<$ty>) { - unsafe { ptr::drop_in_place(this) } - } - } - attr! { - #[export_name = concat!("cxxbridge1$rust_vec$", $segment, "$len")] - unsafe extern "C" fn __len(this: *const RustVec<$ty>) -> usize { - unsafe { &*this }.len() - } - } - attr! { - #[export_name = concat!("cxxbridge1$rust_vec$", $segment, "$capacity")] - unsafe extern "C" fn __capacity(this: *const RustVec<$ty>) -> usize { - unsafe { &*this }.capacity() - } - } - attr! { - #[export_name = concat!("cxxbridge1$rust_vec$", $segment, "$data")] - unsafe extern "C" fn __data(this: *const RustVec<$ty>) -> *const $ty { - unsafe { &*this }.as_ptr() - } - } - attr! { - #[export_name = concat!("cxxbridge1$rust_vec$", $segment, "$reserve_total")] - unsafe extern "C" fn __reserve_total(this: *mut RustVec<$ty>, new_cap: usize) { - unsafe { &mut *this }.reserve_total(new_cap); - } - } - attr! { - #[export_name = concat!("cxxbridge1$rust_vec$", $segment, "$set_len")] - unsafe extern "C" fn __set_len(this: *mut RustVec<$ty>, len: usize) { - unsafe { (*this).set_len(len) } - } - } - attr! { - #[export_name = concat!("cxxbridge1$rust_vec$", $segment, "$truncate")] - unsafe extern "C" fn __truncate(this: *mut RustVec<$ty>, len: usize) { - unsafe { (*this).truncate(len) } - } - } - }; - }; -} - -macro_rules! rust_vec_shims_for_primitive { - ($ty:ident) => { - rust_vec_shims!(stringify!($ty), $ty); - }; -} - -rust_vec_shims_for_primitive!(bool); -rust_vec_shims_for_primitive!(u8); -rust_vec_shims_for_primitive!(u16); -rust_vec_shims_for_primitive!(u32); -rust_vec_shims_for_primitive!(u64); -rust_vec_shims_for_primitive!(usize); -rust_vec_shims_for_primitive!(i8); -rust_vec_shims_for_primitive!(i16); -rust_vec_shims_for_primitive!(i32); -rust_vec_shims_for_primitive!(i64); -rust_vec_shims_for_primitive!(isize); -rust_vec_shims_for_primitive!(f32); -rust_vec_shims_for_primitive!(f64); - -rust_vec_shims!("char", c_char); -rust_vec_shims!("string", RustString); -rust_vec_shims!("str", &str); diff --git a/vendor/cxx/src/type_id.rs b/vendor/cxx/src/type_id.rs deleted file mode 100644 index bd2b4ea61..000000000 --- a/vendor/cxx/src/type_id.rs +++ /dev/null @@ -1,9 +0,0 @@ -/// For use in impls of the `ExternType` trait. See [`ExternType`]. -/// -/// [`ExternType`]: trait.ExternType.html -#[macro_export] -macro_rules! type_id { - ($($path:tt)*) => { - $crate::private::type_id! { $crate $($path)* } - }; -} diff --git a/vendor/cxx/src/unique_ptr.rs b/vendor/cxx/src/unique_ptr.rs deleted file mode 100644 index 33992059e..000000000 --- a/vendor/cxx/src/unique_ptr.rs +++ /dev/null @@ -1,296 +0,0 @@ -use crate::cxx_vector::{CxxVector, VectorElement}; -use crate::fmt::display; -use crate::kind::Trivial; -use crate::string::CxxString; -use crate::ExternType; -use core::ffi::c_void; -use core::fmt::{self, Debug, Display}; -use core::marker::PhantomData; -use core::mem::{self, MaybeUninit}; -use core::ops::{Deref, DerefMut}; -use core::pin::Pin; - -/// Binding to C++ `std::unique_ptr<T, std::default_delete<T>>`. -#[repr(C)] -pub struct UniquePtr<T> -where - T: UniquePtrTarget, -{ - repr: MaybeUninit<*mut c_void>, - ty: PhantomData<T>, -} - -impl<T> UniquePtr<T> -where - T: UniquePtrTarget, -{ - /// Makes a new UniquePtr wrapping a null pointer. - /// - /// Matches the behavior of default-constructing a std::unique\_ptr. - pub fn null() -> Self { - UniquePtr { - repr: T::__null(), - ty: PhantomData, - } - } - - /// Allocates memory on the heap and makes a UniquePtr pointing to it. - pub fn new(value: T) -> Self - where - T: ExternType<Kind = Trivial>, - { - UniquePtr { - repr: T::__new(value), - ty: PhantomData, - } - } - - /// Checks whether the UniquePtr does not own an object. - /// - /// This is the opposite of [std::unique_ptr\<T\>::operator bool](https://en.cppreference.com/w/cpp/memory/unique_ptr/operator_bool). - pub fn is_null(&self) -> bool { - let ptr = unsafe { T::__get(self.repr) }; - ptr.is_null() - } - - /// Returns a reference to the object owned by this UniquePtr if any, - /// otherwise None. - pub fn as_ref(&self) -> Option<&T> { - unsafe { T::__get(self.repr).as_ref() } - } - - /// Returns a mutable pinned reference to the object owned by this UniquePtr - /// if any, otherwise None. - pub fn as_mut(&mut self) -> Option<Pin<&mut T>> { - unsafe { - let mut_reference = (T::__get(self.repr) as *mut T).as_mut()?; - Some(Pin::new_unchecked(mut_reference)) - } - } - - /// Returns a mutable pinned reference to the object owned by this - /// UniquePtr. - /// - /// # Panics - /// - /// Panics if the UniquePtr holds a null pointer. - pub fn pin_mut(&mut self) -> Pin<&mut T> { - match self.as_mut() { - Some(target) => target, - None => panic!( - "called pin_mut on a null UniquePtr<{}>", - display(T::__typename), - ), - } - } - - /// Consumes the UniquePtr, releasing its ownership of the heap-allocated T. - /// - /// Matches the behavior of [std::unique_ptr\<T\>::release](https://en.cppreference.com/w/cpp/memory/unique_ptr/release). - pub fn into_raw(self) -> *mut T { - let ptr = unsafe { T::__release(self.repr) }; - mem::forget(self); - ptr - } - - /// Constructs a UniquePtr retaking ownership of a pointer previously - /// obtained from `into_raw`. - /// - /// # Safety - /// - /// This function is unsafe because improper use may lead to memory - /// problems. For example a double-free may occur if the function is called - /// twice on the same raw pointer. - pub unsafe fn from_raw(raw: *mut T) -> Self { - UniquePtr { - repr: unsafe { T::__raw(raw) }, - ty: PhantomData, - } - } -} - -unsafe impl<T> Send for UniquePtr<T> where T: Send + UniquePtrTarget {} -unsafe impl<T> Sync for UniquePtr<T> where T: Sync + UniquePtrTarget {} - -// UniquePtr is not a self-referential type and is safe to move out of a Pin, -// regardless whether the pointer's target is Unpin. -impl<T> Unpin for UniquePtr<T> where T: UniquePtrTarget {} - -impl<T> Drop for UniquePtr<T> -where - T: UniquePtrTarget, -{ - fn drop(&mut self) { - unsafe { T::__drop(self.repr) } - } -} - -impl<T> Deref for UniquePtr<T> -where - T: UniquePtrTarget, -{ - type Target = T; - - fn deref(&self) -> &Self::Target { - match self.as_ref() { - Some(target) => target, - None => panic!( - "called deref on a null UniquePtr<{}>", - display(T::__typename), - ), - } - } -} - -impl<T> DerefMut for UniquePtr<T> -where - T: UniquePtrTarget + Unpin, -{ - fn deref_mut(&mut self) -> &mut Self::Target { - match self.as_mut() { - Some(target) => Pin::into_inner(target), - None => panic!( - "called deref_mut on a null UniquePtr<{}>", - display(T::__typename), - ), - } - } -} - -impl<T> Debug for UniquePtr<T> -where - T: Debug + UniquePtrTarget, -{ - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - match self.as_ref() { - None => formatter.write_str("nullptr"), - Some(value) => Debug::fmt(value, formatter), - } - } -} - -impl<T> Display for UniquePtr<T> -where - T: Display + UniquePtrTarget, -{ - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - match self.as_ref() { - None => formatter.write_str("nullptr"), - Some(value) => Display::fmt(value, formatter), - } - } -} - -/// Trait bound for types which may be used as the `T` inside of a -/// `UniquePtr<T>` in generic code. -/// -/// This trait has no publicly callable or implementable methods. Implementing -/// it outside of the CXX codebase is not supported. -/// -/// # Example -/// -/// A bound `T: UniquePtrTarget` may be necessary when manipulating -/// [`UniquePtr`] in generic code. -/// -/// ``` -/// use cxx::memory::{UniquePtr, UniquePtrTarget}; -/// use std::fmt::Display; -/// -/// pub fn take_generic_ptr<T>(ptr: UniquePtr<T>) -/// where -/// T: UniquePtrTarget + Display, -/// { -/// println!("the unique_ptr points to: {}", *ptr); -/// } -/// ``` -/// -/// Writing the same generic function without a `UniquePtrTarget` trait bound -/// would not compile. -pub unsafe trait UniquePtrTarget { - #[doc(hidden)] - fn __typename(f: &mut fmt::Formatter) -> fmt::Result; - #[doc(hidden)] - fn __null() -> MaybeUninit<*mut c_void>; - #[doc(hidden)] - fn __new(value: Self) -> MaybeUninit<*mut c_void> - where - Self: Sized, - { - // Opaque C types do not get this method because they can never exist by - // value on the Rust side of the bridge. - let _ = value; - unreachable!() - } - #[doc(hidden)] - unsafe fn __raw(raw: *mut Self) -> MaybeUninit<*mut c_void>; - #[doc(hidden)] - unsafe fn __get(repr: MaybeUninit<*mut c_void>) -> *const Self; - #[doc(hidden)] - unsafe fn __release(repr: MaybeUninit<*mut c_void>) -> *mut Self; - #[doc(hidden)] - unsafe fn __drop(repr: MaybeUninit<*mut c_void>); -} - -extern "C" { - #[link_name = "cxxbridge1$unique_ptr$std$string$null"] - fn unique_ptr_std_string_null(this: *mut MaybeUninit<*mut c_void>); - #[link_name = "cxxbridge1$unique_ptr$std$string$raw"] - fn unique_ptr_std_string_raw(this: *mut MaybeUninit<*mut c_void>, raw: *mut CxxString); - #[link_name = "cxxbridge1$unique_ptr$std$string$get"] - fn unique_ptr_std_string_get(this: *const MaybeUninit<*mut c_void>) -> *const CxxString; - #[link_name = "cxxbridge1$unique_ptr$std$string$release"] - fn unique_ptr_std_string_release(this: *mut MaybeUninit<*mut c_void>) -> *mut CxxString; - #[link_name = "cxxbridge1$unique_ptr$std$string$drop"] - fn unique_ptr_std_string_drop(this: *mut MaybeUninit<*mut c_void>); -} - -unsafe impl UniquePtrTarget for CxxString { - fn __typename(f: &mut fmt::Formatter) -> fmt::Result { - f.write_str("CxxString") - } - fn __null() -> MaybeUninit<*mut c_void> { - let mut repr = MaybeUninit::uninit(); - unsafe { - unique_ptr_std_string_null(&mut repr); - } - repr - } - unsafe fn __raw(raw: *mut Self) -> MaybeUninit<*mut c_void> { - let mut repr = MaybeUninit::uninit(); - unsafe { unique_ptr_std_string_raw(&mut repr, raw) } - repr - } - unsafe fn __get(repr: MaybeUninit<*mut c_void>) -> *const Self { - unsafe { unique_ptr_std_string_get(&repr) } - } - unsafe fn __release(mut repr: MaybeUninit<*mut c_void>) -> *mut Self { - unsafe { unique_ptr_std_string_release(&mut repr) } - } - unsafe fn __drop(mut repr: MaybeUninit<*mut c_void>) { - unsafe { unique_ptr_std_string_drop(&mut repr) } - } -} - -unsafe impl<T> UniquePtrTarget for CxxVector<T> -where - T: VectorElement, -{ - fn __typename(f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "CxxVector<{}>", display(T::__typename)) - } - fn __null() -> MaybeUninit<*mut c_void> { - T::__unique_ptr_null() - } - unsafe fn __raw(raw: *mut Self) -> MaybeUninit<*mut c_void> { - unsafe { T::__unique_ptr_raw(raw) } - } - unsafe fn __get(repr: MaybeUninit<*mut c_void>) -> *const Self { - unsafe { T::__unique_ptr_get(repr) } - } - unsafe fn __release(repr: MaybeUninit<*mut c_void>) -> *mut Self { - unsafe { T::__unique_ptr_release(repr) } - } - unsafe fn __drop(repr: MaybeUninit<*mut c_void>) { - unsafe { T::__unique_ptr_drop(repr) } - } -} diff --git a/vendor/cxx/src/unwind.rs b/vendor/cxx/src/unwind.rs deleted file mode 100644 index 18852da71..000000000 --- a/vendor/cxx/src/unwind.rs +++ /dev/null @@ -1,39 +0,0 @@ -#![allow(missing_docs)] - -use core::mem; - -pub fn prevent_unwind<F, R>(label: &'static str, foreign_call: F) -> R -where - F: FnOnce() -> R, -{ - // Goal is to make it impossible to propagate a panic across the C interface - // of an extern "Rust" function, which would be Undefined Behavior. We - // transform such panicks into a deterministic abort instead. When cxx is - // built in an application using panic=abort, this guard object is compiled - // out because its destructor is statically unreachable. When built with - // panic=unwind, an unwind from the foreign call will attempt to drop the - // guard object leading to a double panic, which is defined by Rust to - // abort. In no_std programs, on most platforms the current mechanism for - // this is for core::intrinsics::abort to invoke an invalid instruction. On - // Unix, the process will probably terminate with a signal like SIGABRT, - // SIGILL, SIGTRAP, SIGSEGV or SIGBUS. The precise behaviour is not - // guaranteed and not stable, but is safe. - let guard = Guard { label }; - - let ret = foreign_call(); - - // If we made it here, no uncaught panic occurred during the foreign call. - mem::forget(guard); - ret -} - -struct Guard { - label: &'static str, -} - -impl Drop for Guard { - #[cold] - fn drop(&mut self) { - panic!("panic in ffi function {}, aborting.", self.label); - } -} diff --git a/vendor/cxx/src/vector.rs b/vendor/cxx/src/vector.rs deleted file mode 100644 index 4afd4879a..000000000 --- a/vendor/cxx/src/vector.rs +++ /dev/null @@ -1,9 +0,0 @@ -//! Less used details of `CxxVector`. -//! -//! `CxxVector` itself is exposed at the crate root. - -pub use crate::cxx_vector::{Iter, IterMut, VectorElement}; -#[doc(inline)] -pub use crate::Vector; -#[doc(no_inline)] -pub use cxx::CxxVector; diff --git a/vendor/cxx/src/weak_ptr.rs b/vendor/cxx/src/weak_ptr.rs deleted file mode 100644 index e9320f374..000000000 --- a/vendor/cxx/src/weak_ptr.rs +++ /dev/null @@ -1,189 +0,0 @@ -use crate::shared_ptr::{SharedPtr, SharedPtrTarget}; -use crate::string::CxxString; -use core::ffi::c_void; -use core::fmt::{self, Debug}; -use core::marker::PhantomData; -use core::mem::MaybeUninit; - -/// Binding to C++ `std::weak_ptr<T>`. -/// -/// The typical way to construct a WeakPtr from Rust is by [downgrading] from a -/// SharedPtr. -/// -/// [downgrading]: crate::SharedPtr::downgrade -#[repr(C)] -pub struct WeakPtr<T> -where - T: WeakPtrTarget, -{ - repr: [MaybeUninit<*mut c_void>; 2], - ty: PhantomData<T>, -} - -impl<T> WeakPtr<T> -where - T: WeakPtrTarget, -{ - /// Makes a new WeakPtr wrapping a null pointer. - /// - /// Matches the behavior of default-constructing a std::weak\_ptr. - pub fn null() -> Self { - let mut weak_ptr = MaybeUninit::<WeakPtr<T>>::uninit(); - let new = weak_ptr.as_mut_ptr().cast(); - unsafe { - T::__null(new); - weak_ptr.assume_init() - } - } - - /// Upgrades a non-owning reference into an owning reference if possible, - /// otherwise to a null reference. - /// - /// Matches the behavior of [std::weak_ptr\<T\>::lock](https://en.cppreference.com/w/cpp/memory/weak_ptr/lock). - pub fn upgrade(&self) -> SharedPtr<T> - where - T: SharedPtrTarget, - { - let this = self as *const Self as *const c_void; - let mut shared_ptr = MaybeUninit::<SharedPtr<T>>::uninit(); - let new = shared_ptr.as_mut_ptr().cast(); - unsafe { - T::__upgrade(this, new); - shared_ptr.assume_init() - } - } -} - -unsafe impl<T> Send for WeakPtr<T> where T: Send + Sync + WeakPtrTarget {} -unsafe impl<T> Sync for WeakPtr<T> where T: Send + Sync + WeakPtrTarget {} - -impl<T> Clone for WeakPtr<T> -where - T: WeakPtrTarget, -{ - fn clone(&self) -> Self { - let mut weak_ptr = MaybeUninit::<WeakPtr<T>>::uninit(); - let new = weak_ptr.as_mut_ptr().cast(); - let this = self as *const Self as *mut c_void; - unsafe { - T::__clone(this, new); - weak_ptr.assume_init() - } - } -} - -impl<T> Drop for WeakPtr<T> -where - T: WeakPtrTarget, -{ - fn drop(&mut self) { - let this = self as *mut Self as *mut c_void; - unsafe { T::__drop(this) } - } -} - -impl<T> Debug for WeakPtr<T> -where - T: Debug + WeakPtrTarget + SharedPtrTarget, -{ - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - Debug::fmt(&self.upgrade(), formatter) - } -} - -/// Trait bound for types which may be used as the `T` inside of a `WeakPtr<T>` -/// in generic code. -/// -/// This trait has no publicly callable or implementable methods. Implementing -/// it outside of the CXX codebase is not supported. -pub unsafe trait WeakPtrTarget { - #[doc(hidden)] - fn __typename(f: &mut fmt::Formatter) -> fmt::Result; - #[doc(hidden)] - unsafe fn __null(new: *mut c_void); - #[doc(hidden)] - unsafe fn __clone(this: *const c_void, new: *mut c_void); - #[doc(hidden)] - unsafe fn __downgrade(shared: *const c_void, new: *mut c_void); - #[doc(hidden)] - unsafe fn __upgrade(weak: *const c_void, shared: *mut c_void); - #[doc(hidden)] - unsafe fn __drop(this: *mut c_void); -} - -macro_rules! impl_weak_ptr_target { - ($segment:expr, $name:expr, $ty:ty) => { - unsafe impl WeakPtrTarget for $ty { - fn __typename(f: &mut fmt::Formatter) -> fmt::Result { - f.write_str($name) - } - unsafe fn __null(new: *mut c_void) { - extern "C" { - attr! { - #[link_name = concat!("cxxbridge1$std$weak_ptr$", $segment, "$null")] - fn __null(new: *mut c_void); - } - } - unsafe { __null(new) } - } - unsafe fn __clone(this: *const c_void, new: *mut c_void) { - extern "C" { - attr! { - #[link_name = concat!("cxxbridge1$std$weak_ptr$", $segment, "$clone")] - fn __clone(this: *const c_void, new: *mut c_void); - } - } - unsafe { __clone(this, new) } - } - unsafe fn __downgrade(shared: *const c_void, weak: *mut c_void) { - extern "C" { - attr! { - #[link_name = concat!("cxxbridge1$std$weak_ptr$", $segment, "$downgrade")] - fn __downgrade(shared: *const c_void, weak: *mut c_void); - } - } - unsafe { __downgrade(shared, weak) } - } - unsafe fn __upgrade(weak: *const c_void, shared: *mut c_void) { - extern "C" { - attr! { - #[link_name = concat!("cxxbridge1$std$weak_ptr$", $segment, "$upgrade")] - fn __upgrade(weak: *const c_void, shared: *mut c_void); - } - } - unsafe { __upgrade(weak, shared) } - } - unsafe fn __drop(this: *mut c_void) { - extern "C" { - attr! { - #[link_name = concat!("cxxbridge1$std$weak_ptr$", $segment, "$drop")] - fn __drop(this: *mut c_void); - } - } - unsafe { __drop(this) } - } - } - }; -} - -macro_rules! impl_weak_ptr_target_for_primitive { - ($ty:ident) => { - impl_weak_ptr_target!(stringify!($ty), stringify!($ty), $ty); - }; -} - -impl_weak_ptr_target_for_primitive!(bool); -impl_weak_ptr_target_for_primitive!(u8); -impl_weak_ptr_target_for_primitive!(u16); -impl_weak_ptr_target_for_primitive!(u32); -impl_weak_ptr_target_for_primitive!(u64); -impl_weak_ptr_target_for_primitive!(usize); -impl_weak_ptr_target_for_primitive!(i8); -impl_weak_ptr_target_for_primitive!(i16); -impl_weak_ptr_target_for_primitive!(i32); -impl_weak_ptr_target_for_primitive!(i64); -impl_weak_ptr_target_for_primitive!(isize); -impl_weak_ptr_target_for_primitive!(f32); -impl_weak_ptr_target_for_primitive!(f64); - -impl_weak_ptr_target!("string", "CxxString", CxxString); |