buffa/message_field.rs
1// Modified by ReallyMe Technologies Limited.
2//! Optional message field wrapper that provides ergonomic access.
3//!
4//! `MessageField<T>` replaces `Option<Box<T>>` for optional/singular message
5//! fields. It dereferences to a default instance when unset, avoiding the
6//! `Option<Box<M>>` unwrapping ceremony that plagues prost-generated code.
7
8use alloc::boxed::Box;
9use core::fmt;
10use core::ops::{Deref, DerefMut};
11
12/// Provides access to a lazily-initialized, immutable default instance of a
13/// type.
14///
15/// Types that implement this trait can be used as the target of
16/// [`MessageField<T>`] dereferences when the field is unset. It is also a
17/// supertrait of [`Message`](crate::Message), so every generated message type
18/// must implement it.
19///
20/// **Codegen implements this automatically** for every generated message
21/// type. You only need to implement it by hand when manually implementing
22/// [`Message`](crate::Message) for a custom type.
23///
24/// # Recommended implementation
25///
26/// The pattern codegen uses — and the recommended pattern for manual
27/// implementations — stores the instance in a `static`
28/// [`once_cell::race::OnceBox`] (re-exported as
29/// `::buffa::__private::OnceBox`), which works in both `no_std + alloc` and
30/// `std` environments:
31///
32/// ```rust,ignore
33/// impl DefaultInstance for MyMessage {
34/// fn default_instance() -> &'static Self {
35/// static VALUE: ::buffa::__private::OnceBox<MyMessage>
36/// = ::buffa::__private::OnceBox::new();
37/// VALUE.get_or_init(|| ::alloc::boxed::Box::new(MyMessage::default()))
38/// }
39/// }
40/// ```
41///
42/// In `std`-only environments [`std::sync::OnceLock`] is also available and
43/// avoids the `alloc::boxed::Box` wrapping:
44///
45/// ```rust,ignore
46/// impl DefaultInstance for MyMessage {
47/// fn default_instance() -> &'static Self {
48/// static VALUE: std::sync::OnceLock<MyMessage> = std::sync::OnceLock::new();
49/// VALUE.get_or_init(MyMessage::default)
50/// }
51/// }
52/// ```
53pub trait DefaultInstance: Default + 'static {
54 /// Return a reference to the single default instance of this type.
55 fn default_instance() -> &'static Self;
56}
57
58/// Implement [`DefaultInstance`] for a message type via a lazily-initialized
59/// `OnceBox` singleton.
60///
61/// Emitted by generated code (one invocation per message struct) so the
62/// six-line singleton body lives here once instead of in every generated
63/// impl. Hand-written `Message` types may also use it.
64///
65/// ```rust,ignore
66/// buffa::impl_default_instance!(MyMessage);
67/// ```
68#[macro_export]
69macro_rules! impl_default_instance {
70 ($ty:ty) => {
71 impl $crate::DefaultInstance for $ty {
72 fn default_instance() -> &'static Self {
73 static VALUE: $crate::__private::OnceBox<$ty> = $crate::__private::OnceBox::new();
74 VALUE.get_or_init(|| {
75 $crate::alloc::boxed::Box::new(<$ty as ::core::default::Default>::default())
76 })
77 }
78 }
79 };
80}
81
82/// The owned smart pointer backing a singular message field inside
83/// [`MessageField`].
84///
85/// The codegen default is [`Inline<T>`] — the message is stored directly in the
86/// parent struct (no heap), with recursive fields kept on `Box<T>`
87/// automatically. `buffa_build`'s [`box_type_in`][bti] selects [`Box<T>`] (or a
88/// custom pointer) for fields where reserving `size_of::<T>()` in the parent is
89/// wasteful. The `box_type_custom` knob substitutes any pointer that implements
90/// `ProtoBox<T>` — for example a `smallbox`-style pointer that stores small
91/// messages inline but spills large ones to the heap. The wire format is
92/// unchanged; only the in-memory ownership of the boxed message changes, and
93/// view types are unaffected.
94///
95/// There is intentionally no blanket impl — the built-in [`Box<T>`] and
96/// [`Inline<T>`] impls below are the only ones buffa provides. Because
97/// `ProtoBox` is buffa-owned, a *foreign* pointer cannot implement it directly
98/// (orphan rule); wrap it in a crate-local newtype, like the `ProtoString`
99/// newtype pattern.
100///
101/// [bti]: https://docs.rs/reallyme-buffa-build/latest/buffa_build/struct.Config.html#method.box_type_in
102///
103/// # Why `DerefMut` (and why `Rc` / `Arc` are excluded)
104///
105/// The decoder merges a message field in place — it calls
106/// [`get_or_insert_default`](MessageField::get_or_insert_default) to obtain a
107/// `&mut T` and decodes into it. That requires `DerefMut`, which `Rc<T>` and
108/// `Arc<T>` cannot provide while shared. So this knob selects an **allocation
109/// strategy** (inline vs heap) for an exclusively-owned message, never a shared
110/// or copy-on-write pointer. A custom pointer that is not exclusively owned will
111/// fail to implement `ProtoBox` at its definition site, not silently misbehave.
112///
113/// # Thread-safety
114///
115/// `ProtoBox` deliberately does **not** require `Send`/`Sync` (unlike
116/// `ProtoString`/`ProtoBytes`/`ProtoList`). `MessageField<T>` is the universal
117/// message-field wrapper and has generic helpers; bounding the pointer
118/// `Send + Sync` would tighten `T: Send + Sync` onto all of them. It is also
119/// unnecessary: a generated message implements [`Message`](crate::Message),
120/// whose `Send + Sync` supertraits already require every field — and thus the
121/// pointer — to be `Send + Sync`, so a non-`Send` custom pointer is rejected at
122/// the message's `impl Message`, just less locally.
123///
124/// # Caveat
125///
126/// A *custom* inline pointer (e.g. `SmallBox`) inflates the parent struct by
127/// its inline-storage size for every such field. The built-in [`Inline<T>`]
128/// default is recursion-aware and is the intended blanket; reserve custom
129/// inline pointers for per-field or per-prefix overrides.
130///
131/// # JSON serialization
132///
133/// When JSON codegen is enabled, custom pointers do not need
134/// `serde::Serialize` or `serde::Deserialize`. Singular message fields use
135/// `MessageField`'s generic serde implementation, and message-valued oneof
136/// variants serialize the pointee through this trait's `Deref` bound.
137///
138/// # Examples
139///
140/// A minimal crate-local newtype wrapping a foreign pointer (the `Clone` derive
141/// is only needed if the enclosing message derives `Clone`):
142///
143/// ```rust,ignore
144/// #[derive(Clone)]
145/// pub struct SmallBox<T>(pub smallbox::SmallBox<T, smallbox::space::S4>);
146///
147/// impl<T> core::ops::Deref for SmallBox<T> {
148/// type Target = T;
149/// fn deref(&self) -> &T { &self.0 }
150/// }
151/// impl<T> core::ops::DerefMut for SmallBox<T> {
152/// fn deref_mut(&mut self) -> &mut T { &mut self.0 }
153/// }
154/// impl<T> buffa::ProtoBox<T> for SmallBox<T> {
155/// fn new(value: T) -> Self { SmallBox(smallbox::smallbox!(value)) }
156/// fn into_inner(self) -> T { self.0.into_inner() }
157/// }
158/// ```
159///
160/// Then point a field at it: `box_type_custom("::my_crate::SmallBox<*>")`.
161#[rustversion::attr(
162 since(1.78),
163 diagnostic::on_unimplemented(
164 message = "`{Self}` cannot be used as a buffa custom box type",
165 note = "buffa owns `ProtoBox`, so a foreign type can't implement it directly (orphan rule). \
166 Wrap it in a crate-local newtype and implement `ProtoBox` on the newtype. \
167 See the `custom-types` example in the buffa repository for a template."
168 )
169)]
170pub trait ProtoBox<T>: Deref<Target = T> + DerefMut {
171 /// Box a freshly-decoded or constructed message value.
172 fn new(value: T) -> Self;
173
174 /// Unwrap the pointer, returning the owned message value (the
175 /// [`take`](MessageField::take) / [`into_option`](MessageField::into_option)
176 /// path).
177 fn into_inner(self) -> T;
178}
179
180impl<T> ProtoBox<T> for Box<T> {
181 #[inline]
182 fn new(value: T) -> Self {
183 Box::new(value)
184 }
185
186 #[inline]
187 fn into_inner(self) -> T {
188 *self
189 }
190}
191
192/// A [`ProtoBox`] that stores the message inline (no heap allocation).
193///
194/// `MessageField<T, Inline<T>>` is laid out as `Option<T>` — set values live
195/// directly in the parent struct. This eliminates the per-field allocation of
196/// the default `Box<T>` pointer at the cost of inflating the parent's size by
197/// `size_of::<T>()` even when the field is unset.
198///
199/// Codegen uses this by default via [`PointerRepr::Inline`][pri], which is
200/// recursion-aware: a field that would form an infinite-size cycle is silently
201/// kept on `Box`. Opt out per-field with `box_type_in(PointerRepr::Box, …)`.
202///
203/// [pri]: https://docs.rs/reallyme-buffa-codegen/latest/buffa_codegen/enum.PointerRepr.html#variant.Inline
204#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
205#[repr(transparent)]
206pub struct Inline<T>(pub T);
207
208impl<T> Deref for Inline<T> {
209 type Target = T;
210 #[inline]
211 fn deref(&self) -> &T {
212 &self.0
213 }
214}
215
216impl<T> DerefMut for Inline<T> {
217 #[inline]
218 fn deref_mut(&mut self) -> &mut T {
219 &mut self.0
220 }
221}
222
223impl<T> ProtoBox<T> for Inline<T> {
224 #[inline]
225 fn new(value: T) -> Self {
226 Inline(value)
227 }
228
229 #[inline]
230 fn into_inner(self) -> T {
231 self.0
232 }
233}
234
235/// Convenience mirror of `Box`'s `From<T>`; codegen and [`MessageField::some`]
236/// use [`ProtoBox::new`] instead.
237impl<T> From<T> for Inline<T> {
238 #[inline]
239 fn from(value: T) -> Self {
240 Inline(value)
241 }
242}
243
244// The built-in pointers must always satisfy the bound; freeze that invariant
245// against future changes to the trait's supertraits.
246const _: fn() = || {
247 fn assert_proto_box<P: ProtoBox<T>, T>() {}
248 assert_proto_box::<Box<u32>, u32>();
249 assert_proto_box::<Inline<u32>, u32>();
250};
251
252/// A wrapper for optional message fields that provides transparent access
253/// to a default instance when the field is not set.
254///
255/// This type is used for singular message fields in generated code. The pointer
256/// type `P` is pluggable; see [`ProtoBox`]. Codegen emits [`Inline<T>`] by
257/// default — the message is stored directly in the parent struct (laid out as
258/// `Option<T>`), so `size_of::<T>()` is reserved whether set or not and there
259/// is no per-field heap allocation. Recursive fields and explicit opt-outs use
260/// `Box<T>` instead, which heap-allocates only when set. The struct's own
261/// `P = Box<T>` type-parameter default applies only to a hand-written
262/// `MessageField<T>` (e.g. in tests), not to generated fields.
263/// Because `P` has a default, a *standalone* construction with no pinning
264/// context needs a type annotation — write `let f: MessageField<Foo> =
265/// MessageField::some(x);` (or `MessageField::<Foo>::some(x)`). In the common
266/// cases — a struct-literal field (`Outer { inner: MessageField::some(x), .. }`)
267/// or an assignment to a typed field — `P` is inferred from the target and no
268/// annotation is needed.
269///
270/// # Access patterns
271///
272/// ```rust,ignore
273/// // Reading through an unset field gives the default:
274/// let msg = Outer::default();
275/// assert_eq!(msg.inner.name, ""); // No unwrap needed, derefs to default
276///
277/// // Check if set:
278/// if msg.inner.is_set() { ... }
279///
280/// // Set a value:
281/// msg.inner = MessageField::some(Inner { name: "hello".into(), ..Default::default() });
282///
283/// // Clear:
284/// msg.inner = MessageField::none();
285/// ```
286///
287/// # Construction and conversion
288///
289/// [`From`] conversions are the idiomatic way to populate a generated message
290/// field. They accept both a message value and an [`Option`] of one. Reading
291/// goes the other way through [`Deref`], so a field whose
292/// message type implements [`DefaultInstance`] needs no unwrapping at all.
293///
294/// ```rust
295/// # use buffa::__doctest_fixtures::Person;
296/// use buffa::MessageField;
297///
298/// // A value converts straight into a set field.
299/// let field: MessageField<Person> = Person { name: "Ada".into(), id: 1 }.into();
300/// // Reading goes through `Deref`, so no unwrapping ceremony.
301/// assert_eq!(field.name, "Ada");
302///
303/// // An `Option` converts too, so `map` chains land directly in the field.
304/// let field: MessageField<Person> = Some("Grace")
305/// .map(|name| Person { name: name.into(), id: 2 })
306/// .into();
307/// assert_eq!(field.id, 2);
308///
309/// // An unset field derefs to the default instance rather than panicking.
310/// let empty: MessageField<Person> = None.into();
311/// assert!(empty.is_unset());
312/// assert_eq!(empty.name, "");
313/// ```
314///
315/// # Equality and hashing
316///
317/// `==` includes presence, as for `Option<T>` and in Go's `proto.Equal`: an
318/// unset field differs from one set to its default, since only the set one is
319/// on the wire. Deref both sides to compare the values alone; that ignores
320/// presence at this level only, not in message fields nested inside. `Deref`
321/// needs `T: DefaultInstance`, which `==` does not.
322///
323/// `Hash` agrees with `==`: it covers presence and the value, as
324/// `Option<&T>` does. Hash `*field` instead to hash the value alone, matching
325/// `*a == *b`.
326///
327/// ```rust
328/// # use buffa::__doctest_fixtures::Person;
329/// use buffa::MessageField;
330///
331/// let unset: MessageField<Person> = MessageField::none();
332/// let set_empty: MessageField<Person> = MessageField::some(Person::default());
333/// assert!(unset != set_empty);
334/// assert!(*unset == *set_empty);
335/// ```
336pub struct MessageField<T: Default, P = Box<T>> {
337 inner: Option<P>,
338 _marker: core::marker::PhantomData<T>,
339}
340
341impl<T: Default, P: ProtoBox<T>> MessageField<T, P> {
342 /// Create a `MessageField` with no value set.
343 #[inline]
344 pub const fn none() -> Self {
345 Self {
346 inner: None,
347 _marker: core::marker::PhantomData,
348 }
349 }
350
351 /// Create a `MessageField` with a value.
352 #[inline]
353 pub fn some(value: T) -> Self {
354 Self {
355 inner: Some(<P as ProtoBox<T>>::new(value)),
356 _marker: core::marker::PhantomData,
357 }
358 }
359
360 /// Create a `MessageField` from an already-constructed pointer, without
361 /// unwrapping and re-boxing the value.
362 ///
363 /// Prefer this over `MessageField::some(p.into_inner())` when you already
364 /// hold a `P` — for an inline pointer (e.g. `SmallBox`) the latter would
365 /// move the value out and re-store it, defeating the point. The generic
366 /// counterpart to [`from_box`](Self::from_box) (which is `Box`-only).
367 #[inline]
368 pub fn from_pointer(value: P) -> Self {
369 Self {
370 inner: Some(value),
371 _marker: core::marker::PhantomData,
372 }
373 }
374
375 /// Returns `true` if the field has a value set.
376 #[inline]
377 pub fn is_set(&self) -> bool {
378 self.inner.is_some()
379 }
380
381 /// Returns `true` if the field has no value set.
382 #[inline]
383 pub fn is_unset(&self) -> bool {
384 self.inner.is_none()
385 }
386
387 /// Get a reference to the inner value, or `None` if unset.
388 #[inline]
389 pub fn as_option(&self) -> Option<&T> {
390 self.inner.as_deref()
391 }
392
393 /// Get a mutable reference to the inner value, or `None` if unset.
394 #[inline]
395 pub fn as_option_mut(&mut self) -> Option<&mut T> {
396 self.inner.as_deref_mut()
397 }
398
399 /// Take the inner value, leaving the field unset.
400 #[inline]
401 pub fn take(&mut self) -> Option<T> {
402 self.inner.take().map(<P as ProtoBox<T>>::into_inner)
403 }
404
405 /// Get a mutable reference to the value, initializing to the default if unset.
406 #[inline]
407 pub fn get_or_insert_default(&mut self) -> &mut T {
408 // `&mut P` coerces to `&mut T` via `P: DerefMut<Target = T>`. Uses
409 // `ProtoBox::new` rather than `Option::get_or_insert_default` so no
410 // `P: Default` bound is needed (a custom pointer need not be `Default`).
411 self.inner
412 .get_or_insert_with(|| <P as ProtoBox<T>>::new(T::default()))
413 }
414
415 /// Call `f` with a mutable reference to the inner value, initializing to
416 /// the default if the field is currently unset.
417 ///
418 /// This is the ergonomic write counterpart to the transparent read
419 /// provided by `Deref`. Instead of calling `get_or_insert_default` once
420 /// per assignment:
421 ///
422 /// ```rust,ignore
423 /// msg.address.get_or_insert_default().street = "123 Main St".into();
424 /// msg.address.get_or_insert_default().city = "Springfield".into();
425 /// ```
426 ///
427 /// use `modify` to initialize the field once and set all sub-fields in
428 /// the closure:
429 ///
430 /// ```rust,ignore
431 /// msg.address.modify(|a| {
432 /// a.street = "123 Main St".into();
433 /// a.city = "Springfield".into();
434 /// });
435 /// ```
436 #[inline]
437 pub fn modify<F: FnOnce(&mut T)>(&mut self, f: F) {
438 f(self.get_or_insert_default());
439 }
440
441 /// Consume the field, returning `Some(T)` if set or `None` if unset.
442 ///
443 /// This unboxes the inner value. For in-place extraction that leaves the
444 /// field unset without consuming the enclosing struct, see [`take`](Self::take).
445 #[inline]
446 pub fn into_option(self) -> Option<T> {
447 self.inner.map(<P as ProtoBox<T>>::into_inner)
448 }
449
450 /// Consume the field, applying `f` to the inner value if set.
451 ///
452 /// Mirrors [`Option::map`]. Equivalent in effect to
453 /// [`into_option`](Self::into_option)`.map(f)`, but reads as if the
454 /// field were a plain `Option`. The motivating case is converting an
455 /// optional submessage into a differently-typed `Option` when mapping
456 /// a generated struct to a domain type:
457 ///
458 /// ```rust,ignore
459 /// // Before: value.shoulder_entity_left.into_option().map(Into::into)
460 /// shoulder_entity_left: value.shoulder_entity_left.map(Into::into),
461 /// ```
462 ///
463 /// With `map(Into::into)` the target type must be inferable from
464 /// context (a typed struct field, annotated `let`, or function return);
465 /// otherwise name the conversion (`map(Domain::from)`). To map without
466 /// consuming the field, use [`as_option`](Self::as_option)`.map(...)`.
467 #[inline]
468 pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
469 self.into_option().map(f)
470 }
471
472 /// Consume the field, returning the inner value.
473 ///
474 /// Equivalent in effect to `into_option().unwrap()`, with a clearer
475 /// panic message. Prefer [`ok_or`](Self::ok_or) /
476 /// [`ok_or_else`](Self::ok_or_else) when an unset field should produce
477 /// an error rather than a panic.
478 ///
479 /// # Panics
480 ///
481 /// Panics if the field is unset.
482 #[inline]
483 #[track_caller]
484 pub fn unwrap(self) -> T {
485 match self.inner {
486 Some(b) => <P as ProtoBox<T>>::into_inner(b),
487 None => panic!("called `MessageField::unwrap()` on an unset field"),
488 }
489 }
490
491 /// Consume the field, returning the inner value, with a custom panic
492 /// message if unset.
493 ///
494 /// Mirrors [`Option::expect`]. Prefer [`ok_or`](Self::ok_or) /
495 /// [`ok_or_else`](Self::ok_or_else) when an unset field should produce
496 /// an error rather than a panic.
497 ///
498 /// # Panics
499 ///
500 /// Panics with `msg` if the field is unset.
501 #[inline]
502 #[track_caller]
503 pub fn expect(self, msg: &str) -> T {
504 match self.inner {
505 Some(b) => <P as ProtoBox<T>>::into_inner(b),
506 None => panic!("{msg}"),
507 }
508 }
509
510 /// Consume the field, returning `Ok(T)` if set or `Err(err)` if unset.
511 ///
512 /// Mirrors [`Option::ok_or`]. Useful for enforcing presence of
513 /// semantically-required fields that the proto schema leaves optional:
514 ///
515 /// ```rust,ignore
516 /// let cmd = request.normalized_command.ok_or(Error::MissingCommand)?;
517 /// ```
518 #[inline]
519 pub fn ok_or<E>(self, err: E) -> Result<T, E> {
520 match self.inner {
521 Some(b) => Ok(<P as ProtoBox<T>>::into_inner(b)),
522 None => Err(err),
523 }
524 }
525
526 /// Consume the field, returning `Ok(T)` if set or `Err(err())` if unset.
527 ///
528 /// Mirrors [`Option::ok_or_else`]. The closure is only called if the
529 /// field is unset, so use this over [`ok_or`](Self::ok_or) when
530 /// constructing the error is non-trivial:
531 ///
532 /// ```rust,ignore
533 /// let cmd = request.normalized_command.ok_or_else(|| {
534 /// ConnectError::invalid_argument("missing normalized_command in request")
535 /// })?;
536 /// ```
537 #[inline]
538 pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
539 match self.inner {
540 Some(b) => Ok(<P as ProtoBox<T>>::into_inner(b)),
541 None => Err(err()),
542 }
543 }
544}
545
546impl<T: Default> MessageField<T, Box<T>> {
547 /// Create a `MessageField` from a boxed value.
548 ///
549 /// Specific to `Box<T>` (the struct's `P = Box<T>` type-parameter default,
550 /// used for recursive fields and explicit opt-outs); inline-backed
551 /// generated fields use [`some`](Self::some) or
552 /// [`from_pointer`](Self::from_pointer) instead.
553 #[inline]
554 pub fn from_box(value: Box<T>) -> Self {
555 Self {
556 inner: Some(value),
557 _marker: core::marker::PhantomData,
558 }
559 }
560}
561
562impl<T: Default, P: ProtoBox<T>> Default for MessageField<T, P> {
563 #[inline]
564 fn default() -> Self {
565 Self::none()
566 }
567}
568
569impl<T: DefaultInstance, P: ProtoBox<T>> Deref for MessageField<T, P> {
570 type Target = T;
571
572 #[inline]
573 fn deref(&self) -> &T {
574 match &self.inner {
575 // `&P` coerces to `&T` via `P: Deref<Target = T>`.
576 Some(value) => value,
577 None => T::default_instance(),
578 }
579 }
580}
581
582impl<T: Default + Clone, P: ProtoBox<T> + Clone> Clone for MessageField<T, P> {
583 fn clone(&self) -> Self {
584 // Build each arm directly. Cloning `inner` into a temporary merges both
585 // arms before the move, and LLVM then copies the whole `Option<P>`,
586 // payload included, even for an unset field (a full nested-message copy
587 // with `Inline<T>`).
588 match &self.inner {
589 Some(value) => Self::from_pointer(value.clone()),
590 None => Self::none(),
591 }
592 }
593}
594
595/// Presence-aware equality: two unset fields are equal, two set fields are
596/// equal when their values are, and an unset field never equals a set one,
597/// not even one set to the default. See [`MessageField`]'s "Equality" section.
598impl<T: Default + PartialEq, P: ProtoBox<T>> PartialEq for MessageField<T, P> {
599 // `always`: with plain `#[inline]`, LLVM inlines `T::eq` into this body
600 // first, and for a larger `T` the grown body then stays a call in the
601 // caller, paid even when both sides are unset. The dispatch is three arms;
602 // `T::eq` keeps its own inlining decision.
603 #[inline(always)]
604 fn eq(&self, other: &Self) -> bool {
605 // Presence is part of the value, as in Go's `proto.Equal` and C++'s
606 // `MessageDifferencer::Equals`: an unset field and one set to its
607 // default encode differently, so they are not equal. Compare the
608 // pointed-to `T` values (via `**`), not the pointers, so no
609 // `P: PartialEq` bound is needed.
610 match (&self.inner, &other.inner) {
611 (Some(a), Some(b)) => **a == **b,
612 (None, None) => true,
613 _ => false,
614 }
615 }
616}
617
618impl<T: Default + Eq, P: ProtoBox<T>> Eq for MessageField<T, P> {}
619
620/// Hashes presence and the value, as `Option<&T>` does, so that it agrees with
621/// `==`: equal fields hash alike. Hash `*field` to hash the value alone.
622impl<T: Default + core::hash::Hash, P: ProtoBox<T>> core::hash::Hash for MessageField<T, P> {
623 #[inline]
624 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
625 self.as_option().hash(state);
626 }
627}
628
629impl<T: Default + fmt::Debug, P: ProtoBox<T>> fmt::Debug for MessageField<T, P> {
630 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
631 match &self.inner {
632 // Format the pointed-to `T` (via `&**`), so no `P: Debug` bound.
633 Some(value) => f.debug_tuple("MessageField::Set").field(&**value).finish(),
634 None => f.write_str("MessageField::Unset"),
635 }
636 }
637}
638
639impl<T: Default, P: ProtoBox<T>> From<Option<T>> for MessageField<T, P> {
640 fn from(opt: Option<T>) -> Self {
641 match opt {
642 Some(v) => Self::some(v),
643 None => Self::none(),
644 }
645 }
646}
647
648impl<T: Default, P: ProtoBox<T>> From<MessageField<T, P>> for Option<T> {
649 /// Unbox a `MessageField` into an `Option<T>`; equivalent to
650 /// [`MessageField::into_option`].
651 #[inline]
652 fn from(field: MessageField<T, P>) -> Self {
653 field.into_option()
654 }
655}
656
657impl<T: Default, P: ProtoBox<T>> From<T> for MessageField<T, P> {
658 fn from(value: T) -> Self {
659 Self::some(value)
660 }
661}
662
663#[cfg(feature = "json")]
664impl<T: Default + serde::Serialize, P: ProtoBox<T>> serde::Serialize for MessageField<T, P> {
665 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
666 match self.inner.as_deref() {
667 Some(v) => s.serialize_some(v),
668 None => s.serialize_none(),
669 }
670 }
671}
672
673#[cfg(feature = "json")]
674impl<'de, T: Default + serde::Deserialize<'de>, P: ProtoBox<T>> serde::Deserialize<'de>
675 for MessageField<T, P>
676{
677 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
678 Option::<T>::deserialize(d).map(|opt| match opt {
679 Some(v) => Self::some(v),
680 None => Self::none(),
681 })
682 }
683}
684
685#[cfg(feature = "arbitrary")]
686impl<'a, T: Default + arbitrary::Arbitrary<'a>, P: ProtoBox<T>> arbitrary::Arbitrary<'a>
687 for MessageField<T, P>
688{
689 fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
690 Ok(if bool::arbitrary(u)? {
691 MessageField::some(T::arbitrary(u)?)
692 } else {
693 MessageField::none()
694 })
695 }
696}
697
698#[cfg(test)]
699mod tests {
700 use super::*;
701
702 #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
703 struct Inner {
704 value: i32,
705 name: alloc::string::String,
706 }
707
708 // Via the exported macro, which doubles as its unit test (hygiene and
709 // `$crate` path resolution).
710 crate::impl_default_instance!(Inner);
711
712 #[test]
713 fn inline_message_field_is_option_layout() {
714 // `Inline<T>` is `repr(transparent)`, so `MessageField<T, Inline<T>>`
715 // (which is `Option<Inline<T>>`) is laid out as `Option<T>`.
716 use core::mem::size_of;
717 assert_eq!(
718 size_of::<MessageField<Inner, Inline<Inner>>>(),
719 size_of::<Option<Inner>>()
720 );
721 // And the `ProtoBox` surface round-trips.
722 let mut f: MessageField<Inner, Inline<Inner>> = MessageField::some(Inner {
723 value: 7,
724 ..Default::default()
725 });
726 assert_eq!(f.value, 7);
727 f.get_or_insert_default().value = 9;
728 assert_eq!(f.take().map(|i| i.value), Some(9));
729 assert!(f.is_unset());
730 }
731
732 #[test]
733 fn impl_default_instance_macro_returns_singleton() {
734 let a: &'static Inner = Inner::default_instance();
735 let b: &'static Inner = Inner::default_instance();
736 assert!(core::ptr::eq(a, b), "singleton must be a single allocation");
737 assert_eq!(a, &Inner::default());
738 }
739
740 #[test]
741 fn test_unset_derefs_to_default() {
742 let field: MessageField<Inner> = MessageField::none();
743 assert!(!field.is_set());
744 assert_eq!(field.value, 0);
745 assert_eq!(field.name, "");
746 }
747
748 #[test]
749 fn test_set_derefs_to_value() {
750 let field: MessageField<Inner> = MessageField::some(Inner {
751 value: 42,
752 name: "hello".into(),
753 });
754 assert!(field.is_set());
755 assert_eq!(field.value, 42);
756 assert_eq!(field.name, "hello");
757 }
758
759 #[test]
760 fn test_get_or_insert_default() {
761 let mut field: MessageField<Inner> = MessageField::none();
762 assert!(!field.is_set());
763 field.get_or_insert_default().value = 10;
764 assert!(field.is_set());
765 assert_eq!(field.value, 10);
766 }
767
768 /// Equality cases shared by every pointer representation `P`.
769 fn assert_equality_cases<P: ProtoBox<Inner>>() {
770 let non_default = || Inner {
771 value: 1,
772 ..Default::default()
773 };
774 let unset: MessageField<Inner, P> = MessageField::none();
775 let other_unset: MessageField<Inner, P> = MessageField::none();
776 let default: MessageField<Inner, P> = MessageField::some(Inner::default());
777 let value: MessageField<Inner, P> = MessageField::some(non_default());
778 let same_value: MessageField<Inner, P> = MessageField::some(non_default());
779
780 assert_eq!(unset, other_unset);
781
782 // Presence is part of the value: unset differs from set-to-default in
783 // both directions, while the values behind them compare equal.
784 assert_ne!(unset, default);
785 assert_ne!(default, unset);
786 assert_eq!(*unset, *default);
787
788 assert_ne!(unset, value);
789 assert_ne!(value, unset);
790
791 assert_ne!(default, value);
792 assert_ne!(value, default);
793 assert_eq!(value, same_value);
794 }
795
796 #[test]
797 fn test_equality() {
798 assert_equality_cases::<Box<Inner>>();
799 }
800
801 #[test]
802 fn test_equality_inline() {
803 assert_equality_cases::<Inline<Inner>>();
804 }
805
806 fn hash_of<H: core::hash::Hash + ?Sized>(value: &H) -> u64 {
807 use core::hash::Hasher;
808 let mut hasher = std::collections::hash_map::DefaultHasher::new();
809 value.hash(&mut hasher);
810 hasher.finish()
811 }
812
813 /// Hashes as `Option<&T>` does, so fields `==` calls equal hash alike and
814 /// unset hashes apart from set to the default.
815 fn assert_hash_cases<P: ProtoBox<Inner>>() {
816 let value = || Inner {
817 value: 7,
818 name: "x".into(),
819 };
820 let unset = MessageField::<Inner, P>::none();
821 let set = MessageField::<Inner, P>::some(value());
822 let set_default = MessageField::<Inner, P>::some(Inner::default());
823 assert_eq!(hash_of(&unset), hash_of(&None::<&Inner>));
824 assert_eq!(hash_of(&set), hash_of(&Some(&value())));
825 assert_eq!(hash_of(&set_default), hash_of(&Some(&Inner::default())));
826 assert_ne!(hash_of(&unset), hash_of(&set_default));
827 }
828
829 #[test]
830 fn test_hash_agrees_with_equality() {
831 assert_hash_cases::<Box<Inner>>();
832 assert_hash_cases::<Inline<Inner>>();
833 }
834
835 /// `==` needs no `DefaultInstance`: only `T: Default + PartialEq`.
836 #[test]
837 fn test_equality_without_default_instance() {
838 #[derive(Debug, Default, PartialEq)]
839 struct Plain(u8);
840
841 let set: MessageField<Plain> = MessageField::some(Plain(1));
842 assert_eq!(set, MessageField::some(Plain(1)));
843 assert_ne!(set, MessageField::none());
844 }
845
846 #[test]
847 fn test_unwrap_set() {
848 let field: MessageField<Inner> = MessageField::some(Inner {
849 value: 7,
850 name: "x".into(),
851 });
852 let inner = field.unwrap();
853 assert_eq!(inner.value, 7);
854 }
855
856 #[test]
857 #[should_panic(expected = "called `MessageField::unwrap()` on an unset field")]
858 fn test_unwrap_unset_panics() {
859 let field: MessageField<Inner> = MessageField::none();
860 let _ = field.unwrap();
861 }
862
863 #[test]
864 #[should_panic(expected = "address is required")]
865 fn test_expect_unset_panics_with_message() {
866 let field: MessageField<Inner> = MessageField::none();
867 let _ = field.expect("address is required");
868 }
869
870 #[test]
871 fn test_from_message_field_for_option_roundtrips() {
872 let inner = Inner {
873 value: 3,
874 name: "rt".into(),
875 };
876 let field: MessageField<Inner> = Some(inner.clone()).into();
877 let back: Option<Inner> = field.into();
878 assert_eq!(back, Some(inner));
879
880 let none_field: MessageField<Inner> = MessageField::none();
881 let none_back: Option<Inner> = none_field.into();
882 assert_eq!(none_back, None);
883 }
884
885 #[test]
886 fn test_take() {
887 let mut field: MessageField<Inner> = MessageField::some(Inner {
888 value: 7,
889 name: "taken".into(),
890 });
891 let taken = field.take();
892 assert!(field.is_unset());
893 assert_eq!(taken.unwrap().value, 7);
894 }
895
896 /// Clone keeps presence and value for every pointer representation `P`.
897 fn assert_clone_cases<P: ProtoBox<Inner> + Clone>() {
898 let unset: MessageField<Inner, P> = MessageField::none();
899 assert!(unset.clone().is_unset());
900
901 let default: MessageField<Inner, P> = MessageField::some(Inner::default());
902 assert!(default.clone().is_set());
903 assert_eq!(default.clone(), default);
904
905 let set: MessageField<Inner, P> = MessageField::some(Inner {
906 value: 7,
907 name: "clone".into(),
908 });
909 let cloned = set.clone();
910 assert!(cloned.is_set());
911 assert_eq!(cloned, set);
912 assert_eq!(cloned.name, "clone");
913 }
914
915 #[test]
916 fn test_clone() {
917 assert_clone_cases::<Box<Inner>>();
918 assert_clone_cases::<Inline<Inner>>();
919 }
920
921 #[test]
922 fn test_modify_initializes_unset_field() {
923 let mut field: MessageField<Inner> = MessageField::none();
924 field.modify(|inner| {
925 inner.value = 42;
926 inner.name = "hello".into();
927 });
928 assert!(field.is_set());
929 assert_eq!(field.value, 42);
930 assert_eq!(field.name, "hello");
931 }
932
933 #[test]
934 fn test_modify_updates_already_set_field() {
935 let mut field: MessageField<Inner> = MessageField::some(Inner {
936 value: 1,
937 name: "original".into(),
938 });
939 field.modify(|inner| {
940 inner.value = 99;
941 });
942 // Existing value is mutated in place, not reset to default.
943 assert_eq!(field.value, 99);
944 assert_eq!(field.name, "original");
945 }
946
947 #[test]
948 fn test_modify_multiple_fields_in_one_call() {
949 // Demonstrates the primary motivation: one initialization, many assignments.
950 let mut field: MessageField<Inner> = MessageField::none();
951 field.modify(|inner| {
952 inner.value = 10;
953 inner.name = "multi".into();
954 });
955 assert_eq!(field.value, 10);
956 assert_eq!(field.name, "multi");
957 }
958
959 #[test]
960 fn test_modify_noop_still_initializes_unset_field() {
961 // Even a no-op closure causes the field to become set (to the default).
962 let mut field: MessageField<Inner> = MessageField::none();
963 field.modify(|_| {});
964 assert!(field.is_set());
965 assert_eq!(field.value, 0);
966 assert_eq!(field.name, "");
967 }
968
969 #[test]
970 fn test_modify_closure_can_move_captured_values() {
971 // Verifies that the FnOnce bound is in effect: a closure that moves a
972 // captured value (String) into the field compiles and works correctly.
973 let mut field: MessageField<Inner> = MessageField::none();
974 let name = alloc::string::String::from("moved");
975 field.modify(|inner| {
976 inner.name = name; // moves `name` -- only valid with FnOnce
977 });
978 assert_eq!(field.name, "moved");
979 }
980
981 #[cfg(feature = "json")]
982 mod serde_tests {
983 use super::*;
984
985 #[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
986 struct Msg {
987 value: i32,
988 }
989
990 #[test]
991 fn unset_serializes_as_null() {
992 let f: MessageField<Msg> = MessageField::none();
993 assert_eq!(serde_json::to_string(&f).unwrap(), "null");
994 }
995
996 #[test]
997 fn set_serializes_as_inner_json() {
998 let f: MessageField<Msg> = MessageField::some(Msg { value: 42 });
999 let json = serde_json::to_string(&f).unwrap();
1000 assert_eq!(json, r#"{"value":42}"#);
1001 }
1002
1003 #[test]
1004 fn null_deserializes_as_unset() {
1005 let f: MessageField<Msg> = serde_json::from_str("null").unwrap();
1006 assert!(f.is_unset());
1007 }
1008
1009 #[test]
1010 fn object_deserializes_as_set() {
1011 let f: MessageField<Msg> = serde_json::from_str(r#"{"value":7}"#).unwrap();
1012 assert!(f.is_set());
1013 assert_eq!(f.as_option().unwrap().value, 7);
1014 }
1015
1016 #[test]
1017 fn round_trip_set_field() {
1018 let original: MessageField<Msg> = MessageField::some(Msg { value: 99 });
1019 let json = serde_json::to_string(&original).unwrap();
1020 let recovered: MessageField<Msg> = serde_json::from_str(&json).unwrap();
1021 assert_eq!(
1022 original.as_option().unwrap().value,
1023 recovered.as_option().unwrap().value
1024 );
1025 }
1026 }
1027
1028 #[test]
1029 fn test_into_option_unboxes() {
1030 let field: MessageField<Inner> = MessageField::some(Inner {
1031 value: 5,
1032 name: "x".into(),
1033 });
1034 // Type annotation asserts this is Option<Inner>, not Option<Box<Inner>>.
1035 let opt: Option<Inner> = field.into_option();
1036 assert_eq!(opt.unwrap().value, 5);
1037
1038 let field: MessageField<Inner> = MessageField::none();
1039 assert!(field.into_option().is_none());
1040 }
1041
1042 #[test]
1043 fn test_map_set_transforms_inner_value() {
1044 let field: MessageField<Inner> = MessageField::some(Inner {
1045 value: 5,
1046 name: "mapped".into(),
1047 });
1048 let mapped: Option<alloc::string::String> = field.map(|inner| inner.name);
1049 assert_eq!(mapped.as_deref(), Some("mapped"));
1050 }
1051
1052 #[test]
1053 fn test_map_unset_returns_none_without_calling_closure() {
1054 let field: MessageField<Inner> = MessageField::none();
1055 let mapped: Option<i32> = field.map(|_| panic!("closure must not run"));
1056 assert_eq!(mapped, None);
1057 }
1058
1059 #[test]
1060 fn test_map_accepts_fnonce_closure() {
1061 let field: MessageField<Inner> = MessageField::some(Inner::default());
1062 let replacement = alloc::string::String::from("moved");
1063 let mapped: Option<alloc::string::String> = field.map(|_| replacement);
1064 assert_eq!(mapped.as_deref(), Some("moved"));
1065 }
1066
1067 #[test]
1068 fn test_map_works_with_inline_pointer() {
1069 let field: MessageField<Inner, Inline<Inner>> = MessageField::some(Inner {
1070 value: 41,
1071 ..Default::default()
1072 });
1073 assert_eq!(field.map(|inner| inner.value + 1), Some(42));
1074 }
1075
1076 #[test]
1077 fn test_ok_or() {
1078 let set: MessageField<Inner> = MessageField::some(Inner {
1079 value: 1,
1080 name: "set".into(),
1081 });
1082 let r: Result<Inner, &str> = set.ok_or("missing");
1083 assert_eq!(r.unwrap().value, 1);
1084
1085 let unset: MessageField<Inner> = MessageField::none();
1086 assert_eq!(unset.ok_or("missing"), Err("missing"));
1087 }
1088
1089 #[test]
1090 fn test_ok_or_else() {
1091 let set: MessageField<Inner> = MessageField::some(Inner {
1092 value: 2,
1093 name: "set".into(),
1094 });
1095 assert_eq!(set.ok_or_else(|| "unreachable").unwrap().value, 2);
1096
1097 let unset: MessageField<Inner> = MessageField::none();
1098 assert_eq!(unset.ok_or_else(|| "missing"), Err("missing"));
1099 }
1100
1101 #[test]
1102 fn test_ok_or_else_closure_not_called_when_set() {
1103 let set: MessageField<Inner> = MessageField::some(Inner::default());
1104 let _ = set.ok_or_else(|| -> &str { panic!("closure must not run") });
1105 }
1106
1107 #[test]
1108 fn test_ok_or_else_partial_move() {
1109 // The motivating pattern: destructure several required fields out of
1110 // an owned request struct, one ok_or_else per field. Each is a partial
1111 // move; the remaining fields stay accessible.
1112 #[derive(Default)]
1113 struct Request {
1114 a: MessageField<Inner>,
1115 b: MessageField<Inner>,
1116 }
1117 let req = Request {
1118 a: MessageField::some(Inner {
1119 value: 1,
1120 ..Default::default()
1121 }),
1122 b: MessageField::some(Inner {
1123 value: 2,
1124 ..Default::default()
1125 }),
1126 };
1127 let a = req.a.ok_or_else(|| "missing a").unwrap();
1128 let b = req.b.ok_or_else(|| "missing b").unwrap();
1129 assert_eq!(a.value, 1);
1130 assert_eq!(b.value, 2);
1131 }
1132
1133 #[test]
1134 fn test_from_conversions() {
1135 let field: MessageField<Inner> = Inner {
1136 value: 1,
1137 name: "from".into(),
1138 }
1139 .into();
1140 assert!(field.is_set());
1141
1142 let field: MessageField<Inner> = None.into();
1143 assert!(field.is_unset());
1144
1145 let field: MessageField<Inner> = Some(Inner {
1146 value: 2,
1147 name: "some".into(),
1148 })
1149 .into();
1150 assert!(field.is_set());
1151 }
1152}