1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2023 Google LLC. All rights reserved.
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
8 //! UPB FFI wrapper code for use by Rust Protobuf.
10 use crate::__internal::{Enum, Private, SealedInternal};
12 IntoProxied, Map, MapIter, MapMut, MapView, Mut, ProtoBytes, ProtoStr, ProtoString, Proxied,
13 ProxiedInMapValue, ProxiedInRepeated, Repeated, RepeatedMut, RepeatedView, View,
16 use std::mem::{size_of, ManuallyDrop, MaybeUninit};
17 use std::ptr::{self, NonNull};
19 use std::sync::OnceLock;
26 // Temporarily 'pub' since a lot of gencode is directly calling any of the ffi
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;
36 impl From<&ProtoStr> for PtrAndLen {
37 fn from(s: &ProtoStr) -> Self {
38 let bytes = s.as_bytes();
39 Self { ptr: bytes.as_ptr(), len: bytes.len() }
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;
47 /// Holds a zero-initialized block of memory for use by upb.
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
56 pub struct ScratchSpace([u8; UPB_SCRATCH_SPACE_BYTES]);
58 pub fn zeroed_block() -> RawMessage {
59 static ZEROED_BLOCK: ScratchSpace = ScratchSpace([0; UPB_SCRATCH_SPACE_BYTES]);
60 NonNull::from(&ZEROED_BLOCK).cast()
65 pub type SerializedData = upb::OwnedArenaBox<[u8]>;
67 impl SealedInternal for SerializedData {}
69 impl IntoProxied<ProtoBytes> for SerializedData {
70 fn into_proxied(self, _private: Private) -> ProtoBytes {
71 ProtoBytes { inner: InnerProtoString(self) }
75 /// The raw contents of every generated message.
78 pub struct MessageInner {
83 /// Mutators that point to their original message use this to do so.
85 /// Since UPB expects runtimes to manage their own arenas, this needs to have
86 /// access to an `Arena`.
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`.
99 /// Note: even though this type is `Copy`, it should only be copied by
100 /// protobuf internals that can maintain mutation invariants:
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)]
110 pub struct MutatorMessageRef<'msg> {
115 impl<'msg> MutatorMessageRef<'msg> {
117 #[allow(clippy::needless_pass_by_ref_mut)] // Sound construction requires mutable access.
118 pub fn new(msg: &'msg mut MessageInner) -> Self {
119 MutatorMessageRef { msg: msg.msg, arena: &msg.arena }
122 pub fn from_parent(parent_msg: MutatorMessageRef<'msg>, message_field_ptr: RawMessage) -> Self {
123 MutatorMessageRef { msg: message_field_ptr, arena: parent_msg.arena }
126 pub fn msg(&self) -> RawMessage {
130 pub fn arena(&self) -> &Arena {
135 /// Kernel-specific owned `string` and `bytes` field type.
137 pub struct InnerProtoString(OwnedArenaBox<[u8]>);
139 impl InnerProtoString {
140 pub(crate) fn as_bytes(&self) -> &[u8] {
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)
151 impl From<&[u8]> for InnerProtoString {
152 fn from(val: &[u8]) -> InnerProtoString {
153 let arena = Arena::new();
154 let in_arena_copy = arena.copy_slice_in(val).unwrap();
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) })
163 /// The raw type-erased version of an owned `Repeated`.
166 pub struct InnerRepeated {
167 raw: RawRepeatedField,
172 pub fn as_mut(&mut self) -> InnerRepeatedMut<'_> {
173 InnerRepeatedMut::new(self.raw, &self.arena)
176 pub fn raw(&self) -> RawRepeatedField {
180 pub fn arena(&self) -> &Arena {
185 /// - `raw` must be a valid `RawRepeatedField`
186 pub unsafe fn from_raw_parts(raw: RawRepeatedField, arena: Arena) -> Self {
191 /// The raw type-erased pointer version of `RepeatedMut`.
192 #[derive(Clone, Copy, Debug)]
194 pub struct InnerRepeatedMut<'msg> {
195 pub(crate) raw: RawRepeatedField,
199 impl<'msg> InnerRepeatedMut<'msg> {
201 pub fn new(raw: RawRepeatedField, arena: &'msg Arena) -> Self {
202 InnerRepeatedMut { raw, arena }
206 macro_rules! impl_repeated_base {
207 ($t:ty, $elem_t:ty, $ufield:ident, $upb_tag:expr) => {
210 fn repeated_new(_: Private) -> Repeated<$t> {
211 let arena = Arena::new();
212 Repeated::from_inner(
214 InnerRepeated { raw: unsafe { upb_Array_New(arena.raw(), $upb_tag) }, arena },
218 unsafe fn repeated_free(_: Private, _f: &mut Repeated<$t>) {
219 // No-op: the memory will be dropped by the arena.
222 fn repeated_len(f: View<Repeated<$t>>) -> usize {
223 unsafe { upb_Array_Size(f.as_raw(Private)) }
226 fn repeated_push(mut f: Mut<Repeated<$t>>, v: impl IntoProxied<$t>) {
227 let arena = f.raw_arena(Private);
229 assert!(upb_Array_Append(
231 <$t as UpbTypeConversions>::into_message_value_fuse_if_required(
233 v.into_proxied(Private)
240 fn repeated_clear(mut f: Mut<Repeated<$t>>) {
242 upb_Array_Resize(f.as_raw(Private), 0, f.raw_arena(Private));
246 unsafe fn repeated_get_unchecked(f: View<Repeated<$t>>, i: usize) -> View<$t> {
248 <$t as UpbTypeConversions>::from_message_value(upb_Array_Get(f.as_raw(Private), i))
252 unsafe fn repeated_set_unchecked(
253 mut f: Mut<Repeated<$t>>,
255 v: impl IntoProxied<$t>,
257 let arena = f.raw_arena(Private);
262 <$t as UpbTypeConversions>::into_message_value_fuse_if_required(
264 v.into_proxied(Private),
270 fn repeated_reserve(mut f: Mut<Repeated<$t>>, additional: usize) {
272 // - `upb_Array_Reserve` is unsafe but assumed to be sound when called on a
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));
283 macro_rules! impl_repeated_primitives {
284 ($(($t:ty, $elem_t:ty, $ufield:ident, $upb_tag:expr)),* $(,)?) => {
286 unsafe impl ProxiedInRepeated for $t {
287 impl_repeated_base!($t, $elem_t, $ufield, $upb_tag);
289 fn repeated_copy_from(src: View<Repeated<$t>>, mut dest: Mut<Repeated<$t>>) {
290 let arena = dest.raw_arena(Private);
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.
296 if (!upb_Array_Resize(dest.as_raw(Private), src.len(), arena)) {
297 panic!("upb_Array_Resize failed.");
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());
310 macro_rules! impl_repeated_bytes {
311 ($(($t:ty, $upb_tag:expr)),* $(,)?) => {
313 unsafe impl ProxiedInRepeated for $t {
314 impl_repeated_base!($t, PtrAndLen, str_val, $upb_tag);
317 fn repeated_copy_from(src: View<Repeated<$t>>, mut dest: Mut<Repeated<$t>>) {
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.
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.");
332 let src_ptrs: &[PtrAndLen] = slice::from_raw_parts(
333 upb_Array_DataPtr(src.as_raw(Private)).cast(),
336 let dest_ptrs: &mut [PtrAndLen] = slice::from_raw_parts_mut(
337 upb_Array_MutableDataPtr(dest.as_raw(Private)).cast(),
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();
350 impl<'msg, T> RepeatedMut<'msg, T> {
351 // Returns a `RawArena` which is live for at least `'msg`
353 pub fn raw_arena(&mut self, _private: Private) -> RawArena {
354 self.inner.arena.raw()
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),
369 impl_repeated_bytes!((ProtoString, upb::CType::String), (ProtoBytes, upb::CType::Bytes),);
371 /// Copy the contents of `src` into `dest`.
374 /// - `minitable` must be a pointer to the minitable for message `T`.
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,
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$`.
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.");
390 let src_msg = upb_Array_Get(src.as_raw(Private), i)
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) });
402 /// Cast a `RepeatedView<SomeEnum>` to `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)) }
410 /// Cast a `RepeatedMut<SomeEnum>` to `RepeatedMut<i32>`.
412 /// Writing an unknown value is sound because all enums
413 /// are representationally open.
414 pub fn cast_enum_repeated_mut<E: Enum + ProxiedInRepeated>(
415 repeated: RepeatedMut<E>,
416 ) -> RepeatedMut<i32> {
418 // - Reading an enum array as an i32 array is sound.
419 // - No shared mutation is possible through the output.
421 let InnerRepeatedMut { arena, raw, .. } = repeated.inner;
422 RepeatedMut::from_inner(Private, InnerRepeatedMut { arena, raw })
426 /// Cast a `RepeatedMut<SomeEnum>` to `RepeatedMut<i32>` and call
427 /// repeated_reserve.
428 pub fn reserve_enum_repeated_mut<E: Enum + ProxiedInRepeated>(
429 repeated: RepeatedMut<E>,
432 let int_repeated = cast_enum_repeated_mut(repeated);
433 ProxiedInRepeated::repeated_reserve(int_repeated, additional);
436 pub fn new_enum_repeated<E: Enum + ProxiedInRepeated>() -> Repeated<E> {
437 let arena = Arena::new();
439 // - `upb_Array_New` is unsafe but assumed to be sound when called on a valid
442 let raw = upb_Array_New(arena.raw(), upb::CType::Int32);
443 Repeated::from_inner(Private, InnerRepeated::from_raw_parts(raw, arena))
447 pub fn free_enum_repeated<E: Enum + ProxiedInRepeated>(_repeated: &mut Repeated<E>) {
448 // No-op: the memory will be dropped by the arena.
451 /// Returns a static empty RepeatedView.
452 pub fn empty_array<T: ProxiedInRepeated>() -> RepeatedView<'static, T> {
453 // TODO: Consider creating a static empty array in C.
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();
459 // - Because the repeated is never mutated, the repeated type is unused and
460 // therefore valid for `T`.
462 RepeatedView::from_raw(
464 EMPTY_REPEATED_VIEW.get_or_init(Repeated::new).as_view().as_raw(Private),
469 /// Returns a static empty MapView.
470 pub fn empty_map<K, V>() -> MapView<'static, K, V>
473 V: ProxiedInMapValue<K>,
475 // TODO: Consider creating a static empty map in C.
477 // Use `<bool, bool>` for a shared empty map for all map types.
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.
486 // If we used a larger key, then UPB would hash more bytes of the key than Rust
488 static EMPTY_MAP_VIEW: OnceLock<Map<bool, bool>> = OnceLock::new();
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).
498 MapView::from_raw(Private, EMPTY_MAP_VIEW.get_or_init(Map::new).as_view().as_raw(Private))
502 impl<'msg, K: ?Sized, V: ?Sized> MapMut<'msg, K, V> {
503 // Returns a `RawArena` which is live for at least `'msg`
505 pub fn raw_arena(&mut self, _private: Private) -> RawArena {
506 self.inner.arena.raw()
512 pub struct InnerMap {
513 pub(crate) raw: RawMap,
518 pub fn new(raw: RawMap, arena: Arena) -> Self {
522 pub fn as_mut(&mut self) -> InnerMapMut<'_> {
523 InnerMapMut { raw: self.raw, arena: &self.arena }
527 #[derive(Clone, Copy, Debug)]
529 pub struct InnerMapMut<'msg> {
530 pub(crate) raw: RawMap,
535 impl<'msg> InnerMapMut<'msg> {
536 pub fn new(raw: RawMap, arena: &'msg Arena) -> Self {
537 InnerMapMut { raw, arena }
541 pub fn as_raw(&self) -> RawMap {
545 pub fn arena(&mut self) -> &Arena {
550 pub fn raw_arena(&mut self) -> RawArena {
555 pub trait UpbTypeConversions: Proxied {
556 fn upb_type() -> upb::CType;
558 fn to_message_value(val: View<'_, Self>) -> upb_MessageValue;
561 /// - `raw_arena` must point to a valid upb arena.
562 unsafe fn into_message_value_fuse_if_required(
565 ) -> upb_MessageValue;
568 /// - `msg` must be the correct variant for `Self`.
569 /// - `msg` pointers must point to memory valid for `'msg` lifetime.
570 unsafe fn from_message_value<'msg>(msg: upb_MessageValue) -> View<'msg, Self>;
573 macro_rules! impl_upb_type_conversions_for_scalars {
574 ($($t:ty, $ufield:ident, $upb_tag:expr, $zero_val:literal;)*) => {
576 impl UpbTypeConversions for $t {
578 fn upb_type() -> upb::CType {
583 fn to_message_value(val: View<'_, $t>) -> upb_MessageValue {
584 upb_MessageValue { $ufield: val }
588 unsafe fn into_message_value_fuse_if_required(_: RawArena, val: $t) -> upb_MessageValue {
589 Self::to_message_value(val)
593 unsafe fn from_message_value<'msg>(msg: upb_MessageValue) -> View<'msg, $t> {
594 unsafe { msg.$ufield }
601 impl_upb_type_conversions_for_scalars!(
602 f32, float_val, upb::CType::Float, 0f32;
603 f64, double_val, upb::CType::Double, 0f64;
604 i32, int32_val, upb::CType::Int32, 0i32;
605 u32, uint32_val, upb::CType::UInt32, 0u32;
606 i64, int64_val, upb::CType::Int64, 0i64;
607 u64, uint64_val, upb::CType::UInt64, 0u64;
608 bool, bool_val, upb::CType::Bool, false;
611 impl UpbTypeConversions for ProtoBytes {
612 fn upb_type() -> upb::CType {
616 fn to_message_value(val: View<'_, ProtoBytes>) -> upb_MessageValue {
617 upb_MessageValue { str_val: val.into() }
620 unsafe fn into_message_value_fuse_if_required(
621 raw_parent_arena: RawArena,
623 ) -> upb_MessageValue {
624 // SAFETY: The arena memory is not freed due to `ManuallyDrop`.
625 let parent_arena = ManuallyDrop::new(unsafe { Arena::from_raw(raw_parent_arena) });
627 let (view, arena) = val.inner.into_raw_parts();
628 parent_arena.fuse(&arena);
630 upb_MessageValue { str_val: view }
633 unsafe fn from_message_value<'msg>(msg: upb_MessageValue) -> View<'msg, ProtoBytes> {
634 unsafe { msg.str_val.as_ref() }
638 impl UpbTypeConversions for ProtoString {
639 fn upb_type() -> upb::CType {
643 fn to_message_value(val: View<'_, ProtoString>) -> upb_MessageValue {
644 upb_MessageValue { str_val: val.as_bytes().into() }
647 unsafe fn into_message_value_fuse_if_required(
650 ) -> upb_MessageValue {
651 // SAFETY: `raw_arena` is valid as promised by the caller
653 <ProtoBytes as UpbTypeConversions>::into_message_value_fuse_if_required(
660 unsafe fn from_message_value<'msg>(msg: upb_MessageValue) -> View<'msg, ProtoString> {
661 unsafe { ProtoStr::from_utf8_unchecked(msg.str_val.as_ref()) }
666 pub struct RawMapIter {
667 // TODO: Replace this `RawMap` with the const type.
673 pub fn new(map: RawMap) -> Self {
674 RawMapIter { map, iter: UPB_MAP_BEGIN }
678 /// - `self.map` must be valid, and remain valid while the return value is
680 pub unsafe fn next_unchecked(&mut self) -> Option<(upb_MessageValue, upb_MessageValue)> {
681 let mut key = MaybeUninit::uninit();
682 let mut value = MaybeUninit::uninit();
683 // SAFETY: the `map` is valid as promised by the caller
684 unsafe { upb_Map_Next(self.map, key.as_mut_ptr(), value.as_mut_ptr(), &mut self.iter) }
685 // SAFETY: if upb_Map_Next returns true, then key and value have been populated.
686 .then(|| unsafe { (key.assume_init(), value.assume_init()) })
690 impl<Key, MessageType> ProxiedInMapValue<Key> for MessageType
692 Key: Proxied + UpbTypeConversions,
693 MessageType: Proxied + UpbTypeConversions,
695 fn map_new(_private: Private) -> Map<Key, Self> {
696 let arena = Arena::new();
700 <Key as UpbTypeConversions>::upb_type(),
701 <Self as UpbTypeConversions>::upb_type(),
705 Map::from_inner(Private, InnerMap::new(raw, arena))
708 unsafe fn map_free(_private: Private, _map: &mut Map<Key, Self>) {
709 // No-op: the memory will be dropped by the arena.
712 fn map_clear(mut map: MapMut<Key, Self>) {
714 upb_Map_Clear(map.as_raw(Private));
718 fn map_len(map: MapView<Key, Self>) -> usize {
719 unsafe { upb_Map_Size(map.as_raw(Private)) }
723 mut map: MapMut<Key, Self>,
725 value: impl IntoProxied<Self>,
727 let arena = map.inner(Private).raw_arena();
729 upb_Map_InsertAndReturnIfInserted(
731 <Key as UpbTypeConversions>::to_message_value(key),
732 <Self as UpbTypeConversions>::into_message_value_fuse_if_required(
734 value.into_proxied(Private),
741 fn map_get<'a>(map: MapView<'a, Key, Self>, key: View<'_, Key>) -> Option<View<'a, Self>> {
742 let mut val = MaybeUninit::uninit();
746 <Key as UpbTypeConversions>::to_message_value(key),
753 Some(unsafe { <Self as UpbTypeConversions>::from_message_value(val.assume_init()) })
756 fn map_remove(mut map: MapMut<Key, Self>, key: View<'_, Key>) -> bool {
760 <Key as UpbTypeConversions>::to_message_value(key),
765 fn map_iter(map: MapView<Key, Self>) -> MapIter<Key, Self> {
766 // SAFETY: MapView<'_,..>> guarantees its RawMap outlives '_.
767 unsafe { MapIter::from_raw(Private, RawMapIter::new(map.as_raw(Private))) }
770 fn map_iter_next<'a>(
771 iter: &mut MapIter<'a, Key, Self>,
772 ) -> Option<(View<'a, Key>, View<'a, Self>)> {
773 // SAFETY: MapIter<'a, ..> guarantees its RawMapIter outlives 'a.
774 unsafe { iter.as_raw_mut(Private).next_unchecked() }
775 // SAFETY: MapIter<K, V> returns key and values message values
776 // with the variants for K and V active.
777 .map(|(k, v)| unsafe {
779 <Key as UpbTypeConversions>::from_message_value(k),
780 <Self as UpbTypeConversions>::from_message_value(v),
786 /// `upb_Map_Insert`, but returns a `bool` for whether insert occurred.
788 /// Returns `true` if the entry was newly inserted.
791 /// Panics if the arena is out of memory.
794 /// The same as `upb_Map_Insert`:
795 /// - `map` must be a valid map.
796 /// - The `arena` must be valid and outlive the map.
797 /// - The inserted value must outlive the map.
798 #[allow(non_snake_case)]
799 pub unsafe fn upb_Map_InsertAndReturnIfInserted(
801 key: upb_MessageValue,
802 value: upb_MessageValue,
805 match unsafe { upb_Map_Insert(map, key, value, arena) } {
806 upb::MapInsertStatus::Inserted => true,
807 upb::MapInsertStatus::Replaced => false,
808 upb::MapInsertStatus::OutOfMemory => panic!("map arena is out of memory"),