Skip to main content

google_protobuf/upb_kernel/
message.rs

1use super::*;
2
3#[derive(Debug)]
4#[doc(hidden)]
5pub struct OwnedMessageInner<T> {
6    ptr: MessagePtr<T>,
7    arena: Arena,
8}
9
10impl<T: Message> Default for OwnedMessageInner<T> {
11    fn default() -> Self {
12        Self::new()
13    }
14}
15
16impl<T: Message> OwnedMessageInner<T> {
17    pub fn new() -> Self {
18        let arena = Arena::new();
19        let ptr = MessagePtr::new(&arena).expect("alloc should never fail");
20        Self { ptr, arena }
21    }
22
23    /// # Safety
24    /// - The underlying pointer must of type `T` and be allocated on `arena`.
25    pub unsafe fn wrap_raw(raw: RawMessage, arena: Arena) -> Self {
26        // SAFETY:
27        // - Caller guaranteed `raw` is valid and of type `T`
28        let ptr = unsafe { MessagePtr::wrap(raw) };
29        OwnedMessageInner { ptr, arena }
30    }
31
32    pub fn ptr_mut(&mut self) -> MessagePtr<T> {
33        self.ptr
34    }
35
36    pub fn ptr(&self) -> MessagePtr<T> {
37        self.ptr
38    }
39
40    pub fn raw(&self) -> RawMessage {
41        self.ptr.raw()
42    }
43
44    #[allow(clippy::needless_pass_by_ref_mut)] // Sound access requires mutable access.
45    pub fn arena(&mut self) -> &Arena {
46        &self.arena
47    }
48}
49
50/// Mutators that point to their original message use this to do so.
51///
52/// Since UPB expects runtimes to manage their own arenas, this needs to have
53/// access to an `Arena`.
54///
55/// This has two possible designs:
56/// - Store two pointers here, `RawMessage` and `&'msg Arena`. This doesn't place any restriction on
57///   the layout of generated messages and their mutators. This makes a vtable-based mutator three
58///   pointers, which can no longer be returned in registers on most platforms.
59/// - Store one pointer here, `&'msg OwnedMessageInner`, where `OwnedMessageInner` stores a
60///   `RawMessage` and an `Arena`. This would require all generated messages to store
61///   `OwnedMessageInner`, and since their mutators need to be able to generate `BytesMut`, would
62///   also require `BytesMut` to store a `&'msg OwnedMessageInner` since they can't store an owned
63///   `Arena`.
64///
65/// The following invariants must be upheld:
66///
67/// - No concurrent mutation for any two fields in a message: this means mutators cannot be `Send`
68///   but are `Sync`.
69/// - If there are multiple accessible `Mut` to a single message at a time, they must be different
70///   fields, and not be in the same oneof. As such, a `Mut` cannot be `Clone` but *can* reborrow
71///   itself with `.as_mut()`, which converts `&'b mut Mut<'a, T>` to `Mut<'b, T>`.
72#[derive(Debug)]
73#[doc(hidden)]
74pub struct MessageMutInner<'msg, T> {
75    pub(crate) ptr: MessagePtr<T>,
76    pub(crate) arena: &'msg Arena,
77}
78
79impl<'msg, T: Message> MessageMutInner<'msg, T> {
80    /// # Safety
81    /// - `msg` must be a valid `RawMessage`
82    /// - `arena` must hold the memory for `msg`
83    pub unsafe fn wrap_raw(raw: RawMessage, arena: &'msg Arena) -> Self {
84        // SAFETY:
85        // - Caller guaranteed `raw` is valid and of type `T`
86        let ptr = unsafe { MessagePtr::wrap(raw) };
87        MessageMutInner { ptr, arena }
88    }
89
90    #[allow(clippy::needless_pass_by_ref_mut)] // Sound construction requires mutable access.
91    pub fn mut_of_owned(msg: &'msg mut OwnedMessageInner<T>) -> Self {
92        MessageMutInner { ptr: msg.ptr, arena: &msg.arena }
93    }
94
95    pub fn from_parent<ParentT>(
96        parent_msg: MessageMutInner<'msg, ParentT>,
97        ptr: MessagePtr<T>,
98    ) -> Self {
99        MessageMutInner { ptr, arena: parent_msg.arena }
100    }
101
102    pub fn ptr_mut(&mut self) -> MessagePtr<T> {
103        self.ptr
104    }
105
106    pub fn ptr(&self) -> MessagePtr<T> {
107        self.ptr
108    }
109
110    pub fn raw(&self) -> RawMessage {
111        self.ptr.raw()
112    }
113
114    pub fn arena(&self) -> &Arena {
115        self.arena
116    }
117
118    pub fn as_view(&self) -> MessageViewInner<'msg, T> {
119        MessageViewInner { ptr: self.ptr, _phantom: PhantomData }
120    }
121
122    pub fn reborrow<'shorter>(&mut self) -> MessageMutInner<'shorter, T>
123    where
124        'msg: 'shorter,
125    {
126        Self { ptr: self.ptr, arena: self.arena }
127    }
128}
129
130#[derive(Debug)]
131#[doc(hidden)]
132pub struct MessageViewInner<'msg, T> {
133    ptr: MessagePtr<T>,
134    _phantom: PhantomData<&'msg ()>,
135}
136
137impl<'msg, T: Message> Clone for MessageViewInner<'msg, T> {
138    fn clone(&self) -> Self {
139        *self
140    }
141}
142impl<'msg, T: Message> Copy for MessageViewInner<'msg, T> {}
143
144impl<'msg, T: Message> MessageViewInner<'msg, T> {
145    /// # Safety
146    /// - The underlying pointer must live as long as `'msg`.
147    pub unsafe fn wrap(ptr: MessagePtr<T>) -> Self {
148        // SAFETY:
149        // - Caller guaranteed `raw` is valid
150        MessageViewInner { ptr, _phantom: PhantomData }
151    }
152
153    /// # Safety
154    /// - The underlying pointer must of type `T` and live as long as `'msg`.
155    pub unsafe fn wrap_raw(raw: RawMessage) -> Self {
156        // SAFETY:
157        // - Caller guaranteed `raw` is valid and of type `T`
158        let ptr = unsafe { MessagePtr::wrap(raw) };
159        MessageViewInner { ptr, _phantom: PhantomData }
160    }
161
162    #[allow(clippy::needless_pass_by_ref_mut)] // Sound construction requires mutable access.
163    pub fn view_of_owned(owned: &'msg OwnedMessageInner<T>) -> Self {
164        MessageViewInner { ptr: owned.ptr, _phantom: PhantomData }
165    }
166
167    #[allow(clippy::needless_pass_by_ref_mut)] // Sound construction requires mutable access.
168    pub fn view_of_mut(msg_mut: MessageMutInner<'msg, T>) -> Self {
169        MessageViewInner { ptr: msg_mut.ptr, _phantom: PhantomData }
170    }
171
172    pub fn ptr(&self) -> MessagePtr<T> {
173        self.ptr
174    }
175
176    pub fn raw(&self) -> RawMessage {
177        self.ptr.raw()
178    }
179}
180
181/// The scratch size of 64 KiB matches the maximum supported size that a
182/// upb_Message can possibly be.
183const UPB_SCRATCH_SPACE_BYTES: usize = 65_536;
184
185/// Holds a zero-initialized block of memory for use by upb.
186///
187/// By default, if a message is not set in cpp, a default message is created.
188/// upb departs from this and returns a null ptr. However, since contiguous
189/// chunks of memory filled with zeroes are legit messages from upb's point of
190/// view, we can allocate a large block and refer to that when dealing
191/// with readonly access.
192#[repr(C, align(8))] // align to UPB_MALLOC_ALIGN = 8
193pub(crate) struct ScratchSpace([u8; UPB_SCRATCH_SPACE_BYTES]);
194impl ScratchSpace {
195    pub fn zeroed_block() -> RawMessage {
196        static ZEROED_BLOCK: ScratchSpace = ScratchSpace([0; UPB_SCRATCH_SPACE_BYTES]);
197        NonNull::from(&ZEROED_BLOCK).cast()
198    }
199}
200
201impl<T: Message> Default for MessageViewInner<'static, T> {
202    fn default() -> Self {
203        unsafe {
204            // SAFETY:
205            // - `ScratchSpace::zeroed_block()` is a valid const `RawMessage` for all possible T.
206            // - `ScratchSpace::zeroed_block()' has 'static lifetime.
207            Self::wrap_raw(ScratchSpace::zeroed_block())
208        }
209    }
210}
211
212/// Internal-only trait to support blanket impls that need const access to raw messages
213/// on codegen. Should never be used by application code.
214#[doc(hidden)]
215pub unsafe trait UpbGetMessagePtr: SealedInternal {
216    type Msg: AssociatedMiniTable + Message;
217
218    fn get_ptr(&self, _private: Private) -> MessagePtr<Self::Msg>;
219}
220
221/// Internal-only trait to support blanket impls that need mutable access to raw messages
222/// on codegen. Must not be implemented on View proxies. Should never be used by application code.
223#[doc(hidden)]
224pub unsafe trait UpbGetMessagePtrMut: SealedInternal {
225    type Msg: AssociatedMiniTable + Message;
226
227    fn get_ptr_mut(&mut self, _private: Private) -> MessagePtr<Self::Msg>;
228}
229
230/// Internal-only trait to support blanket impls that need const access to raw messages
231/// on codegen. Should never be used by application code.
232#[doc(hidden)]
233pub unsafe trait UpbGetArena: SealedInternal {
234    fn get_arena(&mut self, _private: Private) -> &Arena;
235}
236
237pub trait KernelMessage:
238    AssociatedMiniTable + UpbGetArena + UpbGetMessagePtr + UpbGetMessagePtrMut + OwnedMessageInterop
239{
240}
241
242impl<T> KernelMessage for T where
243    T: AssociatedMiniTable
244        + UpbGetArena
245        + UpbGetMessagePtr
246        + UpbGetMessagePtrMut
247        + OwnedMessageInterop
248{
249}
250
251pub trait KernelMessageView<'msg>:
252    UpbGetMessagePtr + MessageViewInterop<'msg> + From<MessageViewInner<'msg, Self::KMessage>>
253{
254    type KMessage;
255}
256
257impl<'msg, T> KernelMessageView<'msg> for T
258where
259    T: UpbGetMessagePtr + MessageViewInterop<'msg> + From<MessageViewInner<'msg, T::Msg>>,
260{
261    type KMessage = T::Msg;
262}
263
264pub trait KernelMessageMut<'msg>:
265    UpbGetMessagePtr
266    + UpbGetMessagePtrMut
267    + UpbGetArena
268    + MessageMutInterop<'msg>
269    + From<MessageMutInner<'msg, Self::KMessage>>
270{
271    type KMessage;
272}
273impl<'msg, T> KernelMessageMut<'msg> for T
274where
275    T: UpbGetMessagePtr
276        + UpbGetMessagePtrMut
277        + UpbGetArena
278        + MessageMutInterop<'msg>
279        + From<MessageMutInner<'msg, <T as UpbGetMessagePtr>::Msg>>,
280{
281    type KMessage = <T as UpbGetMessagePtr>::Msg;
282}
283
284/// Message equality definition which may have both false-negatives and false-positives in the face
285/// of unknown fields.
286///
287/// This behavior is deliberately held back from being exposed as an `Eq` trait for messages. The
288/// reason is that it is impossible to properly compare unknown fields for message equality, since
289/// without the schema you cannot know how to interpret the wire format properly for comparison.
290///
291/// False negative cases (where message_eq will return false on unknown fields where it
292/// would return true if the fields were known) are common and will occur in production: for
293/// example, as map and repeated fields look exactly the same, map field order is unstable, the
294/// comparison cannot know to treat it as unordered and will return false when it was the same
295/// map but in a different order.
296///
297/// False positives cases (where message_eq will return true on unknown fields where it would have
298/// return false if the fields were known) are possible but uncommon in practice. One example
299/// of this direction can occur if two fields are defined in the same oneof and both are present on
300/// the wire but in opposite order, without the schema these messages appear equal but with the
301/// schema they are not-equal.
302///
303/// This lossy behavior in the face of unknown fields is especially problematic in the face of
304/// extensions and other treeshaking behaviors where a given field being known or not to binary is a
305/// spooky-action-at-a-distance behavior, which may lead to surprising changes in outcome in
306/// equality tests based on changes made arbitrarily distant from the code performing the equality
307/// check.
308///
309/// Broadly this is recommended for use in tests (where unknown field behaviors are rarely a
310/// concern), and in limited/targeted cases where the lossy behavior in the face of unknown fields
311/// behavior is unlikely to be a problem.
312pub fn message_eq<T>(a: &T, b: &T) -> bool
313where
314    T: AsView + Debug,
315    <T as AsView>::Proxied: AssociatedMiniTable,
316    for<'a> View<'a, <T as AsView>::Proxied>: UpbGetMessagePtr,
317{
318    unsafe {
319        upb_Message_IsEqual(
320            a.as_view().get_ptr(Private).raw(),
321            b.as_view().get_ptr(Private).raw(),
322            <T as AsView>::Proxied::mini_table(),
323            0,
324        )
325    }
326}
327
328/// Message equality definition for checking partial equality of two messages. Fields that are not
329/// set in the expected message are ignored when comparing against the actual message.
330///
331/// This should only be used for testing purposes.
332pub fn message_partially_eq<T>(actual: &T, expected: &T) -> bool
333where
334    T: AsView + Debug,
335    <T as AsView>::Proxied: AssociatedMiniTable,
336    for<'a> View<'a, <T as AsView>::Proxied>: UpbGetMessagePtr,
337{
338    const UPB_COMPARE_OPTION_PARTIAL: i32 = 1 << 1;
339
340    // Safety: we provide valid pointers and the C code does not retain them.
341    unsafe {
342        upb_Message_IsEqual(
343            actual.as_view().get_ptr(Private).raw(),
344            expected.as_view().get_ptr(Private).raw(),
345            <T as AsView>::Proxied::mini_table(),
346            UPB_COMPARE_OPTION_PARTIAL,
347        )
348    }
349}
350
351impl<T> MatcherEq for T
352where
353    Self: AsView + Debug,
354    <Self as AsView>::Proxied: AssociatedMiniTable,
355    for<'a> View<'a, <Self as AsView>::Proxied>: UpbGetMessagePtr,
356{
357    fn matches(&self, o: &Self) -> bool {
358        message_eq(self, o)
359    }
360
361    fn matches_partially(&self, expected: &Self) -> bool {
362        message_partially_eq(self, expected)
363    }
364}
365
366impl<T: UpbGetMessagePtrMut> Clear for T {
367    fn clear(&mut self) {
368        unsafe { self.get_ptr_mut(Private).clear() }
369    }
370}
371
372fn clear_and_parse_helper<T>(
373    msg: &mut T,
374    data: &[u8],
375    decode_options: i32,
376) -> Result<(), ParseError>
377where
378    T: UpbGetMessagePtrMut + UpbGetArena,
379{
380    Clear::clear(msg);
381    // SAFETY:
382    // - `msg` is a valid mutable message.
383    // - `mini_table` is the one associated with `msg`
384    // - `msg.arena().raw()` is held for the same lifetime as `msg`.
385    unsafe {
386        upb::wire::decode_with_options(
387            data,
388            msg.get_ptr_mut(Private),
389            generated_extension_registry().as_ptr(),
390            msg.get_arena(Private),
391            decode_options,
392        )
393    }
394    .map(|_| ())
395    .map_err(|_| {
396        Clear::clear(msg);
397        ParseError
398    })
399}
400
401impl<T> ClearAndParse for T
402where
403    Self: UpbGetMessagePtrMut + UpbGetArena,
404{
405    fn clear_and_parse(&mut self, data: &[u8]) -> Result<(), ParseError> {
406        clear_and_parse_helper(self, data, upb::wire::decode_options::CHECK_REQUIRED)
407    }
408
409    fn clear_and_parse_dont_enforce_required(&mut self, data: &[u8]) -> Result<(), ParseError> {
410        clear_and_parse_helper(self, data, 0)
411    }
412}
413
414impl<T> Serialize for T
415where
416    Self: UpbGetMessagePtr,
417{
418    fn serialize(&self) -> Result<Vec<u8>, SerializeError> {
419        //~ TODO: This discards the info we have about the reason
420        //~ of the failure, we should try to keep it instead.
421        upb::wire::encode(self.get_ptr(Private)).map_err(|_| SerializeError)
422    }
423
424    fn serialized_len(&self) -> usize {
425        upb::wire::byte_size(self.get_ptr(Private))
426    }
427}
428
429impl<T> TakeFrom for T
430where
431    Self: CopyFrom + AsMut,
432    for<'a> Mut<'a, <Self as AsMut>::MutProxied>: Clear,
433{
434    fn take_from(&mut self, mut src: impl AsMut<MutProxied = Self::Proxied>) {
435        let mut src = src.as_mut();
436        // TODO: b/393559271 - Optimize this copy out.
437        CopyFrom::copy_from(self, AsView::as_view(&src));
438        Clear::clear(&mut src);
439    }
440}
441
442impl<T> CopyFrom for T
443where
444    Self: AsView + UpbGetArena + UpbGetMessagePtr,
445    Self::Proxied: AssociatedMiniTable,
446    for<'a> View<'a, Self::Proxied>: UpbGetMessagePtr,
447{
448    fn copy_from(&mut self, src: impl AsView<Proxied = Self::Proxied>) {
449        // SAFETY: self and src are both valid `T`s associated with
450        // `Self::mini_table()`.
451        unsafe {
452            assert!(upb_Message_DeepCopy(
453                self.get_ptr(Private).raw(),
454                src.as_view().get_ptr(Private).raw(),
455                <Self::Proxied as AssociatedMiniTable>::mini_table(),
456                self.get_arena(Private).raw()
457            ));
458        }
459    }
460}
461
462impl<T> MergeFrom for T
463where
464    Self: AsView + UpbGetArena + UpbGetMessagePtr,
465    Self::Proxied: AssociatedMiniTable,
466    for<'a> View<'a, Self::Proxied>: UpbGetMessagePtr,
467{
468    fn merge_from(&mut self, src: impl AsView<Proxied = Self::Proxied>) {
469        // SAFETY: self and src are both valid `T`s.
470        unsafe {
471            assert!(upb_Message_MergeFrom(
472                self.get_ptr(Private).raw(),
473                src.as_view().get_ptr(Private).raw(),
474                <Self::Proxied as AssociatedMiniTable>::mini_table(),
475                generated_extension_registry().as_ptr(),
476                self.get_arena(Private).raw()
477            ));
478        }
479    }
480}
481
482/// # Safety
483/// - The field at `index` must be a message field of type `T`.
484pub unsafe fn message_set_sub_message<
485    'msg,
486    P: Message + AssociatedMiniTable,
487    T: Message + UpbGetMessagePtrMut + UpbGetArena,
488>(
489    parent: MessageMutInner<'msg, P>,
490    index: u32,
491    val: impl IntoProxied<T>,
492) {
493    // The message and arena are dropped after the setter. The
494    // memory remains allocated as we fuse the arena with the
495    // parent message's arena.
496    let mut child = val.into_proxied(Private);
497    parent.arena.fuse(child.get_arena(Private));
498
499    let child_ptr = child.get_ptr_mut(Private);
500    unsafe {
501        // SAFETY:
502        // - `parent.ptr` is valid as it comes from a `MessageMutInner`.
503        // - The caller guarantees that `index` refers to a valid message field of type `T`.
504        // - The child's arena has been fused into the parent's arena above.
505        parent.ptr.set_base_field_message_at_index(index, child_ptr);
506    }
507}
508
509/// # Safety
510/// - The field at `index` must be a string field.
511pub unsafe fn message_set_string_field<'msg, P: Message + AssociatedMiniTable>(
512    parent: MessageMutInner<'msg, P>,
513    index: u32,
514    val: impl IntoProxied<ProtoString>,
515) {
516    let s = val.into_proxied(Private);
517    let (view, arena) = s.into_inner(Private).into_raw_parts();
518    parent.arena().fuse(&arena);
519    unsafe {
520        // SAFETY:
521        // - `parent.ptr` is valid as it comes from a `MessageMutInner`.
522        // - The caller guarantees that `index` refers to a valid string field.
523        // - The string's arena has been fused into the parent's arena above.
524        parent.ptr.set_base_field_string_at_index(index, view);
525    }
526}
527
528/// # Safety
529/// - The field at `index` must be a bytes field.
530pub unsafe fn message_set_bytes_field<'msg, P: Message + AssociatedMiniTable>(
531    parent: MessageMutInner<'msg, P>,
532    index: u32,
533    val: impl IntoProxied<ProtoBytes>,
534) {
535    let s = val.into_proxied(Private);
536    let (view, arena) = s.into_inner(Private).into_raw_parts();
537    parent.arena().fuse(&arena);
538    unsafe {
539        // SAFETY:
540        // - `parent.ptr` is valid as it comes from a `MessageMutInner`.
541        // - The caller guarantees that `index` refers to a valid bytes field.
542        // - The string's arena has been fused into the parent's arena above.
543        parent.ptr.set_base_field_string_at_index(index, view);
544    }
545}
546
547/// # Safety
548/// - The field at `index` must be a repeated field of `T`.
549pub unsafe fn message_set_repeated_field<'msg, P: Message + AssociatedMiniTable, T: Singular>(
550    parent: MessageMutInner<'msg, P>,
551    index: u32,
552    val: impl IntoProxied<Repeated<T>>,
553) {
554    let child = val.into_proxied(Private);
555    let inner = child.inner(Private);
556    parent.arena().fuse(inner.arena());
557    unsafe {
558        // SAFETY:
559        // - `parent.ptr` is valid as it comes from a `MessageMutInner`.
560        // - The caller guarantees that `index` refers to a valid repeated field.
561        // - The repeated field's arena has been fused into the parent's arena above.
562        parent.ptr.set_array_at_index(index, inner.raw());
563    }
564}
565
566/// # Safety
567/// - The field at `index` must be a map field with key type `K` and value type `V`.
568pub unsafe fn message_set_map_field<
569    'msg,
570    P: Message + AssociatedMiniTable,
571    K: MapKey,
572    V: MapValue,
573>(
574    parent: MessageMutInner<'msg, P>,
575    index: u32,
576    val: impl IntoProxied<Map<K, V>>,
577) {
578    let mut child = val.into_proxied(Private);
579    let child_as_mut = child.as_mut();
580    let mut inner = child_as_mut.inner(Private);
581
582    parent.arena().fuse(inner.arena());
583    unsafe {
584        // SAFETY:
585        // - `parent.ptr` is valid as it comes from a `MessageMutInner`.
586        // - The caller guarantees that `index` refers to a valid map field.
587        // - The map's arena has been fused into the parent's arena above.
588        parent.ptr.set_map_at_index(index, inner.as_raw());
589    }
590}