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