• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2023 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 //! UPB FFI wrapper code for use by Rust Protobuf.
9 
10 use crate::__internal::{Enum, Private, SealedInternal};
11 use crate::{
12     IntoProxied, Map, MapIter, MapMut, MapView, Mut, ProtoBytes, ProtoStr, ProtoString, Proxied,
13     ProxiedInMapValue, ProxiedInRepeated, Repeated, RepeatedMut, RepeatedView, View,
14 };
15 use core::fmt::Debug;
16 use std::mem::{size_of, ManuallyDrop, MaybeUninit};
17 use std::ptr::{self, NonNull};
18 use std::slice;
19 use std::sync::OnceLock;
20 
21 #[cfg(bzl)]
22 extern crate upb;
23 #[cfg(not(bzl))]
24 use crate::upb;
25 
26 // Temporarily 'pub' since a lot of gencode is directly calling any of the ffi
27 // fns.
28 pub use upb::*;
29 
30 pub type RawArena = upb::RawArena;
31 pub type RawMessage = upb::RawMessage;
32 pub type RawRepeatedField = upb::RawArray;
33 pub type RawMap = upb::RawMap;
34 pub type PtrAndLen = upb::StringView;
35 
36 impl From<&ProtoStr> for PtrAndLen {
from(s: &ProtoStr) -> Self37     fn from(s: &ProtoStr) -> Self {
38         let bytes = s.as_bytes();
39         Self { ptr: bytes.as_ptr(), len: bytes.len() }
40     }
41 }
42 
43 /// The scratch size of 64 KiB matches the maximum supported size that a
44 /// upb_Message can possibly be.
45 const UPB_SCRATCH_SPACE_BYTES: usize = 65_536;
46 
47 /// Holds a zero-initialized block of memory for use by upb.
48 ///
49 /// By default, if a message is not set in cpp, a default message is created.
50 /// upb departs from this and returns a null ptr. However, since contiguous
51 /// chunks of memory filled with zeroes are legit messages from upb's point of
52 /// view, we can allocate a large block and refer to that when dealing
53 /// with readonly access.
54 #[repr(C, align(8))] // align to UPB_MALLOC_ALIGN = 8
55 #[doc(hidden)]
56 pub struct ScratchSpace([u8; UPB_SCRATCH_SPACE_BYTES]);
57 impl ScratchSpace {
zeroed_block() -> RawMessage58     pub fn zeroed_block() -> RawMessage {
59         static ZEROED_BLOCK: ScratchSpace = ScratchSpace([0; UPB_SCRATCH_SPACE_BYTES]);
60         NonNull::from(&ZEROED_BLOCK).cast()
61     }
62 }
63 
64 #[doc(hidden)]
65 pub type SerializedData = upb::OwnedArenaBox<[u8]>;
66 
67 impl SealedInternal for SerializedData {}
68 
69 impl IntoProxied<ProtoBytes> for SerializedData {
into_proxied(self, _private: Private) -> ProtoBytes70     fn into_proxied(self, _private: Private) -> ProtoBytes {
71         ProtoBytes { inner: InnerProtoString(self) }
72     }
73 }
74 
75 /// The raw contents of every generated message.
76 #[derive(Debug)]
77 #[doc(hidden)]
78 pub struct MessageInner {
79     pub msg: RawMessage,
80     pub arena: Arena,
81 }
82 
83 /// Mutators that point to their original message use this to do so.
84 ///
85 /// Since UPB expects runtimes to manage their own arenas, this needs to have
86 /// access to an `Arena`.
87 ///
88 /// This has two possible designs:
89 /// - Store two pointers here, `RawMessage` and `&'msg Arena`. This doesn't
90 ///   place any restriction on the layout of generated messages and their
91 ///   mutators. This makes a vtable-based mutator three pointers, which can no
92 ///   longer be returned in registers on most platforms.
93 /// - Store one pointer here, `&'msg MessageInner`, where `MessageInner` stores
94 ///   a `RawMessage` and an `Arena`. This would require all generated messages
95 ///   to store `MessageInner`, and since their mutators need to be able to
96 ///   generate `BytesMut`, would also require `BytesMut` to store a `&'msg
97 ///   MessageInner` since they can't store an owned `Arena`.
98 ///
99 /// Note: even though this type is `Copy`, it should only be copied by
100 /// protobuf internals that can maintain mutation invariants:
101 ///
102 /// - No concurrent mutation for any two fields in a message: this means
103 ///   mutators cannot be `Send` but are `Sync`.
104 /// - If there are multiple accessible `Mut` to a single message at a time, they
105 ///   must be different fields, and not be in the same oneof. As such, a `Mut`
106 ///   cannot be `Clone` but *can* reborrow itself with `.as_mut()`, which
107 ///   converts `&'b mut Mut<'a, T>` to `Mut<'b, T>`.
108 #[derive(Clone, Copy, Debug)]
109 #[doc(hidden)]
110 pub struct MutatorMessageRef<'msg> {
111     msg: RawMessage,
112     arena: &'msg Arena,
113 }
114 
115 impl<'msg> MutatorMessageRef<'msg> {
116     #[doc(hidden)]
117     #[allow(clippy::needless_pass_by_ref_mut)] // Sound construction requires mutable access.
new(msg: &'msg mut MessageInner) -> Self118     pub fn new(msg: &'msg mut MessageInner) -> Self {
119         MutatorMessageRef { msg: msg.msg, arena: &msg.arena }
120     }
121 
from_parent(parent_msg: MutatorMessageRef<'msg>, message_field_ptr: RawMessage) -> Self122     pub fn from_parent(parent_msg: MutatorMessageRef<'msg>, message_field_ptr: RawMessage) -> Self {
123         MutatorMessageRef { msg: message_field_ptr, arena: parent_msg.arena }
124     }
125 
msg(&self) -> RawMessage126     pub fn msg(&self) -> RawMessage {
127         self.msg
128     }
129 
arena(&self) -> &Arena130     pub fn arena(&self) -> &Arena {
131         self.arena
132     }
133 }
134 
135 /// Kernel-specific owned `string` and `bytes` field type.
136 #[doc(hidden)]
137 pub struct InnerProtoString(OwnedArenaBox<[u8]>);
138 
139 impl InnerProtoString {
as_bytes(&self) -> &[u8]140     pub(crate) fn as_bytes(&self) -> &[u8] {
141         &self.0
142     }
143 
144     #[doc(hidden)]
into_raw_parts(self) -> (PtrAndLen, Arena)145     pub fn into_raw_parts(self) -> (PtrAndLen, Arena) {
146         let (data_ptr, arena) = self.0.into_parts();
147         (unsafe { data_ptr.as_ref().into() }, arena)
148     }
149 }
150 
151 impl From<&[u8]> for InnerProtoString {
from(val: &[u8]) -> InnerProtoString152     fn from(val: &[u8]) -> InnerProtoString {
153         let arena = Arena::new();
154         let in_arena_copy = arena.copy_slice_in(val).unwrap();
155         // SAFETY:
156         // - `in_arena_copy` is valid slice that will live for `arena`'s lifetime and
157         //   this is the only reference in the program to it.
158         // - `in_arena_copy` is a pointer into an allocation on `arena`
159         InnerProtoString(unsafe { OwnedArenaBox::new(Into::into(in_arena_copy), arena) })
160     }
161 }
162 
163 /// The raw type-erased version of an owned `Repeated`.
164 #[derive(Debug)]
165 #[doc(hidden)]
166 pub struct InnerRepeated {
167     raw: RawRepeatedField,
168     arena: Arena,
169 }
170 
171 impl InnerRepeated {
as_mut(&mut self) -> InnerRepeatedMut<'_>172     pub fn as_mut(&mut self) -> InnerRepeatedMut<'_> {
173         InnerRepeatedMut::new(self.raw, &self.arena)
174     }
175 
raw(&self) -> RawRepeatedField176     pub fn raw(&self) -> RawRepeatedField {
177         self.raw
178     }
179 
arena(&self) -> &Arena180     pub fn arena(&self) -> &Arena {
181         &self.arena
182     }
183 
184     /// # Safety
185     /// - `raw` must be a valid `RawRepeatedField`
from_raw_parts(raw: RawRepeatedField, arena: Arena) -> Self186     pub unsafe fn from_raw_parts(raw: RawRepeatedField, arena: Arena) -> Self {
187         Self { raw, arena }
188     }
189 }
190 
191 /// The raw type-erased pointer version of `RepeatedMut`.
192 #[derive(Clone, Copy, Debug)]
193 #[doc(hidden)]
194 pub struct InnerRepeatedMut<'msg> {
195     pub(crate) raw: RawRepeatedField,
196     arena: &'msg Arena,
197 }
198 
199 impl<'msg> InnerRepeatedMut<'msg> {
200     #[doc(hidden)]
new(raw: RawRepeatedField, arena: &'msg Arena) -> Self201     pub fn new(raw: RawRepeatedField, arena: &'msg Arena) -> Self {
202         InnerRepeatedMut { raw, arena }
203     }
204 }
205 
206 macro_rules! impl_repeated_base {
207     ($t:ty, $elem_t:ty, $ufield:ident, $upb_tag:expr) => {
208         #[allow(dead_code)]
209         #[inline]
210         fn repeated_new(_: Private) -> Repeated<$t> {
211             let arena = Arena::new();
212             Repeated::from_inner(
213                 Private,
214                 InnerRepeated { raw: unsafe { upb_Array_New(arena.raw(), $upb_tag) }, arena },
215             )
216         }
217         #[allow(dead_code)]
218         unsafe fn repeated_free(_: Private, _f: &mut Repeated<$t>) {
219             // No-op: the memory will be dropped by the arena.
220         }
221         #[inline]
222         fn repeated_len(f: View<Repeated<$t>>) -> usize {
223             unsafe { upb_Array_Size(f.as_raw(Private)) }
224         }
225         #[inline]
226         fn repeated_push(mut f: Mut<Repeated<$t>>, v: impl IntoProxied<$t>) {
227             let arena = f.raw_arena(Private);
228             unsafe {
229                 assert!(upb_Array_Append(
230                     f.as_raw(Private),
231                     <$t as UpbTypeConversions>::into_message_value_fuse_if_required(
232                         arena,
233                         v.into_proxied(Private)
234                     ),
235                     arena,
236                 ));
237             }
238         }
239         #[inline]
240         fn repeated_clear(mut f: Mut<Repeated<$t>>) {
241             unsafe {
242                 upb_Array_Resize(f.as_raw(Private), 0, f.raw_arena(Private));
243             }
244         }
245         #[inline]
246         unsafe fn repeated_get_unchecked(f: View<Repeated<$t>>, i: usize) -> View<$t> {
247             unsafe {
248                 <$t as UpbTypeConversions>::from_message_value(upb_Array_Get(f.as_raw(Private), i))
249             }
250         }
251         #[inline]
252         unsafe fn repeated_set_unchecked(
253             mut f: Mut<Repeated<$t>>,
254             i: usize,
255             v: impl IntoProxied<$t>,
256         ) {
257             let arena = f.raw_arena(Private);
258             unsafe {
259                 upb_Array_Set(
260                     f.as_raw(Private),
261                     i,
262                     <$t as UpbTypeConversions>::into_message_value_fuse_if_required(
263                         arena,
264                         v.into_proxied(Private),
265                     ),
266                 )
267             }
268         }
269         #[inline]
270         fn repeated_reserve(mut f: Mut<Repeated<$t>>, additional: usize) {
271             // SAFETY:
272             // - `upb_Array_Reserve` is unsafe but assumed to be sound when called on a
273             //   valid array.
274             unsafe {
275                 let arena = f.raw_arena(Private);
276                 let size = upb_Array_Size(f.as_raw(Private));
277                 assert!(upb_Array_Reserve(f.as_raw(Private), size + additional, arena));
278             }
279         }
280     };
281 }
282 
283 macro_rules! impl_repeated_primitives {
284     ($(($t:ty, $elem_t:ty, $ufield:ident, $upb_tag:expr)),* $(,)?) => {
285         $(
286             unsafe impl ProxiedInRepeated for $t {
287                 impl_repeated_base!($t, $elem_t, $ufield, $upb_tag);
288 
289                 fn repeated_copy_from(src: View<Repeated<$t>>, mut dest: Mut<Repeated<$t>>) {
290                     let arena = dest.raw_arena(Private);
291                     // SAFETY:
292                     // - `upb_Array_Resize` is unsafe but assumed to be always sound to call.
293                     // - `copy_nonoverlapping` is unsafe but here we guarantee that both pointers
294                     //   are valid, the pointers are `#[repr(u8)]`, and the size is correct.
295                     unsafe {
296                         if (!upb_Array_Resize(dest.as_raw(Private), src.len(), arena)) {
297                             panic!("upb_Array_Resize failed.");
298                         }
299                         ptr::copy_nonoverlapping(
300                           upb_Array_DataPtr(src.as_raw(Private)).cast::<u8>(),
301                           upb_Array_MutableDataPtr(dest.as_raw(Private)).cast::<u8>(),
302                           size_of::<$elem_t>() * src.len());
303                     }
304                 }
305             }
306         )*
307     }
308 }
309 
310 macro_rules! impl_repeated_bytes {
311     ($(($t:ty, $upb_tag:expr)),* $(,)?) => {
312         $(
313             unsafe impl ProxiedInRepeated for $t {
314                 impl_repeated_base!($t, PtrAndLen, str_val, $upb_tag);
315 
316                 #[inline]
317                 fn repeated_copy_from(src: View<Repeated<$t>>, mut dest: Mut<Repeated<$t>>) {
318                     let len = src.len();
319                     // SAFETY:
320                     // - `upb_Array_Resize` is unsafe but assumed to be always sound to call.
321                     // - `upb_Array` ensures its elements are never uninitialized memory.
322                     // - The `DataPtr` and `MutableDataPtr` functions return pointers to spans
323                     //   of memory that are valid for at least `len` elements of PtrAndLen.
324                     // - `copy_nonoverlapping` is unsafe but here we guarantee that both pointers
325                     //   are valid, the pointers are `#[repr(u8)]`, and the size is correct.
326                     // - The bytes held within a valid array are valid.
327                     unsafe {
328                         let arena = ManuallyDrop::new(Arena::from_raw(dest.raw_arena(Private)));
329                         if (!upb_Array_Resize(dest.as_raw(Private), src.len(), arena.raw())) {
330                             panic!("upb_Array_Resize failed.");
331                         }
332                         let src_ptrs: &[PtrAndLen] = slice::from_raw_parts(
333                             upb_Array_DataPtr(src.as_raw(Private)).cast(),
334                             len
335                         );
336                         let dest_ptrs: &mut [PtrAndLen] = slice::from_raw_parts_mut(
337                             upb_Array_MutableDataPtr(dest.as_raw(Private)).cast(),
338                             len
339                         );
340                         for (src_ptr, dest_ptr) in src_ptrs.iter().zip(dest_ptrs) {
341                             *dest_ptr = arena.copy_slice_in(src_ptr.as_ref()).unwrap().into();
342                         }
343                     }
344                 }
345             }
346         )*
347     }
348 }
349 
350 impl<'msg, T> RepeatedMut<'msg, T> {
351     // Returns a `RawArena` which is live for at least `'msg`
352     #[doc(hidden)]
raw_arena(&mut self, _private: Private) -> RawArena353     pub fn raw_arena(&mut self, _private: Private) -> RawArena {
354         self.inner.arena.raw()
355     }
356 }
357 
358 impl_repeated_primitives!(
359     // proxied type, element type, upb_MessageValue field name, upb::CType variant
360     (bool, bool, bool_val, upb::CType::Bool),
361     (f32, f32, float_val, upb::CType::Float),
362     (f64, f64, double_val, upb::CType::Double),
363     (i32, i32, int32_val, upb::CType::Int32),
364     (u32, u32, uint32_val, upb::CType::UInt32),
365     (i64, i64, int64_val, upb::CType::Int64),
366     (u64, u64, uint64_val, upb::CType::UInt64),
367 );
368 
369 impl_repeated_bytes!((ProtoString, upb::CType::String), (ProtoBytes, upb::CType::Bytes),);
370 
371 /// Copy the contents of `src` into `dest`.
372 ///
373 /// # Safety
374 /// - `minitable` must be a pointer to the minitable for message `T`.
repeated_message_copy_from<T: ProxiedInRepeated>( src: View<Repeated<T>>, mut dest: Mut<Repeated<T>>, minitable: *const upb_MiniTable, )375 pub unsafe fn repeated_message_copy_from<T: ProxiedInRepeated>(
376     src: View<Repeated<T>>,
377     mut dest: Mut<Repeated<T>>,
378     minitable: *const upb_MiniTable,
379 ) {
380     // SAFETY:
381     // - `src.as_raw()` is a valid `const upb_Array*`.
382     // - `dest.as_raw()` is a valid `upb_Array*`.
383     // - Elements of `src` and have message minitable `$minitable$`.
384     unsafe {
385         let size = upb_Array_Size(src.as_raw(Private));
386         if !upb_Array_Resize(dest.as_raw(Private), size, dest.raw_arena(Private)) {
387             panic!("upb_Array_Resize failed.");
388         }
389         for i in 0..size {
390             let src_msg = upb_Array_Get(src.as_raw(Private), i)
391                 .msg_val
392                 .expect("upb_Array* element should not be NULL");
393             // Avoid the use of `upb_Array_DeepClone` as it creates an
394             // entirely new `upb_Array*` at a new memory address.
395             let cloned_msg = upb_Message_DeepClone(src_msg, minitable, dest.raw_arena(Private))
396                 .expect("upb_Message_DeepClone failed.");
397             upb_Array_Set(dest.as_raw(Private), i, upb_MessageValue { msg_val: Some(cloned_msg) });
398         }
399     }
400 }
401 
402 /// Cast a `RepeatedView<SomeEnum>` to `RepeatedView<i32>`.
cast_enum_repeated_view<E: Enum + ProxiedInRepeated>( repeated: RepeatedView<E>, ) -> RepeatedView<i32>403 pub fn cast_enum_repeated_view<E: Enum + ProxiedInRepeated>(
404     repeated: RepeatedView<E>,
405 ) -> RepeatedView<i32> {
406     // SAFETY: Reading an enum array as an i32 array is sound.
407     unsafe { RepeatedView::from_raw(Private, repeated.as_raw(Private)) }
408 }
409 
410 /// Cast a `RepeatedMut<SomeEnum>` to `RepeatedMut<i32>`.
411 ///
412 /// Writing an unknown value is sound because all enums
413 /// are representationally open.
cast_enum_repeated_mut<E: Enum + ProxiedInRepeated>( repeated: RepeatedMut<E>, ) -> RepeatedMut<i32>414 pub fn cast_enum_repeated_mut<E: Enum + ProxiedInRepeated>(
415     repeated: RepeatedMut<E>,
416 ) -> RepeatedMut<i32> {
417     // SAFETY:
418     // - Reading an enum array as an i32 array is sound.
419     // - No shared mutation is possible through the output.
420     unsafe {
421         let InnerRepeatedMut { arena, raw, .. } = repeated.inner;
422         RepeatedMut::from_inner(Private, InnerRepeatedMut { arena, raw })
423     }
424 }
425 
426 /// Cast a `RepeatedMut<SomeEnum>` to `RepeatedMut<i32>` and call
427 /// repeated_reserve.
reserve_enum_repeated_mut<E: Enum + ProxiedInRepeated>( repeated: RepeatedMut<E>, additional: usize, )428 pub fn reserve_enum_repeated_mut<E: Enum + ProxiedInRepeated>(
429     repeated: RepeatedMut<E>,
430     additional: usize,
431 ) {
432     let int_repeated = cast_enum_repeated_mut(repeated);
433     ProxiedInRepeated::repeated_reserve(int_repeated, additional);
434 }
435 
new_enum_repeated<E: Enum + ProxiedInRepeated>() -> Repeated<E>436 pub fn new_enum_repeated<E: Enum + ProxiedInRepeated>() -> Repeated<E> {
437     let arena = Arena::new();
438     // SAFETY:
439     // - `upb_Array_New` is unsafe but assumed to be sound when called on a valid
440     //   arena.
441     unsafe {
442         let raw = upb_Array_New(arena.raw(), upb::CType::Int32);
443         Repeated::from_inner(Private, InnerRepeated::from_raw_parts(raw, arena))
444     }
445 }
446 
free_enum_repeated<E: Enum + ProxiedInRepeated>(_repeated: &mut Repeated<E>)447 pub fn free_enum_repeated<E: Enum + ProxiedInRepeated>(_repeated: &mut Repeated<E>) {
448     // No-op: the memory will be dropped by the arena.
449 }
450 
451 /// Returns a static empty RepeatedView.
empty_array<T: ProxiedInRepeated>() -> RepeatedView<'static, T>452 pub fn empty_array<T: ProxiedInRepeated>() -> RepeatedView<'static, T> {
453     // TODO: Consider creating a static empty array in C.
454 
455     // Use `i32` for a shared empty repeated for all repeated types in the program.
456     static EMPTY_REPEATED_VIEW: OnceLock<Repeated<i32>> = OnceLock::new();
457 
458     // SAFETY:
459     // - Because the repeated is never mutated, the repeated type is unused and
460     //   therefore valid for `T`.
461     unsafe {
462         RepeatedView::from_raw(
463             Private,
464             EMPTY_REPEATED_VIEW.get_or_init(Repeated::new).as_view().as_raw(Private),
465         )
466     }
467 }
468 
469 /// Returns a static empty MapView.
empty_map<K, V>() -> MapView<'static, K, V> where K: Proxied, V: ProxiedInMapValue<K>,470 pub fn empty_map<K, V>() -> MapView<'static, K, V>
471 where
472     K: Proxied,
473     V: ProxiedInMapValue<K>,
474 {
475     // TODO: Consider creating a static empty map in C.
476 
477     // Use `<bool, bool>` for a shared empty map for all map types.
478     //
479     // This relies on an implicit contract with UPB that it is OK to use an empty
480     // Map<bool, bool> as an empty map of all other types. The only const
481     // function on `upb_Map` that will care about the size of key or value is
482     // `get()` where it will hash the appropriate number of bytes of the
483     // provided `upb_MessageValue`, and that bool being the smallest type in the
484     // union means it will happen to work for all possible key types.
485     //
486     // If we used a larger key, then UPB would hash more bytes of the key than Rust
487     // initialized.
488     static EMPTY_MAP_VIEW: OnceLock<Map<bool, bool>> = OnceLock::new();
489 
490     // SAFETY:
491     // - The map is empty and never mutated.
492     // - The value type is never used.
493     // - The size of the key type is used when `get()` computes the hash of the key.
494     //   The map is empty, therefore it doesn't matter what hash is computed, but we
495     //   have to use `bool` type as the smallest key possible (otherwise UPB would
496     //   read more bytes than Rust allocated).
497     unsafe {
498         MapView::from_raw(Private, EMPTY_MAP_VIEW.get_or_init(Map::new).as_view().as_raw(Private))
499     }
500 }
501 
502 impl<'msg, K: ?Sized, V: ?Sized> MapMut<'msg, K, V> {
503     // Returns a `RawArena` which is live for at least `'msg`
504     #[doc(hidden)]
raw_arena(&mut self, _private: Private) -> RawArena505     pub fn raw_arena(&mut self, _private: Private) -> RawArena {
506         self.inner.arena.raw()
507     }
508 }
509 
510 #[derive(Debug)]
511 #[doc(hidden)]
512 pub struct InnerMap {
513     pub(crate) raw: RawMap,
514     arena: Arena,
515 }
516 
517 impl InnerMap {
new(raw: RawMap, arena: Arena) -> Self518     pub fn new(raw: RawMap, arena: Arena) -> Self {
519         Self { raw, arena }
520     }
521 
as_mut(&mut self) -> InnerMapMut<'_>522     pub fn as_mut(&mut self) -> InnerMapMut<'_> {
523         InnerMapMut { raw: self.raw, arena: &self.arena }
524     }
525 }
526 
527 #[derive(Clone, Copy, Debug)]
528 #[doc(hidden)]
529 pub struct InnerMapMut<'msg> {
530     pub(crate) raw: RawMap,
531     arena: &'msg Arena,
532 }
533 
534 #[doc(hidden)]
535 impl<'msg> InnerMapMut<'msg> {
new(raw: RawMap, arena: &'msg Arena) -> Self536     pub fn new(raw: RawMap, arena: &'msg Arena) -> Self {
537         InnerMapMut { raw, arena }
538     }
539 
540     #[doc(hidden)]
as_raw(&self) -> RawMap541     pub fn as_raw(&self) -> RawMap {
542         self.raw
543     }
544 
545     #[doc(hidden)]
raw_arena(&self) -> RawArena546     pub fn raw_arena(&self) -> RawArena {
547         self.arena.raw()
548     }
549 }
550 
551 pub trait UpbTypeConversions: Proxied {
upb_type() -> upb::CType552     fn upb_type() -> upb::CType;
553 
to_message_value(val: View<'_, Self>) -> upb_MessageValue554     fn to_message_value(val: View<'_, Self>) -> upb_MessageValue;
555 
556     /// # Safety
557     /// - `raw_arena` must point to a valid upb arena.
into_message_value_fuse_if_required( raw_arena: RawArena, val: Self, ) -> upb_MessageValue558     unsafe fn into_message_value_fuse_if_required(
559         raw_arena: RawArena,
560         val: Self,
561     ) -> upb_MessageValue;
562 
563     /// # Safety
564     /// - `msg` must be the correct variant for `Self`.
565     /// - `msg` pointers must point to memory valid for `'msg` lifetime.
from_message_value<'msg>(msg: upb_MessageValue) -> View<'msg, Self>566     unsafe fn from_message_value<'msg>(msg: upb_MessageValue) -> View<'msg, Self>;
567 }
568 
569 macro_rules! impl_upb_type_conversions_for_scalars {
570     ($($t:ty, $ufield:ident, $upb_tag:expr, $zero_val:literal;)*) => {
571         $(
572             impl UpbTypeConversions for $t {
573                 #[inline(always)]
574                 fn upb_type() -> upb::CType {
575                     $upb_tag
576                 }
577 
578                 #[inline(always)]
579                 fn to_message_value(val: View<'_, $t>) -> upb_MessageValue {
580                     upb_MessageValue { $ufield: val }
581                 }
582 
583                 #[inline(always)]
584                 unsafe fn into_message_value_fuse_if_required(_: RawArena, val: $t) -> upb_MessageValue {
585                     Self::to_message_value(val)
586                 }
587 
588                 #[inline(always)]
589                 unsafe fn from_message_value<'msg>(msg: upb_MessageValue) -> View<'msg, $t> {
590                     unsafe { msg.$ufield }
591                 }
592             }
593         )*
594     };
595 }
596 
597 impl_upb_type_conversions_for_scalars!(
598     f32, float_val, upb::CType::Float, 0f32;
599     f64, double_val, upb::CType::Double, 0f64;
600     i32, int32_val, upb::CType::Int32, 0i32;
601     u32, uint32_val, upb::CType::UInt32, 0u32;
602     i64, int64_val, upb::CType::Int64, 0i64;
603     u64, uint64_val, upb::CType::UInt64, 0u64;
604     bool, bool_val, upb::CType::Bool, false;
605 );
606 
607 impl UpbTypeConversions for ProtoBytes {
upb_type() -> upb::CType608     fn upb_type() -> upb::CType {
609         upb::CType::Bytes
610     }
611 
to_message_value(val: View<'_, ProtoBytes>) -> upb_MessageValue612     fn to_message_value(val: View<'_, ProtoBytes>) -> upb_MessageValue {
613         upb_MessageValue { str_val: val.into() }
614     }
615 
into_message_value_fuse_if_required( raw_parent_arena: RawArena, val: ProtoBytes, ) -> upb_MessageValue616     unsafe fn into_message_value_fuse_if_required(
617         raw_parent_arena: RawArena,
618         val: ProtoBytes,
619     ) -> upb_MessageValue {
620         // SAFETY: The arena memory is not freed due to `ManuallyDrop`.
621         let parent_arena = ManuallyDrop::new(unsafe { Arena::from_raw(raw_parent_arena) });
622 
623         let (view, arena) = val.inner.into_raw_parts();
624         parent_arena.fuse(&arena);
625 
626         upb_MessageValue { str_val: view }
627     }
628 
from_message_value<'msg>(msg: upb_MessageValue) -> View<'msg, ProtoBytes>629     unsafe fn from_message_value<'msg>(msg: upb_MessageValue) -> View<'msg, ProtoBytes> {
630         unsafe { msg.str_val.as_ref() }
631     }
632 }
633 
634 impl UpbTypeConversions for ProtoString {
upb_type() -> upb::CType635     fn upb_type() -> upb::CType {
636         upb::CType::String
637     }
638 
to_message_value(val: View<'_, ProtoString>) -> upb_MessageValue639     fn to_message_value(val: View<'_, ProtoString>) -> upb_MessageValue {
640         upb_MessageValue { str_val: val.as_bytes().into() }
641     }
642 
into_message_value_fuse_if_required( raw_arena: RawArena, val: ProtoString, ) -> upb_MessageValue643     unsafe fn into_message_value_fuse_if_required(
644         raw_arena: RawArena,
645         val: ProtoString,
646     ) -> upb_MessageValue {
647         // SAFETY: `raw_arena` is valid as promised by the caller
648         unsafe {
649             <ProtoBytes as UpbTypeConversions>::into_message_value_fuse_if_required(
650                 raw_arena,
651                 val.into(),
652             )
653         }
654     }
655 
from_message_value<'msg>(msg: upb_MessageValue) -> View<'msg, ProtoString>656     unsafe fn from_message_value<'msg>(msg: upb_MessageValue) -> View<'msg, ProtoString> {
657         unsafe { ProtoStr::from_utf8_unchecked(msg.str_val.as_ref()) }
658     }
659 }
660 
661 #[doc(hidden)]
662 pub struct RawMapIter {
663     // TODO: Replace this `RawMap` with the const type.
664     map: RawMap,
665     iter: usize,
666 }
667 
668 impl RawMapIter {
new(map: RawMap) -> Self669     pub fn new(map: RawMap) -> Self {
670         RawMapIter { map, iter: UPB_MAP_BEGIN }
671     }
672 
673     /// # Safety
674     /// - `self.map` must be valid, and remain valid while the return value is
675     ///   in use.
next_unchecked(&mut self) -> Option<(upb_MessageValue, upb_MessageValue)>676     pub unsafe fn next_unchecked(&mut self) -> Option<(upb_MessageValue, upb_MessageValue)> {
677         let mut key = MaybeUninit::uninit();
678         let mut value = MaybeUninit::uninit();
679         // SAFETY: the `map` is valid as promised by the caller
680         unsafe { upb_Map_Next(self.map, key.as_mut_ptr(), value.as_mut_ptr(), &mut self.iter) }
681             // SAFETY: if upb_Map_Next returns true, then key and value have been populated.
682             .then(|| unsafe { (key.assume_init(), value.assume_init()) })
683     }
684 }
685 
686 impl<Key, MessageType> ProxiedInMapValue<Key> for MessageType
687 where
688     Key: Proxied + UpbTypeConversions,
689     MessageType: Proxied + UpbTypeConversions,
690 {
map_new(_private: Private) -> Map<Key, Self>691     fn map_new(_private: Private) -> Map<Key, Self> {
692         let arena = Arena::new();
693         let raw = unsafe {
694             upb_Map_New(
695                 arena.raw(),
696                 <Key as UpbTypeConversions>::upb_type(),
697                 <Self as UpbTypeConversions>::upb_type(),
698             )
699         };
700 
701         Map::from_inner(Private, InnerMap::new(raw, arena))
702     }
703 
map_free(_private: Private, _map: &mut Map<Key, Self>)704     unsafe fn map_free(_private: Private, _map: &mut Map<Key, Self>) {
705         // No-op: the memory will be dropped by the arena.
706     }
707 
map_clear(mut map: MapMut<Key, Self>)708     fn map_clear(mut map: MapMut<Key, Self>) {
709         unsafe {
710             upb_Map_Clear(map.as_raw(Private));
711         }
712     }
713 
map_len(map: MapView<Key, Self>) -> usize714     fn map_len(map: MapView<Key, Self>) -> usize {
715         unsafe { upb_Map_Size(map.as_raw(Private)) }
716     }
717 
map_insert( mut map: MapMut<Key, Self>, key: View<'_, Key>, value: impl IntoProxied<Self>, ) -> bool718     fn map_insert(
719         mut map: MapMut<Key, Self>,
720         key: View<'_, Key>,
721         value: impl IntoProxied<Self>,
722     ) -> bool {
723         let arena = map.inner(Private).raw_arena();
724         unsafe {
725             upb_Map_InsertAndReturnIfInserted(
726                 map.as_raw(Private),
727                 <Key as UpbTypeConversions>::to_message_value(key),
728                 <Self as UpbTypeConversions>::into_message_value_fuse_if_required(
729                     arena,
730                     value.into_proxied(Private),
731                 ),
732                 arena,
733             )
734         }
735     }
736 
map_get<'a>(map: MapView<'a, Key, Self>, key: View<'_, Key>) -> Option<View<'a, Self>>737     fn map_get<'a>(map: MapView<'a, Key, Self>, key: View<'_, Key>) -> Option<View<'a, Self>> {
738         let mut val = MaybeUninit::uninit();
739         let found = unsafe {
740             upb_Map_Get(
741                 map.as_raw(Private),
742                 <Key as UpbTypeConversions>::to_message_value(key),
743                 val.as_mut_ptr(),
744             )
745         };
746         if !found {
747             return None;
748         }
749         Some(unsafe { <Self as UpbTypeConversions>::from_message_value(val.assume_init()) })
750     }
751 
map_remove(mut map: MapMut<Key, Self>, key: View<'_, Key>) -> bool752     fn map_remove(mut map: MapMut<Key, Self>, key: View<'_, Key>) -> bool {
753         unsafe {
754             upb_Map_Delete(
755                 map.as_raw(Private),
756                 <Key as UpbTypeConversions>::to_message_value(key),
757                 ptr::null_mut(),
758             )
759         }
760     }
map_iter(map: MapView<Key, Self>) -> MapIter<Key, Self>761     fn map_iter(map: MapView<Key, Self>) -> MapIter<Key, Self> {
762         // SAFETY: MapView<'_,..>> guarantees its RawMap outlives '_.
763         unsafe { MapIter::from_raw(Private, RawMapIter::new(map.as_raw(Private))) }
764     }
765 
map_iter_next<'a>( iter: &mut MapIter<'a, Key, Self>, ) -> Option<(View<'a, Key>, View<'a, Self>)>766     fn map_iter_next<'a>(
767         iter: &mut MapIter<'a, Key, Self>,
768     ) -> Option<(View<'a, Key>, View<'a, Self>)> {
769         // SAFETY: MapIter<'a, ..> guarantees its RawMapIter outlives 'a.
770         unsafe { iter.as_raw_mut(Private).next_unchecked() }
771             // SAFETY: MapIter<K, V> returns key and values message values
772             //         with the variants for K and V active.
773             .map(|(k, v)| unsafe {
774                 (
775                     <Key as UpbTypeConversions>::from_message_value(k),
776                     <Self as UpbTypeConversions>::from_message_value(v),
777                 )
778             })
779     }
780 }
781 
782 /// `upb_Map_Insert`, but returns a `bool` for whether insert occurred.
783 ///
784 /// Returns `true` if the entry was newly inserted.
785 ///
786 /// # Panics
787 /// Panics if the arena is out of memory.
788 ///
789 /// # Safety
790 /// The same as `upb_Map_Insert`:
791 /// - `map` must be a valid map.
792 /// - The `arena` must be valid and outlive the map.
793 /// - The inserted value must outlive the map.
794 #[allow(non_snake_case)]
upb_Map_InsertAndReturnIfInserted( map: RawMap, key: upb_MessageValue, value: upb_MessageValue, arena: RawArena, ) -> bool795 pub unsafe fn upb_Map_InsertAndReturnIfInserted(
796     map: RawMap,
797     key: upb_MessageValue,
798     value: upb_MessageValue,
799     arena: RawArena,
800 ) -> bool {
801     match unsafe { upb_Map_Insert(map, key, value, arena) } {
802         upb::MapInsertStatus::Inserted => true,
803         upb::MapInsertStatus::Replaced => false,
804         upb::MapInsertStatus::OutOfMemory => panic!("map arena is out of memory"),
805     }
806 }
807