• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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  String &operator=(const String &) noexcept;
27  String &operator=(String &&) noexcept;
28
29  explicit operator std::string() const;
30
31  // Note: no null terminator.
32  const char *data() const noexcept;
33  size_t size() const noexcept;
34  size_t length() const noexcept;
35
36  const char *c_str() noexcept;
37
38  using iterator = char *;
39  iterator begin() noexcept;
40  iterator end() noexcept;
41
42  using const_iterator = const char *;
43  const_iterator begin() const noexcept;
44  const_iterator end() const noexcept;
45  const_iterator cbegin() const noexcept;
46  const_iterator cend() const noexcept;
47
48  bool operator==(const String &) const noexcept;
49  bool operator!=(const String &) const noexcept;
50  bool operator<(const String &) const noexcept;
51  bool operator<=(const String &) const noexcept;
52  bool operator>(const String &) const noexcept;
53  bool operator>=(const String &) const noexcept;
54
55  void swap(String &) noexcept;
56};
57
58std::ostream &operator<<(std::ostream &, const String &);
59#
60# } // namespace rust
61```
62
63### Restrictions:
64
65None. Strings may be used as function arguments and function return values, by
66value or by reference, as well as fields of shared structs.
67
68## Example
69
70```rust,noplayground
71// src/main.rs
72
73#[cxx::bridge]
74mod ffi {
75    struct ConcatRequest {
76        fst: String,
77        snd: String,
78    }
79
80    unsafe extern "C++" {
81        include!("example/include/concat.h");
82        fn concat(r: ConcatRequest) -> String;
83    }
84}
85
86fn main() {
87    let concatenated = ffi::concat(ffi::ConcatRequest {
88        fst: "fearless".to_owned(),
89        snd: "concurrency".to_owned(),
90    });
91    println!("concatenated: {:?}", concatenated);
92}
93```
94
95```cpp
96// include/concat.h
97
98#pragma once
99#include "example/src/main.rs.h"
100#include "rust/cxx.h"
101
102rust::String concat(ConcatRequest r);
103```
104
105```cpp
106// src/concat.cc
107
108#include "example/include/concat.h"
109
110rust::String concat(ConcatRequest r) {
111  // The full suite of operator overloads hasn't been added
112  // yet on rust::String, but we can get it done like this:
113  return std::string(r.fst) + std::string(r.snd);
114}
115```
116