Skip to main content

google_protobuf/upb_kernel/
conversions.rs

1use super::*;
2use crate::Enum;
3
4pub trait UpbTypeConversions<Tag>: Proxied {
5    fn upb_type() -> upb::CType;
6
7    fn to_message_value(val: View<'_, Self>) -> upb_MessageValue;
8
9    /// # Safety
10    /// - `raw_arena` must point to a valid upb arena.
11    unsafe fn into_message_value_fuse_if_required(
12        raw_arena: RawArena,
13        val: Self,
14    ) -> upb_MessageValue;
15
16    /// # Safety
17    /// - `msg_val` must be the correct variant for `Self`.
18    /// - `msg_val` pointers must point to memory valid for `'msg` lifetime.
19    /// - If `Self` is a closed enum, then `msg_val.int32_val` must be a valid enum entry.
20    unsafe fn from_message_value<'msg>(msg_val: upb_MessageValue) -> View<'msg, Self>;
21
22    /// # Safety
23    /// - `raw` must be the correct variant for `Self`.
24    /// - `raw` pointers must point to memory valid for `'msg` lifetime.
25    #[allow(unused_variables)]
26    unsafe fn from_message_mut<'msg>(raw: RawMessage, arena: &'msg Arena) -> Mut<'msg, Self>
27    where
28        Self: Message,
29    {
30        panic!("mut_from_message_value is only implemented for messages.")
31    }
32
33    /// # Safety
34    /// - `src` must be a valid array of `Self`.
35    /// - `dest` must be a valid mutable array of `Self`.
36    /// - `arena` must point to an arena that will outlive `dest`.
37    unsafe fn copy_repeated(src: RawArray, dest: RawArray, arena: RawArena);
38}
39
40impl<T> UpbTypeConversions<MessageTag> for T
41where
42    Self: Message,
43    for<'a> View<'a, Self>: MessageViewInterop<'a>,
44    for<'a> Mut<'a, Self>: From<MessageMutInner<'a, Self>>,
45{
46    fn upb_type() -> CType {
47        CType::Message
48    }
49
50    fn to_message_value(val: View<'_, Self>) -> upb_MessageValue {
51        upb_MessageValue { msg_val: Some(val.get_ptr(Private).raw()) }
52    }
53
54    unsafe fn into_message_value_fuse_if_required(
55        raw_parent_arena: RawArena,
56        mut val: Self,
57    ) -> upb_MessageValue {
58        // SAFETY: The arena memory is not freed due to `ManuallyDrop`.
59        let parent_arena =
60            std::mem::ManuallyDrop::new(unsafe { Arena::from_raw(raw_parent_arena) });
61
62        parent_arena.fuse(val.get_arena(Private));
63        upb_MessageValue { msg_val: Some(val.get_ptr(Private).raw()) }
64    }
65
66    unsafe fn from_message_value<'msg>(msg: upb_MessageValue) -> View<'msg, Self> {
67        unsafe {
68            let raw = msg.msg_val.expect("expected present message value in map");
69            View::<Self>::__unstable_wrap_raw_message_unchecked_lifetime(
70                raw.as_ptr() as *const std::ffi::c_void
71            )
72        }
73    }
74
75    unsafe fn from_message_mut<'msg>(msg: RawMessage, arena: &'msg Arena) -> Mut<'msg, Self> {
76        unsafe { MessageMutInner::<'msg, Self>::wrap_raw(msg, arena).into() }
77    }
78
79    unsafe fn copy_repeated(src: RawArray, dest: RawArray, arena: RawArena) {
80        // SAFETY:
81        // - `src` is a valid `const upb_Array*`.
82        // - `dest` is a valid `upb_Array*`.
83        // - Elements of `src` and `dest` have minitable `Self::mini_table()`.
84        unsafe {
85            let size = upb_Array_Size(src);
86            if !upb_Array_Resize(dest, size, arena) {
87                panic!("upb_Array_Resize failed (alloc should be infallible)");
88            }
89            for i in 0..size {
90                let src_msg =
91                    upb_Array_Get(src, i).msg_val.expect("upb_Array* element should not be NULL");
92                // Avoid the use of `upb_Array_DeepClone` as it creates an
93                // entirely new `upb_Array*` at a new memory address.
94                let cloned_msg = upb_Message_DeepClone(src_msg, Self::mini_table(), arena)
95                    .expect("upb_Message_DeepClone failed (alloc should be infallible)");
96                upb_Array_Set(dest, i, upb_MessageValue { msg_val: Some(cloned_msg) });
97            }
98        }
99    }
100}
101
102impl<T> UpbTypeConversions<EnumTag> for T
103where
104    Self: Enum,
105{
106    fn upb_type() -> CType {
107        CType::Enum
108    }
109
110    fn to_message_value(val: View<'_, Self>) -> upb_MessageValue {
111        upb_MessageValue { int32_val: val.into() }
112    }
113
114    unsafe fn into_message_value_fuse_if_required(
115        _raw_parent_arena: RawArena,
116        val: Self,
117    ) -> upb_MessageValue {
118        upb_MessageValue { int32_val: val.into() }
119    }
120
121    unsafe fn from_message_value<'msg>(val: upb_MessageValue) -> View<'msg, Self> {
122        // SAFETY: The caller guarantees that `val` is the correct variant.
123        let result = Self::try_from(unsafe { val.int32_val });
124        std::debug_assert!(result.is_ok());
125        // SAFETY:
126        // - The caller guarantees that `val.int32_val` is valid for this enum.
127        unsafe { result.unwrap_unchecked() }
128    }
129
130    unsafe fn copy_repeated(src: RawArray, dest: RawArray, arena: RawArena) {
131        // SAFETY:
132        // - Enum arrays have the same representation as i32 arrays.
133        // - The caller guarantees that src and dest are enum arrays and that `arena` will outlive
134        //   `dest`.
135        unsafe {
136            <i32 as UpbTypeConversions<PrimitiveTag>>::copy_repeated(src, dest, arena);
137        }
138    }
139}
140
141macro_rules! impl_upb_type_conversions_for_scalars {
142    ($($t:ty, $ufield:ident, $upb_tag:expr, $zero_val:literal;)*) => {
143        $(
144            impl UpbTypeConversions<PrimitiveTag> for $t {
145                #[inline(always)]
146                fn upb_type() -> upb::CType {
147                    $upb_tag
148                }
149
150                #[inline(always)]
151                fn to_message_value(val: View<'_, $t>) -> upb_MessageValue {
152                    upb_MessageValue { $ufield: val }
153                }
154
155                #[inline(always)]
156                unsafe fn into_message_value_fuse_if_required(_: RawArena, val: $t) -> upb_MessageValue {
157                    <Self as UpbTypeConversions<PrimitiveTag>>::to_message_value(val)
158                }
159
160                #[inline(always)]
161                unsafe fn from_message_value<'msg>(msg: upb_MessageValue) -> View<'msg, $t> {
162                    unsafe { msg.$ufield }
163                }
164
165                #[inline(always)]
166                unsafe fn copy_repeated(src: RawArray, dest: RawArray, arena: RawArena) {
167                    // SAFETY:
168                    // - `upb_Array_Resize` is unsafe but assumed to be always sound to call.
169                    // - `copy_nonoverlapping` is unsafe but here we guarantee that both pointers
170                    //   are valid, the pointers are `#[repr(u8)]`, and the size is correct.
171                    unsafe {
172                        let len = upb_Array_Size(src);
173                        if (!upb_Array_Resize(dest, len, arena)) {
174                            panic!("upb_Array_Resize failed (alloc should be infallible)");
175                        }
176                        ptr::copy_nonoverlapping(
177                          upb_Array_DataPtr(src).cast::<u8>(),
178                          upb_Array_MutableDataPtr(dest).cast::<u8>(),
179                          size_of::<$t>() * len);
180                    }
181                }
182            }
183        )*
184    };
185}
186
187impl_upb_type_conversions_for_scalars!(
188    f32, float_val, upb::CType::Float, 0f32;
189    f64, double_val, upb::CType::Double, 0f64;
190    i32, int32_val, upb::CType::Int32, 0i32;
191    u32, uint32_val, upb::CType::UInt32, 0u32;
192    i64, int64_val, upb::CType::Int64, 0i64;
193    u64, uint64_val, upb::CType::UInt64, 0u64;
194    bool, bool_val, upb::CType::Bool, false;
195);
196
197impl UpbTypeConversions<PrimitiveTag> for ProtoBytes {
198    fn upb_type() -> upb::CType {
199        upb::CType::Bytes
200    }
201
202    fn to_message_value(val: View<'_, ProtoBytes>) -> upb_MessageValue {
203        upb_MessageValue { str_val: val.into() }
204    }
205
206    unsafe fn into_message_value_fuse_if_required(
207        raw_parent_arena: RawArena,
208        val: ProtoBytes,
209    ) -> upb_MessageValue {
210        // SAFETY: The arena memory is not freed due to `ManuallyDrop`.
211        let parent_arena = ManuallyDrop::new(unsafe { Arena::from_raw(raw_parent_arena) });
212
213        let (view, arena) = val.inner.into_raw_parts();
214        parent_arena.fuse(&arena);
215
216        upb_MessageValue { str_val: view }
217    }
218
219    unsafe fn from_message_value<'msg>(msg: upb_MessageValue) -> View<'msg, ProtoBytes> {
220        let _ = unsafe { msg.str_val.as_ref() };
221        // We actually need view of ProtoBytes, the original code had:
222        // unsafe { msg.str_val.as_ref() }
223        // Wait, ProtoBytes view is `&[u8]`. What was the actual code?
224        // Ah, it actually was: `unsafe { msg.str_val.as_ref() }`
225        // But the return type is `View<'msg, ProtoBytes>`. `View<ProtoBytes>` is `&[u8]`.
226        // Let's just return what `msg.str_val.as_ref()` returns, which is `&[u8]`.
227        unsafe { msg.str_val.as_ref() }
228    }
229
230    unsafe fn copy_repeated(src: RawArray, dest: RawArray, arena: RawArena) {
231        unsafe {
232            copy_repeated_bytes(src, dest, arena);
233        }
234    }
235}
236
237impl UpbTypeConversions<PrimitiveTag> for ProtoString {
238    fn upb_type() -> upb::CType {
239        upb::CType::String
240    }
241
242    fn to_message_value(val: View<'_, ProtoString>) -> upb_MessageValue {
243        upb_MessageValue { str_val: val.as_bytes().into() }
244    }
245
246    unsafe fn into_message_value_fuse_if_required(
247        raw_arena: RawArena,
248        val: ProtoString,
249    ) -> upb_MessageValue {
250        // SAFETY: `raw_arena` is valid as promised by the caller
251        unsafe {
252            <ProtoBytes as UpbTypeConversions<PrimitiveTag>>::into_message_value_fuse_if_required(
253                raw_arena,
254                val.into(),
255            )
256        }
257    }
258
259    unsafe fn from_message_value<'msg>(msg: upb_MessageValue) -> View<'msg, ProtoString> {
260        ProtoStr::from_utf8_unchecked(unsafe { msg.str_val.as_ref() })
261    }
262
263    unsafe fn copy_repeated(src: RawArray, dest: RawArray, arena: RawArena) {
264        unsafe {
265            copy_repeated_bytes(src, dest, arena);
266        }
267    }
268}
269
270/// # Safety
271/// - `src` must be a valid array of string or bytes.
272/// - `dest` must be a valid mutable array of the same type as `src`.
273/// - `arena` must point to an arena that will outlive `dest`.
274unsafe fn copy_repeated_bytes(src: RawArray, dest: RawArray, arena: RawArena) {
275    // SAFETY:
276    // - `upb_Array_Resize` is unsafe but assumed to be always sound to call.
277    // - `upb_Array` ensures its elements are never uninitialized memory.
278    // - The `DataPtr` and `MutableDataPtr` functions return pointers to spans
279    //   of memory that are valid for at least `len` elements of PtrAndLen.
280    // - `copy_nonoverlapping` is unsafe but here we guarantee that both pointers
281    //   are valid, the pointers are `#[repr(u8)]`, and the size is correct.
282    // - The bytes held within a valid array are valid.
283    unsafe {
284        let len = upb_Array_Size(src);
285        let arena = ManuallyDrop::new(Arena::from_raw(arena));
286        if !upb_Array_Resize(dest, len, arena.raw()) {
287            panic!("upb_Array_Resize failed (alloc should be infallible)");
288        }
289        let src_ptrs: &[PtrAndLen] = slice::from_raw_parts(upb_Array_DataPtr(src).cast(), len);
290        let dest_ptrs: &mut [PtrAndLen] =
291            slice::from_raw_parts_mut(upb_Array_MutableDataPtr(dest).cast(), len);
292        for (src_ptr, dest_ptr) in src_ptrs.iter().zip(dest_ptrs) {
293            *dest_ptr = arena.copy_slice_in(src_ptr.as_ref()).unwrap().into();
294        }
295    }
296}