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