fidl_next_codec/wire/vec/
raw.rs

1// Copyright 2024 The Fuchsia 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
5use core::ptr::slice_from_raw_parts_mut;
6
7use munge::munge;
8
9use crate::{Slot, WirePointer, WireU64, ZeroPadding};
10
11#[repr(C)]
12pub struct RawWireVector<T> {
13    pub len: WireU64,
14    pub ptr: WirePointer<T>,
15}
16
17unsafe impl<T> ZeroPadding for RawWireVector<T> {
18    #[inline]
19    unsafe fn zero_padding(_: *mut Self) {
20        // Wire vectors have no padding bytes
21    }
22}
23
24// SAFETY: `RawWireVector` doesn't add any restrictions on sending across thread boundaries, and so
25// is `Send` if `T` is `Send`.
26unsafe impl<T: Send> Send for RawWireVector<T> {}
27
28// SAFETY: `RawWireVector` doesn't add any interior mutability, so it is `Sync` if `T` is `Sync`.
29unsafe impl<T: Sync> Sync for RawWireVector<T> {}
30
31impl<T> RawWireVector<T> {
32    pub fn encode_present(slot: Slot<'_, Self>, len: u64) {
33        munge!(let Self { len: mut encoded_len, ptr } = slot);
34        **encoded_len = len;
35        WirePointer::encode_present(ptr);
36    }
37
38    pub fn encode_absent(slot: Slot<'_, Self>) {
39        munge!(let Self { mut len, ptr } = slot);
40        **len = 0;
41        WirePointer::encode_absent(ptr);
42    }
43
44    pub fn len(&self) -> u64 {
45        *self.len
46    }
47
48    pub fn as_ptr(&self) -> *mut T {
49        self.ptr.as_ptr()
50    }
51
52    pub fn as_slice_ptr(&self) -> *mut [T] {
53        slice_from_raw_parts_mut(self.as_ptr(), self.len() as usize)
54    }
55}