xref: /aosp_15_r20/external/cronet/base/containers/span_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_CONTAINERS_SPAN_RUST_H_
6 #define BASE_CONTAINERS_SPAN_RUST_H_
7 
8 #include <stdint.h>
9 
10 #include "base/containers/span.h"
11 #include "base/rust_buildflags.h"
12 #include "third_party/rust/cxx/v1/cxx.h"
13 
14 #if !BUILDFLAG(BUILD_RUST_BASE_CONVERSIONS)
15 #error "span_rust.h included without BUILD_RUST_BASE_CONVERSIONS"
16 #endif
17 
18 namespace base {
19 
20 // Create a Rust slice from a base::span.
SpanToRustSlice(span<const uint8_t> span)21 inline rust::Slice<const uint8_t> SpanToRustSlice(span<const uint8_t> span) {
22   return rust::Slice<const uint8_t>(span.data(), span.size());
23 }
24 
25 // Note to future editors: if you add code to convert from a rust::Slice to
26 // a base::span, you should be aware that Rust slices (and cxx)
27 // return a fabricated non-null pointer for zero-length slices, and that
28 // this will likely need converting to NULL before constructing a span.
29 // cxx handles the conversion from NULL to an artificial pointer
30 // (specifically it uses alignof<T>) in the C++ -> Rust direction, but
31 // does nothing cunning in the other direction, presumably on the
32 // assumption that C++ won't access the data pointer if the length is 0.
33 // But we do not think (reinterpret_cast<T*>(alignof(T)), 0) can safely
34 // be stored in base::span today. The pointer arithmetic
35 // rules have special cases for NULL, but otherwise it is only defined if
36 // there is actually an object at the address, and there is no object at
37 // alignof(T).
38 // https://eel.is/c++draft/expr.add#4
39 // https://eel.is/c++draft/expr.add#5
40 
41 }  // namespace base
42 
43 #endif  // BASE_CONTAINERS_SPAN_RUST_H_
44