string_piece_rust.h 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. // Copyright 2021 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_STRINGS_STRING_PIECE_RUST_H_
  5. #define BASE_STRINGS_STRING_PIECE_RUST_H_
  6. #include <stdint.h>
  7. #include "base/strings/string_piece.h"
  8. #include "third_party/rust/cxx/v1/crate/include/cxx.h"
  9. namespace base {
  10. // Create a Rust str from a base::BasicStringPiece. This will call std::abort
  11. // if there is any invalid UTF8. If you're concerned about this, then
  12. // instead use StringPieceToRustSlice and convert the data to a string on
  13. // the Rust side (or pass in a std::string).
  14. inline rust::Str StringPieceToRustStrUTF8(StringPiece string_piece) {
  15. return rust::Str(string_piece.data(), string_piece.size());
  16. }
  17. // Create a Rust slice from a StringPiece. No UTF8 check is performed.
  18. inline rust::Slice<const uint8_t> StringPieceToRustSlice(
  19. StringPiece string_piece) {
  20. return rust::Slice<const uint8_t>(
  21. reinterpret_cast<const uint8_t*>(string_piece.data()),
  22. string_piece.length() * sizeof(StringPiece::value_type));
  23. }
  24. // Create a StringPiece from a Rust str.
  25. inline StringPiece RustStrToStringPiece(rust::Str str) {
  26. return StringPiece(str.data(), str.size());
  27. }
  28. } // namespace base
  29. #endif // BASE_STRINGS_STRING_PIECE_RUST_H_