1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//! Table-based encoding.
use super::StructMetadata;
use super::TableEncoder;
use crate::protobuf::FieldSizer;
use crate::protobuf::FieldWriter;
use crate::protobuf::MessageSizer;
use crate::protobuf::MessageWriter;
use crate::FieldEncode;
use crate::MessageEncode;
use core::marker::PhantomData;
use std::mem::MaybeUninit;
use std::slice;
impl<T, R> MessageEncode<T, R> for TableEncoder
where
T: StructEncodeMetadata<R>,
{
fn write_message(item: T, writer: MessageWriter<'_, '_, R>) {
let mut item = MaybeUninit::new(item);
// SAFETY: `T` guarantees that its encoders and offsets are correct for
// this type.
unsafe {
write_fields(
T::NUMBERS,
T::ENCODERS,
T::OFFSETS,
item.as_mut_ptr().cast(),
writer,
);
}
}
fn compute_message_size(item: &mut T, sizer: MessageSizer<'_>) {
// SAFETY: `T` guarantees that its encoders and offsets are correct for
// this type.
unsafe {
compute_size_fields::<R>(
T::NUMBERS,
T::ENCODERS,
T::OFFSETS,
std::ptr::from_mut(item).cast::<u8>(),
sizer,
);
}
}
}
impl<T, R> FieldEncode<T, R> for TableEncoder
where
T: StructEncodeMetadata<R>,
{
// Override the default implementation to use the table encoder directly.
// This saves code size by avoiding extra stub functions and vtables.
const ENTRY: EncoderEntry<T, R> = EncoderEntry::table();
fn write_field(item: T, writer: FieldWriter<'_, '_, R>) {
let mut item = MaybeUninit::new(item);
// SAFETY: `T` guarantees that its encoders and offsets are correct for
// this type.
unsafe {
write_message(
T::NUMBERS,
T::ENCODERS,
T::OFFSETS,
item.as_mut_ptr().cast(),
writer,
);
}
}
fn compute_field_size(item: &mut T, sizer: FieldSizer<'_>) {
// SAFETY: `T` guarantees that its encoders and offsets are correct for
// this type.
unsafe {
compute_size_message::<R>(
T::NUMBERS,
T::ENCODERS,
T::OFFSETS,
std::ptr::from_mut(item).cast::<u8>(),
sizer,
);
}
}
}
unsafe fn write_message<R>(
numbers: &[u32],
encoders: &[ErasedEncoderEntry],
offsets: &[usize],
base: *mut u8,
writer: FieldWriter<'_, '_, R>,
) {
assert_eq!(numbers.len(), encoders.len());
assert_eq!(numbers.len(), offsets.len());
// SAFETY: guaranteed by the caller.
unsafe {
write_message_by_ptr(
numbers.len(),
numbers.as_ptr(),
encoders.as_ptr(),
offsets.as_ptr(),
base,
writer,
)
}
}
#[inline(never)]
unsafe fn write_message_by_ptr<R>(
count: usize,
numbers: *const u32,
encoders: *const ErasedEncoderEntry,
offsets: *const usize,
base: *mut u8,
writer: FieldWriter<'_, '_, R>,
) {
// SAFETY: guaranteed by the caller.
writer.message(|writer| unsafe {
write_fields_inline(
slice::from_raw_parts(numbers, count),
slice::from_raw_parts(encoders, count),
slice::from_raw_parts(offsets, count),
base,
writer,
)
})
}
/// Writes the fields of a message using the provided metadata.
///
/// Note that `base` will no longer contain a valid object after this function
/// returns.
///
/// # Safety
/// The caller must ensure that the provided encoders and offsets correspond to
/// fields in the struct at `base`, and that `base` is owned.
#[doc(hidden)] // only used publicly for `mesh_derive`
pub unsafe fn write_fields<R>(
numbers: &[u32],
encoders: &[ErasedEncoderEntry],
offsets: &[usize],
base: *mut u8,
writer: MessageWriter<'_, '_, R>,
) {
assert_eq!(numbers.len(), encoders.len());
assert_eq!(numbers.len(), offsets.len());
// SAFETY: guaranteed by the caller.
unsafe {
write_fields_by_ptr(
numbers.len(),
numbers.as_ptr(),
encoders.as_ptr(),
offsets.as_ptr(),
base,
writer,
)
}
}
#[inline(never)]
unsafe fn write_fields_by_ptr<R>(
count: usize,
numbers: *const u32,
encoders: *const ErasedEncoderEntry,
offsets: *const usize,
base: *mut u8,
writer: MessageWriter<'_, '_, R>,
) {
// SAFETY: guaranteed by the caller.
unsafe {
write_fields_inline(
slice::from_raw_parts(numbers, count),
slice::from_raw_parts(encoders, count),
slice::from_raw_parts(offsets, count),
base,
writer,
)
}
}
unsafe fn write_fields_inline<R>(
numbers: &[u32],
encoders: &[ErasedEncoderEntry],
offsets: &[usize],
base: *mut u8,
mut writer: MessageWriter<'_, '_, R>,
) {
for ((&number, encoder), &offset) in numbers.iter().zip(encoders).zip(offsets) {
let writer = writer.field(number);
// SAFETY: the caller guarantees that `base` points to an object
// compatible with this encoder and that it will not access the object
// through `base` after this returns.
unsafe {
let ptr = base.add(offset);
match encoder.decode() {
Ok(vtable) => (vtable.write_fn)(ptr, writer),
Err(table) => {
write_message_by_ptr(
table.count,
table.numbers,
table.encoders,
table.offsets,
ptr,
writer,
);
}
}
}
}
}
unsafe fn compute_size_message<R>(
numbers: &[u32],
encoders: &[ErasedEncoderEntry],
offsets: &[usize],
base: *mut u8,
sizer: FieldSizer<'_>,
) {
assert_eq!(numbers.len(), encoders.len());
assert_eq!(numbers.len(), offsets.len());
// SAFETY: guaranteed by the caller.
unsafe {
compute_size_message_by_ptr::<R>(
numbers.len(),
numbers.as_ptr(),
encoders.as_ptr(),
offsets.as_ptr(),
base,
sizer,
)
}
}
#[inline(never)]
unsafe fn compute_size_message_by_ptr<R>(
count: usize,
numbers: *const u32,
encoders: *const ErasedEncoderEntry,
offsets: *const usize,
base: *mut u8,
sizer: FieldSizer<'_>,
) {
// SAFETY: guaranteed by the caller.
sizer.message(|sizer| unsafe {
compute_size_fields_inline::<R>(
slice::from_raw_parts(numbers, count),
slice::from_raw_parts(encoders, count),
slice::from_raw_parts(offsets, count),
base,
sizer,
)
})
}
/// Computes the size of a message using the provided metadata.
///
/// # Safety
/// The caller must ensure that the provided encoders and offsets correspond to
/// fields in the struct at `base`, and that `base` is valid for write.
#[doc(hidden)] // only used publicly for `mesh_derive`
pub unsafe fn compute_size_fields<R>(
numbers: &[u32],
encoders: &[ErasedEncoderEntry],
offsets: &[usize],
base: *mut u8,
sizer: MessageSizer<'_>,
) {
assert_eq!(numbers.len(), encoders.len());
assert_eq!(numbers.len(), offsets.len());
// SAFETY: guaranteed by the caller.
unsafe {
compute_size_fields_by_ptr::<R>(
numbers.len(),
numbers.as_ptr(),
encoders.as_ptr(),
offsets.as_ptr(),
base,
sizer,
)
}
}
#[inline(never)]
unsafe fn compute_size_fields_by_ptr<R>(
count: usize,
numbers: *const u32,
encoders: *const ErasedEncoderEntry,
offsets: *const usize,
base: *mut u8,
sizer: MessageSizer<'_>,
) {
// SAFETY: guaranteed by the caller.
unsafe {
compute_size_fields_inline::<R>(
slice::from_raw_parts(numbers, count),
slice::from_raw_parts(encoders, count),
slice::from_raw_parts(offsets, count),
base,
sizer,
)
}
}
unsafe fn compute_size_fields_inline<R>(
numbers: &[u32],
encoders: &[ErasedEncoderEntry],
offsets: &[usize],
base: *mut u8,
mut sizer: MessageSizer<'_>,
) {
for ((&number, encoder), &offset) in numbers.iter().zip(encoders).zip(offsets) {
let sizer = sizer.field(number);
// SAFETY: the caller guarantees that `base` points to an object
// compatible with this encoder.
unsafe {
let ptr = base.add(offset);
match encoder.decode::<R>() {
Ok(vtable) => (vtable.compute_size_fn)(ptr, sizer),
Err(table) => {
compute_size_message_by_ptr::<R>(
table.count,
table.numbers,
table.encoders,
table.offsets,
ptr,
sizer,
);
}
}
}
}
}
/// Metadata for encoding a struct.
///
/// # Safety
///
/// The implementor must ensure that the `ENCODERS` are correct and complete for
/// `Self` and `R`.
pub unsafe trait StructEncodeMetadata<R>: StructMetadata {
/// The list of encoder vtables.
const ENCODERS: &'static [ErasedEncoderEntry];
}
/// An entry in the encoder table.
///
/// This contains the metadata necessary to apply an encoder to a field.
///
/// This cannot be instantiated directly; use [`FieldEncode::ENTRY`] to get an
/// instance for a particular encoder.
pub struct EncoderEntry<T, R>(ErasedEncoderEntry, PhantomData<fn(T, &mut R)>);
impl<T, R> EncoderEntry<T, R> {
/// # Safety
/// The caller must ensure that the erased entry is an valid entry for `T`
/// and `R`.
pub(crate) const unsafe fn new_unchecked(entry: ErasedEncoderEntry) -> Self {
Self(entry, PhantomData)
}
/// Returns an encoder entry that contains a vtable with methods for
/// encoding the field.
pub(crate) const fn custom<E: FieldEncode<T, R>>() -> Self {
Self(
ErasedEncoderEntry(
std::ptr::from_ref(
const {
&StaticEncoderVtable {
write_fn: write_field_dyn::<T, R, E>,
compute_size_fn: compute_size_field_dyn::<T, R, E>,
}
},
)
.cast::<()>(),
),
PhantomData,
)
}
/// Returns an encoder entry that contains an encoder table.
const fn table() -> Self
where
T: StructEncodeMetadata<R>,
{
Self(
ErasedEncoderEntry(
std::ptr::from_ref(
const {
&EncoderTable {
count: T::NUMBERS.len(),
numbers: T::NUMBERS.as_ptr(),
encoders: T::ENCODERS.as_ptr(),
offsets: T::OFFSETS.as_ptr(),
}
},
)
.cast::<()>()
.wrapping_byte_add(ENTRY_IS_TABLE),
),
PhantomData,
)
}
/// Return the type-erased encoder entry.
pub const fn erase(&self) -> ErasedEncoderEntry {
self.0
}
}
/// An type-erased version of [`EncoderEntry`], for use in a
/// [`StructEncodeMetadata::ENCODERS`] table.
//
// Internally, this is a pointer to either a vtable or a table.
// The low bit is used to distinguish between the two.
#[derive(Copy, Clone)]
pub struct ErasedEncoderEntry(*const ());
const ENTRY_IS_TABLE: usize = 1;
const _: () = assert!(align_of::<ErasedEncoderEntry>() > ENTRY_IS_TABLE);
const _: () = assert!(align_of::<StaticEncoderVtable<()>>() > ENTRY_IS_TABLE);
impl ErasedEncoderEntry {
/// Decodes the entry into either a vtable or a table.
///
/// # Safety
/// The caller must ensure that the encoder was for resource type `R`.
unsafe fn decode<R>(&self) -> Result<&StaticEncoderVtable<R>, &EncoderTable> {
// SAFETY: `R` is guaranteed by caller to be the right type.
unsafe {
if self.0 as usize & ENTRY_IS_TABLE == 0 {
Ok(&*self.0.cast::<StaticEncoderVtable<R>>())
} else {
Err(&*self
.0
.wrapping_byte_sub(ENTRY_IS_TABLE)
.cast::<EncoderTable>())
}
}
}
}
struct EncoderTable {
count: usize,
numbers: *const u32,
encoders: *const ErasedEncoderEntry,
offsets: *const usize,
}
/// A vtable for encoding a message.
struct StaticEncoderVtable<R> {
write_fn: unsafe fn(*mut u8, FieldWriter<'_, '_, R>),
compute_size_fn: unsafe fn(*mut u8, FieldSizer<'_>),
}
unsafe fn write_field_dyn<T, R, E: FieldEncode<T, R>>(
field: *mut u8,
writer: FieldWriter<'_, '_, R>,
) {
// SAFETY: caller guarantees that `field` points to a `T`, and this function
// takes ownership of it.
let field = unsafe { field.cast::<T>().read() };
E::write_field(field, writer);
}
unsafe fn compute_size_field_dyn<T, R, E: FieldEncode<T, R>>(
field: *mut u8,
sizer: FieldSizer<'_>,
) {
// SAFETY: caller guarantees that `field` points to a `T`.
let field = unsafe { &mut *field.cast::<T>() };
E::compute_field_size(field, sizer);
}