Skip to main content

google_protobuf/
codegen_traits.rs

1// Protocol Buffers - Google's data interchange format
2// Copyright 2024 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//! Traits that are implemented by codegen types.
9
10#[cfg(not(lite_runtime))]
11use crate::__internal::runtime::KernelWithReflection;
12use crate::__internal::runtime::{
13    KernelMessage, KernelMessageMut, KernelMessageView, MessageMutInterop, MessageViewInterop,
14    OwnedMessageInterop,
15};
16use crate::__internal::SealedInternal;
17use crate::AsMut;
18use crate::AsView;
19use crate::IntoMut;
20use crate::IntoView;
21use crate::MutProxied;
22use crate::{ProtoBytes, ProtoString};
23use create::Parse;
24use read::Serialize;
25use std::fmt::Debug;
26use write::{Clear, ClearAndParse, CopyFrom, MergeFrom, TakeFrom};
27
28/// Used to constrain Messages to only be EntityType<Tag=MessageTag>
29pub(crate) trait MessageTypeHelper<T> {}
30impl<T: EntityType<Tag = entity_tag::MessageTag>> MessageTypeHelper<entity_tag::MessageTag> for T {}
31
32/// A trait implemented only by Message types.
33pub trait MessageType {}
34impl<T> MessageType for T where T: EntityType + MessageTypeHelper<T::Tag> {}
35
36/// A trait that all generated owned message types implement.
37#[diagnostic::on_unimplemented(
38    message = "the trait `Message` is not implemented for `{Self}`",
39    note = "if `{Self}` is a view or a mut, consider calling `.to_owned()` to get an owned message"
40)]
41pub trait Message: SealedInternal
42  + EntityType<Tag = entity_tag::MessageTag>
43  + MessageType
44  + MutProxied
45  + for<'a> MutProxied<View<'a> = Self::MessageView<'a>, Mut<'a> = Self::MessageMut<'a>>
46  // Create traits:
47  + Parse + Default
48  // Read traits:
49  + Debug + Serialize
50  // Write traits:
51  + Clear + ClearAndParse + TakeFrom + CopyFrom + MergeFrom
52  // Thread safety:
53  + Send + Sync
54  // Copy/Clone:
55  + Clone
56  // C++ interop:
57  + OwnedMessageInterop
58  // Kernel-specific traits
59  + KernelMessage
60{
61    /// The same type as `<Self as Proxied>::View`. This is defined as a second redundant associated
62    /// type and should not be necessary, but the having this available is a hacky workaround
63    /// that can appease the trait solver in some cases.
64    type MessageView<'msg>: MessageView<'msg, Message = Self>;
65
66    /// The same type as `<Self as Proxied>::Mut`. This is defined as a second redundant associated
67    /// type and should not be necessary, but the having this available is a hacky workaround
68    /// that can appease the trait solver in some cases.
69    type MessageMut<'msg>: MessageMut<'msg, Message = Self>;
70}
71
72/// A marker trait for messages that support reflection.
73#[cfg(not(lite_runtime))]
74pub trait WithReflection: Message + KernelWithReflection {}
75
76/// A trait that all generated message views implement.
77#[diagnostic::on_unimplemented(
78    message = "the trait `MessageView` is not implemented for `{Self}`",
79    note = "if `{Self}` is an owned message or a mut, consider calling `.as_view()`, or changing \
80            the fn to accept `impl AsView<Proxied = T>`"
81)]
82pub trait MessageView<'msg>: SealedInternal
83    + AsView<Proxied = Self::Message>
84    + IntoView<'msg, Proxied = Self::Message>
85    + EntityType<Tag = entity_tag::ViewProxyTag>
86    // Read traits:
87    + Debug + Serialize + Default
88    // Thread safety:
89    + Send + Sync
90    // Copy/Clone:
91    + Copy + Clone
92    // C++ interop:
93    + MessageViewInterop<'msg>
94    + KernelMessageView<'msg, KMessage = Self::Message>
95{
96    #[doc(hidden)]
97    type Message: Message;
98}
99
100/// A trait that all generated message muts implement.
101#[diagnostic::on_unimplemented(
102    message = "the trait `MessageMut` is not implemented for `{Self}`",
103    note = "if `{Self}` is an owned message, consider calling `.as_mut()`, or changing the fn to \
104            accept `impl AsMut<MutProxied = T>`"
105)]
106pub trait MessageMut<'msg>: SealedInternal
107    + AsView<Proxied = Self::Message>
108    + IntoView<'msg, Proxied = Self::Message>
109    + AsMut<MutProxied = Self::Message>
110    + IntoMut<'msg, MutProxied = Self::Message>
111    // Read traits:
112    + Debug + Serialize
113    // Write traits:
114    + Clear + ClearAndParse + TakeFrom + CopyFrom + MergeFrom
115    // Thread safety:
116    + Send + Sync
117    // Copy/Clone:
118    // (Neither)
119    // C++ interop:
120    + MessageMutInterop<'msg>
121    // Kernel-specific traits (including user-visible interop traits):
122    + KernelMessageMut<'msg, KMessage = Self::Message>
123{
124    #[doc(hidden)]
125    type Message: Message;
126}
127
128/// This trait allows us to associate a tag with each type of protobuf entity. The tag indicates
129/// whether the entity is a message, enum, primitive, view proxy, or mut proxy. The main purpose of
130/// this is to allow us to have separate blanket implementations of various traits for messages
131/// and enums.
132pub trait EntityType {
133    type Tag;
134}
135
136pub mod entity_tag {
137    pub struct MessageTag;
138    pub struct EnumTag;
139    pub struct PrimitiveTag;
140    pub struct ViewProxyTag;
141    pub struct MutProxyTag;
142    pub struct RepeatedTag;
143}
144
145macro_rules! impl_entity_type_for_primitives {
146    ($($t:ty,)*) => {
147        $(
148            impl EntityType for $t {
149                type Tag = entity_tag::PrimitiveTag;
150            }
151        )*
152    };
153}
154
155impl_entity_type_for_primitives!(f32, f64, i32, u32, i64, u64, bool, ProtoBytes, ProtoString,);
156
157/// Operations related to constructing a message. Only owned messages implement
158/// these traits.
159pub(crate) mod create {
160    use super::SealedInternal;
161    pub trait Parse: SealedInternal + Sized {
162        fn parse(serialized: &[u8]) -> Result<Self, crate::ParseError>;
163        fn parse_dont_enforce_required(serialized: &[u8]) -> Result<Self, crate::ParseError>;
164    }
165
166    impl<T> Parse for T
167    where
168        Self: Default + crate::ClearAndParse,
169    {
170        fn parse(serialized: &[u8]) -> Result<Self, crate::ParseError> {
171            let mut msg = Self::default();
172            crate::ClearAndParse::clear_and_parse(&mut msg, serialized).map(|_| msg)
173        }
174
175        fn parse_dont_enforce_required(serialized: &[u8]) -> Result<Self, crate::ParseError> {
176            let mut msg = Self::default();
177            crate::ClearAndParse::clear_and_parse_dont_enforce_required(&mut msg, serialized)
178                .map(|_| msg)
179        }
180    }
181}
182
183/// Operations related to reading some aspect of a message (methods that would
184/// have a `&self` receiver on an owned message). Owned messages, views, and
185/// muts all implement these traits.
186pub(crate) mod read {
187    use super::SealedInternal;
188
189    pub trait Serialize: SealedInternal {
190        fn serialize(&self) -> Result<Vec<u8>, crate::SerializeError>;
191        fn serialized_len(&self) -> usize;
192    }
193}
194
195/// Operations related to mutating a message (methods that would have a `&mut
196/// self` receiver on an owned message). Owned messages and muts implement these
197/// traits.
198pub(crate) mod write {
199    use super::SealedInternal;
200    use crate::{AsMut, AsView};
201
202    pub trait Clear: SealedInternal {
203        fn clear(&mut self);
204    }
205
206    pub trait ClearAndParse: SealedInternal {
207        fn clear_and_parse(&mut self, data: &[u8]) -> Result<(), crate::ParseError>;
208        fn clear_and_parse_dont_enforce_required(
209            &mut self,
210            data: &[u8],
211        ) -> Result<(), crate::ParseError>;
212    }
213
214    /// Copies the contents from `src` into `self`.
215    ///
216    /// This is a copy in the sense that `src` message is not mutated and `self` will have
217    /// the same state as `src` after this call; it may not be a bitwise copy.
218    pub trait CopyFrom: AsView + SealedInternal {
219        fn copy_from(&mut self, src: impl AsView<Proxied = Self::Proxied>);
220    }
221
222    /// Moves the contents from `src` into `self`.
223    ///
224    /// Any previous state of `self` is discarded, and if `src` is still observable then it is
225    /// guaranteed to be in its default state after this call. If `src` is a field on a parent
226    /// message, the presence of that field will be unaffected.
227    pub trait TakeFrom: AsView + SealedInternal {
228        fn take_from(&mut self, src: impl AsMut<MutProxied = Self::Proxied>);
229    }
230
231    pub trait MergeFrom: AsView + SealedInternal {
232        fn merge_from(&mut self, src: impl AsView<Proxied = Self::Proxied>);
233    }
234}