• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1{{#title rust::Str — Rust ♡ C++}}
2# rust::Str
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 Str final {
15public:
16  Str() noexcept;
17  Str(const Str &) noexcept;
18  Str(const String &) noexcept;
19
20  // Throws std::invalid_argument if not utf-8.
21  Str(const std::string &);
22  Str(const char *);
23  Str(const char *, size_t);
24
25  Str &operator=(const Str &) noexcept;
26
27  explicit operator std::string() const;
28
29  // Note: no null terminator.
30  const char *data() const noexcept;
31  size_t size() const noexcept;
32  size_t length() const noexcept;
33
34  using iterator = const char *;
35  using const_iterator = const char *;
36  const_iterator begin() const noexcept;
37  const_iterator end() const noexcept;
38  const_iterator cbegin() const noexcept;
39  const_iterator cend() const noexcept;
40
41  bool operator==(const Str &) const noexcept;
42  bool operator!=(const Str &) const noexcept;
43  bool operator<(const Str &) const noexcept;
44  bool operator<=(const Str &) const noexcept;
45  bool operator>(const Str &) const noexcept;
46  bool operator>=(const Str &) const noexcept;
47
48  void swap(Str &) noexcept;
49};
50
51std::ostream &operator<<(std::ostream &, const Str &);
52#
53# } // namespace rust
54```
55
56### Notes:
57
58**Be aware that rust::Str behaves like &amp;str i.e. it is a borrow!**&ensp;C++
59needs to be mindful of the lifetimes at play.
60
61Just to reiterate: &amp;str is rust::Str. Do not try to write &amp;str as `const
62rust::Str &`. A language-level C++ reference is not able to capture the fat
63pointer nature of &amp;str.
64
65### Restrictions:
66
67Allowed as function argument or return value. Not supported in shared structs
68yet. `&mut str` is not supported yet, but is also extremely obscure so this is
69fine.
70
71## Example
72
73```rust,noplayground
74// src/main.rs
75
76#[cxx::bridge]
77mod ffi {
78    extern "Rust" {
79        fn r(greeting: &str);
80    }
81
82    unsafe extern "C++" {
83        include!("example/include/greeting.h");
84        fn c(greeting: &str);
85    }
86}
87
88fn r(greeting: &str) {
89    println!("{}", greeting);
90}
91
92fn main() {
93    ffi::c("hello from Rust");
94}
95```
96
97```cpp
98// include/greeting.h
99
100#pragma once
101#include "example/src/main.rs.h"
102#include "rust/cxx.h"
103
104void c(rust::Str greeting);
105```
106
107```cpp
108// src/greeting.cc
109
110#include "example/include/greeting.h"
111#include <iostream>
112
113void c(rust::Str greeting) {
114  std::cout << greeting << std::endl;
115  r("hello from C++");
116}
117```
118