1 // Protocol Buffers - Google's data interchange format 2 // Copyright 2024 Google LLC. All rights reserved. 3 // 4 // Use of this source code is governed by a BSD-style 5 // license that can be found in the LICENSE file or at 6 // https://developers.google.com/open-source/licenses/bsd 7 8 /// ABI compatible struct with upb_StringView. 9 /// 10 /// Note that this has semantics similar to `std::string_view` in C++ and 11 /// `&[u8]` in Rust, but is not ABI-compatible with either. 12 /// 13 /// If `len` is 0, then `ptr` is allowed to be either null or dangling. C++ 14 /// considers a dangling 0-len `std::string_view` to be invalid, and Rust 15 /// considers a `&[u8]` with a null data pointer to be invalid. 16 #[repr(C)] 17 #[derive(Copy, Clone)] 18 pub struct StringView { 19 /// Pointer to the first byte. 20 /// Borrows the memory. 21 pub ptr: *const u8, 22 23 /// Length of the `[u8]` pointed to by `ptr`. 24 pub len: usize, 25 } 26 27 impl StringView { 28 /// Unsafely dereference this slice. 29 /// 30 /// # Safety 31 /// - `self.ptr` must be dereferencable and immutable for `self.len` bytes 32 /// for the lifetime `'a`. It can be null or dangling if `self.len == 0`. as_ref<'a>(self) -> &'a [u8]33 pub unsafe fn as_ref<'a>(self) -> &'a [u8] { 34 if self.ptr.is_null() { 35 assert_eq!(self.len, 0, "Non-empty slice with null data pointer"); 36 &[] 37 } else { 38 // SAFETY: 39 // - `ptr` is non-null 40 // - `ptr` is valid for `len` bytes as promised by the caller. 41 unsafe { core::slice::from_raw_parts(self.ptr, self.len) } 42 } 43 } 44 } 45 46 impl From<&[u8]> for StringView { from(slice: &[u8]) -> Self47 fn from(slice: &[u8]) -> Self { 48 Self { ptr: slice.as_ptr(), len: slice.len() } 49 } 50 } 51 52 impl<const N: usize> From<&[u8; N]> for StringView { from(slice: &[u8; N]) -> Self53 fn from(slice: &[u8; N]) -> Self { 54 Self { ptr: slice.as_ptr(), len: N } 55 } 56 } 57