• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2024 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_STRINGS_STRING_VIEW_RUST_H_
6 #define BASE_STRINGS_STRING_VIEW_RUST_H_
7 
8 #include <stdint.h>
9 
10 #include <string_view>
11 
12 #include "build/build_config.h"
13 #include "third_party/rust/cxx/v1/cxx.h"
14 
15 #if BUILDFLAG(IS_NACL)
16 #error "string_view_rust.h included under IS_NACL"
17 #endif
18 
19 namespace base {
20 
21 // Create a Rust str from a std::string_view. This will call std::abort
22 // if there is any invalid UTF8. If you're concerned about this, then
23 // instead use StringViewToRustSlice and convert the data to a string on
24 // the Rust side (or pass in a std::string).
StringViewToRustStrUTF8(std::string_view string_piece)25 inline rust::Str StringViewToRustStrUTF8(std::string_view string_piece) {
26   return rust::Str(string_piece.data(), string_piece.size());
27 }
28 
29 // Create a Rust slice from a std::string_view. No UTF8 check is performed.
StringViewToRustSlice(std::string_view string_piece)30 inline rust::Slice<const uint8_t> StringViewToRustSlice(
31     std::string_view string_piece) {
32   return rust::Slice<const uint8_t>(
33       reinterpret_cast<const uint8_t*>(string_piece.data()),
34       string_piece.length() * sizeof(std::string_view::value_type));
35 }
36 
37 // Create a std::string_view from a Rust str.
RustStrToStringView(rust::Str str)38 inline std::string_view RustStrToStringView(rust::Str str) {
39   return std::string_view(str.data(), str.size());
40 }
41 
42 }  // namespace base
43 
44 #endif  // BASE_STRINGS_STRING_VIEW_RUST_H_
45