1{{#title rust::String — Rust ♡ C++}} 2# rust::String 3 4### Public API: 5 6```cpp,hidelines 7// rust/cxx.h 8# 9# #include <iosfwd> 10# #include <string> 11# 12# namespace rust { 13 14class String final { 15public: 16 String() noexcept; 17 String(const String &) noexcept; 18 String(String &&) noexcept; 19 ~String() noexcept; 20 21 // Throws std::invalid_argument if not utf-8. 22 String(const std::string &); 23 String(const char *); 24 String(const char *, size_t); 25 26 // Throws std::invalid_argument if not utf-16. 27 String(const char16_t *); 28 String(const char16_t *, size_t); 29 30 String &operator=(const String &) noexcept; 31 String &operator=(String &&) noexcept; 32 33 explicit operator std::string() const; 34 35 // Note: no null terminator. 36 const char *data() const noexcept; 37 size_t size() const noexcept; 38 size_t length() const noexcept; 39 bool empty() const noexcept; 40 41 const char *c_str() noexcept; 42 43 size_t capacity() const noexcept; 44 void reserve(size_t new_cap) noexcept; 45 46 using iterator = char *; 47 iterator begin() noexcept; 48 iterator end() noexcept; 49 50 using const_iterator = const char *; 51 const_iterator begin() const noexcept; 52 const_iterator end() const noexcept; 53 const_iterator cbegin() const noexcept; 54 const_iterator cend() const noexcept; 55 56 bool operator==(const String &) const noexcept; 57 bool operator!=(const String &) const noexcept; 58 bool operator<(const String &) const noexcept; 59 bool operator<=(const String &) const noexcept; 60 bool operator>(const String &) const noexcept; 61 bool operator>=(const String &) const noexcept; 62 63 void swap(String &) noexcept; 64}; 65 66std::ostream &operator<<(std::ostream &, const String &); 67# 68# } // namespace rust 69``` 70 71### Restrictions: 72 73None. Strings may be used as function arguments and function return values, by 74value or by reference, as well as fields of shared structs. 75 76## Example 77 78```rust,noplayground 79// src/main.rs 80 81#[cxx::bridge] 82mod ffi { 83 struct ConcatRequest { 84 fst: String, 85 snd: String, 86 } 87 88 unsafe extern "C++" { 89 include!("example/include/concat.h"); 90 fn concat(r: ConcatRequest) -> String; 91 } 92} 93 94fn main() { 95 let concatenated = ffi::concat(ffi::ConcatRequest { 96 fst: "fearless".to_owned(), 97 snd: "concurrency".to_owned(), 98 }); 99 println!("concatenated: {:?}", concatenated); 100} 101``` 102 103```cpp 104// include/concat.h 105 106#pragma once 107#include "example/src/main.rs.h" 108#include "rust/cxx.h" 109 110rust::String concat(ConcatRequest r); 111``` 112 113```cpp 114// src/concat.cc 115 116#include "example/include/concat.h" 117 118rust::String concat(ConcatRequest r) { 119 // The full suite of operator overloads hasn't been added 120 // yet on rust::String, but we can get it done like this: 121 return std::string(r.fst) + std::string(r.snd); 122} 123``` 124