• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2021 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_PIECE_RUST_H_
6 #define BASE_STRINGS_STRING_PIECE_RUST_H_
7 
8 #include "base/rust_buildflags.h"
9 
10 #if BUILDFLAG(BUILD_RUST_BASE_CONVERSIONS)
11 
12 #include <stdint.h>
13 
14 #include "base/strings/string_piece.h"
15 #include "third_party/rust/cxx/v1/crate/include/cxx.h"  // nogncheck
16 
17 namespace base {
18 
19 // Create a Rust str from a base::BasicStringPiece. This will call std::abort
20 // if there is any invalid UTF8. If you're concerned about this, then
21 // instead use StringPieceToRustSlice and convert the data to a string on
22 // the Rust side (or pass in a std::string).
StringPieceToRustStrUTF8(StringPiece string_piece)23 inline rust::Str StringPieceToRustStrUTF8(StringPiece string_piece) {
24   return rust::Str(string_piece.data(), string_piece.size());
25 }
26 
27 // Create a Rust slice from a StringPiece. No UTF8 check is performed.
StringPieceToRustSlice(StringPiece string_piece)28 inline rust::Slice<const uint8_t> StringPieceToRustSlice(
29     StringPiece string_piece) {
30   return rust::Slice<const uint8_t>(
31       reinterpret_cast<const uint8_t*>(string_piece.data()),
32       string_piece.length() * sizeof(StringPiece::value_type));
33 }
34 
35 // Create a StringPiece from a Rust str.
RustStrToStringPiece(rust::Str str)36 inline StringPiece RustStrToStringPiece(rust::Str str) {
37   return StringPiece(str.data(), str.size());
38 }
39 
40 }  // namespace base
41 
42 #endif  // BUILDFLAG(BUILD_RUST_BASE_CONVERSIONS)
43 
44 #endif  // BASE_STRINGS_STRING_PIECE_RUST_H_
45