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