Skip to content

Commit

Permalink
Merge pull request #1367 from anforowicz/rust-slice-from-vec
Browse files Browse the repository at this point in the history
Ergonomics: allow constructing `rust::Slice` from any C++ container.
  • Loading branch information
dtolnay authored Aug 14, 2024
2 parents a73ec24 + feacee0 commit 6c8ac69
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
3 changes: 3 additions & 0 deletions include/cxx.h
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,9 @@ class Slice final
Slice() noexcept;
Slice(T *, std::size_t count) noexcept;

template <typename C>
explicit Slice(C& c) : Slice(c.data(), c.size()) {}

Slice &operator=(const Slice<T> &) &noexcept = default;
Slice &operator=(Slice<T> &&) &noexcept = default;

Expand Down
6 changes: 6 additions & 0 deletions tests/ffi/tests.cc
Original file line number Diff line number Diff line change
Expand Up @@ -884,6 +884,12 @@ extern "C" const char *cxx_run_test() noexcept {
rust::String bad_utf16_rstring = rust::String::lossy(bad_utf16_literal);
ASSERT(bad_utf8_rstring == bad_utf16_rstring);

std::vector<int> cpp_vec{1, 2, 3};
rust::Slice<int> slice_of_cpp_vec(cpp_vec);
ASSERT(slice_of_cpp_vec.data() == cpp_vec.data());
ASSERT(slice_of_cpp_vec.size() == cpp_vec.size());
ASSERT(slice_of_cpp_vec[0] == 1);

rust::Vec<int> vec1{1, 2};
rust::Vec<int> vec2{3, 4};
swap(vec1, vec2);
Expand Down

0 comments on commit 6c8ac69

Please sign in to comment.