Skip to main content

buffa/
enumeration.rs

1// Modified by ReallyMe Technologies Limited.
2//! Enum support: the [`Enumeration`] trait and [`EnumValue<E>`] open-enum wrapper.
3//!
4//! Generated enum types implement [`Enumeration`]. For **open** enum fields
5//! (the editions default), generated message structs use [`EnumValue<E>`] to
6//! hold either a `Known(E)` variant or an `Unknown(i32)` wire value.
7
8use core::fmt;
9use core::hash::Hash;
10
11/// Trait implemented by all generated protobuf enum types.
12pub trait Enumeration: Clone + Copy + PartialEq + Eq + Hash + fmt::Debug {
13    /// Whether this enum represents `google.protobuf.NullValue` for JSON collections.
14    ///
15    /// Generated code sets this only for that exact protobuf type. The default
16    /// preserves existing implementations and rejects null collection elements
17    /// for ordinary enums, including enums with a case named `NULL_VALUE`.
18    /// This is semantic metadata supplied by the enum's owner, not an identity
19    /// check. A manually implemented NullValue provider must opt in explicitly
20    /// and recognize numeric zero as its null sentinel.
21    const IS_NULL_VALUE: bool = false;
22
23    /// Convert from an `i32` wire value to the enum.
24    ///
25    /// Returns `Some` for known variants, `None` for unknown values.
26    fn from_i32(value: i32) -> Option<Self>;
27
28    /// Convert the enum to its `i32` wire value.
29    fn to_i32(&self) -> i32;
30
31    /// The name of this enum variant as it appears in the `.proto` file.
32    fn proto_name(&self) -> &'static str;
33
34    /// Look up a variant by its protobuf name string.
35    ///
36    /// Returns `Some` for recognized names, `None` for unrecognized names.
37    /// The default implementation always returns `None`; generated code
38    /// overrides this with a match on all known variant names.
39    fn from_proto_name(_name: &str) -> Option<Self> {
40        None
41    }
42
43    /// All known variants of this enum, in proto declaration order.
44    ///
45    /// Generated `impl Enumeration` blocks override this with a static
46    /// slice of every variant. The default implementation returns an
47    /// empty slice so out-of-tree consumers implementing this trait
48    /// against an older codegen version continue to compile — they
49    /// should override the default once regenerated.
50    ///
51    /// # Example
52    ///
53    /// ```ignore
54    /// for variant in MyEnum::values() {
55    ///     println!("{:?} = {}", variant, variant.to_i32());
56    /// }
57    /// assert!(MyEnum::values().contains(&MyEnum::Active));
58    /// ```
59    fn values() -> &'static [Self] {
60        &[]
61    }
62}
63
64/// A protobuf enum field value that can hold either a known variant or an
65/// unknown `i32` value.
66///
67/// Used for **open** enums (the default in editions). Open enums accept any
68/// `i32` value on the wire, even if it doesn't correspond to a known variant.
69///
70/// # Conversion
71///
72/// Use [`.into()`](Into::into) to populate an open enum field from either a
73/// generated enum variant or a raw integer. Known variants become
74/// [`Known`](Self::Known); unrecognized integers are preserved as
75/// [`Unknown`](Self::Unknown).
76///
77/// ```rust
78/// # use buffa::Enumeration;
79/// use buffa::EnumValue;
80/// # // `Status` stands in for a generated enum.
81/// # #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
82/// # enum Status {
83/// #     Active,
84/// # }
85/// # impl Enumeration for Status {
86/// #     fn from_i32(value: i32) -> Option<Self> {
87/// #         (value == 1).then_some(Self::Active)
88/// #     }
89/// #     fn to_i32(&self) -> i32 {
90/// #         1
91/// #     }
92/// #     fn proto_name(&self) -> &'static str {
93/// #         "ACTIVE"
94/// #     }
95/// # }
96/// // A variant converts into a known value.
97/// let known: EnumValue<Status> = Status::Active.into();
98/// assert_eq!(known, EnumValue::Known(Status::Active));
99///
100/// // An integer off the wire that no variant matches is preserved as-is.
101/// let unknown: EnumValue<Status> = 99.into();
102/// assert_eq!(unknown, EnumValue::Unknown(99));
103/// ```
104#[derive(Clone, Copy, PartialEq, Eq, Hash)]
105pub enum EnumValue<E: Enumeration> {
106    /// A known enum variant.
107    Known(E),
108    /// An unknown value received on the wire.
109    Unknown(i32),
110}
111
112impl<E: Enumeration> EnumValue<E> {
113    /// Get the `i32` wire value.
114    #[inline]
115    pub fn to_i32(&self) -> i32 {
116        match self {
117            Self::Known(e) => e.to_i32(),
118            Self::Unknown(v) => *v,
119        }
120    }
121
122    /// Returns `true` if this is a known enum variant.
123    ///
124    /// This is a shorthand for `self.as_known().is_some()`, mirroring the
125    /// [`MessageField::is_set`](crate::MessageField::is_set) pattern.
126    #[inline]
127    pub fn is_known(&self) -> bool {
128        matches!(self, Self::Known(_))
129    }
130
131    /// Returns `true` if the wire value was not recognized as a known variant.
132    #[inline]
133    pub fn is_unknown(&self) -> bool {
134        matches!(self, Self::Unknown(_))
135    }
136
137    /// Try to convert to a known enum variant.
138    #[inline]
139    pub fn as_known(&self) -> Option<E> {
140        match self {
141            Self::Known(e) => Some(*e),
142            Self::Unknown(_) => None,
143        }
144    }
145}
146
147impl<E: Enumeration> From<i32> for EnumValue<E> {
148    fn from(value: i32) -> Self {
149        match E::from_i32(value) {
150            Some(e) => Self::Known(e),
151            None => Self::Unknown(value),
152        }
153    }
154}
155
156impl<E: Enumeration> From<E> for EnumValue<E> {
157    fn from(value: E) -> Self {
158        Self::Known(value)
159    }
160}
161
162/// Compare an [`EnumValue`] directly with a known variant: `field == MyEnum::Foo`.
163///
164/// Returns `true` only when `self` is `Known(e)` and `e == *other`.
165/// An `Unknown` value is never equal to any known variant.
166///
167/// # Asymmetry
168///
169/// Only the `EnumValue == E` direction is available; the reverse `E ==
170/// EnumValue` is not implementable due to the orphan rule. If you need to
171/// compare in that order, use `field.as_known() == Some(variant)` instead.
172impl<E: Enumeration> PartialEq<E> for EnumValue<E> {
173    fn eq(&self, other: &E) -> bool {
174        match self {
175            Self::Known(e) => e == other,
176            Self::Unknown(_) => false,
177        }
178    }
179}
180
181impl<E: Enumeration> fmt::Debug for EnumValue<E> {
182    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183        match self {
184            Self::Known(e) => write!(f, "{:?}", e),
185            Self::Unknown(v) => write!(f, "Unknown({v})"),
186        }
187    }
188}
189
190impl<E: Enumeration> fmt::Display for EnumValue<E> {
191    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192        match self {
193            Self::Known(e) => f.write_str(e.proto_name()),
194            Self::Unknown(v) => write!(f, "{v}"),
195        }
196    }
197}
198
199#[cfg(feature = "json")]
200impl<E: Enumeration> serde::Serialize for EnumValue<E> {
201    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
202        match self {
203            Self::Known(e) => s.serialize_str(e.proto_name()),
204            Self::Unknown(v) => s.serialize_i32(*v),
205        }
206    }
207}
208
209#[cfg(feature = "json")]
210impl<'de, E: Enumeration> serde::Deserialize<'de> for EnumValue<E> {
211    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
212        use crate::json_helpers::EnumJsonErrorReason;
213
214        struct EnumValueVisitor<E>(core::marker::PhantomData<E>);
215
216        impl<'de, E: Enumeration> serde::de::Visitor<'de> for EnumValueVisitor<E> {
217            type Value = EnumValue<E>;
218
219            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220                f.write_str("a protobuf enum name string or integer value")
221            }
222
223            /// Handles JSON `null` input, used for `google.protobuf.NullValue`
224            /// whose JSON representation is the literal `null`.
225            fn visit_unit<Err: serde::de::Error>(self) -> Result<EnumValue<E>, Err> {
226                Ok(EnumValue::from(0))
227            }
228
229            #[cfg(feature = "zeroize")]
230            fn visit_byte_buf<Err: serde::de::Error>(
231                self,
232                value: alloc::vec::Vec<u8>,
233            ) -> Result<Self::Value, Err> {
234                // Preserve Serde's borrowed-byte rejection while wiping the
235                // owned allocation that its default forwarding would release.
236                let value = zeroize::Zeroizing::new(value);
237                self.visit_bytes(&value)
238            }
239            fn visit_str<Err: serde::de::Error>(self, v: &str) -> Result<EnumValue<E>, Err> {
240                match E::from_proto_name(v) {
241                    Some(e) => Ok(EnumValue::Known(e)),
242                    None => {
243                        // Without `std` an unknown name is always an error
244                        // here, even when the process-wide option is set:
245                        // `json_helpers::try_deserialize_enum` needs the error
246                        // to tell an unknown name from the default value.
247                        #[cfg(all(feature = "std", feature = "json"))]
248                        if crate::json::ignore_unknown_enum_values() {
249                            return Ok(EnumValue::from(0));
250                        }
251                        Err(Err::custom(EnumJsonErrorReason::UnknownName))
252                    }
253                }
254            }
255
256            #[cfg(feature = "zeroize")]
257            fn visit_string<Err: serde::de::Error>(
258                self,
259                value: alloc::string::String,
260            ) -> Result<Self::Value, Err> {
261                // Serde transferred this allocation, so wipe it even when
262                // the enum name cannot be resolved.
263                let value = zeroize::Zeroizing::new(value);
264                self.visit_str(&value)
265            }
266
267            fn visit_i64<Err: serde::de::Error>(self, v: i64) -> Result<EnumValue<E>, Err> {
268                let n =
269                    i32::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
270                Ok(EnumValue::from(n))
271            }
272
273            fn visit_u64<Err: serde::de::Error>(self, v: u64) -> Result<EnumValue<E>, Err> {
274                let n =
275                    i32::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
276                Ok(EnumValue::from(n))
277            }
278
279            // Deserializers delivering 128-bit integers, including JSON Values
280            // with arbitrary precision, use checked narrowing to avoid echoing input.
281            fn visit_i128<Err: serde::de::Error>(self, v: i128) -> Result<Self::Value, Err> {
282                let v =
283                    i64::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
284                self.visit_i64(v)
285            }
286
287            fn visit_u128<Err: serde::de::Error>(self, v: u128) -> Result<Self::Value, Err> {
288                let v =
289                    u64::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
290                self.visit_u64(v)
291            }
292
293            fn visit_f64<Err: serde::de::Error>(self, _: f64) -> Result<Self::Value, Err> {
294                Err(Err::custom(EnumJsonErrorReason::InvalidType))
295            }
296
297            fn visit_bool<Err: serde::de::Error>(self, _: bool) -> Result<Self::Value, Err> {
298                Err(Err::custom(EnumJsonErrorReason::InvalidType))
299            }
300        }
301
302        d.deserialize_any(EnumValueVisitor(core::marker::PhantomData))
303    }
304}
305
306impl<E: Enumeration> Default for EnumValue<E> {
307    /// Returns the default value for this enum field.
308    ///
309    /// Per the protobuf specification, the default value for an enum field is
310    /// the variant whose wire value is `0`.  If `0` is not a defined variant of
311    /// `E`, this returns [`EnumValue::Unknown(0)`](EnumValue::Unknown), which is
312    /// the correct protobuf default but may be surprising — the field's default
313    /// is technically an unknown variant.
314    fn default() -> Self {
315        Self::from(0)
316    }
317}
318
319#[cfg(feature = "arbitrary")]
320impl<'a, E: Enumeration + arbitrary::Arbitrary<'a>> arbitrary::Arbitrary<'a> for EnumValue<E> {
321    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
322        // Bias towards known variants (75%) but also generate unknown values
323        // (25%) to exercise unknown-value handling.
324        if u.ratio(3, 4)? {
325            Ok(EnumValue::Known(E::arbitrary(u)?))
326        } else {
327            Ok(EnumValue::Unknown(i32::arbitrary(u)?))
328        }
329    }
330}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335
336    #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
337    enum Color {
338        Red,
339        Green,
340        Blue,
341    }
342
343    impl Enumeration for Color {
344        fn from_i32(v: i32) -> Option<Self> {
345            match v {
346                0 => Some(Color::Red),
347                1 => Some(Color::Green),
348                2 => Some(Color::Blue),
349                _ => None,
350            }
351        }
352        fn to_i32(&self) -> i32 {
353            *self as i32
354        }
355        fn proto_name(&self) -> &'static str {
356            match self {
357                Color::Red => "RED",
358                Color::Green => "GREEN",
359                Color::Blue => "BLUE",
360            }
361        }
362        fn from_proto_name(name: &str) -> Option<Self> {
363            match name {
364                "RED" => Some(Color::Red),
365                "GREEN" => Some(Color::Green),
366                "BLUE" => Some(Color::Blue),
367                _ => None,
368            }
369        }
370    }
371
372    // ---- From<i32> -------------------------------------------------------
373
374    #[test]
375    fn from_i32_known_value_produces_known_variant() {
376        let v: EnumValue<Color> = EnumValue::from(1);
377        assert_eq!(v, EnumValue::Known(Color::Green));
378    }
379
380    #[test]
381    fn from_i32_unknown_values_produce_unknown_variant() {
382        // Values not in Color's variant set (0/1/2) round-trip as Unknown(v).
383        for v in [99, -1, i32::MIN, i32::MAX] {
384            let ev: EnumValue<Color> = EnumValue::from(v);
385            assert_eq!(ev, EnumValue::Unknown(v), "from({v})");
386            assert_eq!(ev.to_i32(), v, "to_i32 roundtrip for {v}");
387        }
388    }
389
390    // ---- From<E> ---------------------------------------------------------
391
392    #[test]
393    fn from_enum_variant_produces_known() {
394        let v = EnumValue::from(Color::Blue);
395        assert_eq!(v, EnumValue::Known(Color::Blue));
396    }
397
398    // ---- to_i32 ----------------------------------------------------------
399
400    #[test]
401    fn to_i32_known_returns_variant_value() {
402        let v = EnumValue::Known(Color::Green);
403        assert_eq!(v.to_i32(), 1);
404    }
405
406    #[test]
407    fn to_i32_unknown_returns_raw_value() {
408        let v: EnumValue<Color> = EnumValue::Unknown(42);
409        assert_eq!(v.to_i32(), 42);
410    }
411
412    #[test]
413    fn to_i32_unknown_negative_returns_raw_value() {
414        let v: EnumValue<Color> = EnumValue::Unknown(-1);
415        assert_eq!(v.to_i32(), -1);
416    }
417
418    // ---- as_known --------------------------------------------------------
419
420    #[test]
421    fn as_known_returns_some_for_known_variant() {
422        let v = EnumValue::Known(Color::Red);
423        assert_eq!(v.as_known(), Some(Color::Red));
424    }
425
426    #[test]
427    fn as_known_returns_none_for_unknown() {
428        let v: EnumValue<Color> = EnumValue::Unknown(7);
429        assert_eq!(v.as_known(), None);
430    }
431
432    // ---- Debug -----------------------------------------------------------
433
434    #[test]
435    fn debug_known_variant_uses_enum_debug() {
436        let v = EnumValue::Known(Color::Blue);
437        assert_eq!(format!("{v:?}"), "Blue");
438    }
439
440    #[test]
441    fn debug_unknown_shows_raw_value() {
442        let v: EnumValue<Color> = EnumValue::Unknown(99);
443        assert_eq!(format!("{v:?}"), "Unknown(99)");
444    }
445
446    // ---- Display ---------------------------------------------------------
447
448    #[test]
449    fn display_known_variant_uses_proto_name() {
450        let v = EnumValue::Known(Color::Green);
451        assert_eq!(format!("{v}"), "GREEN");
452    }
453
454    #[test]
455    fn display_unknown_shows_raw_integer() {
456        let v: EnumValue<Color> = EnumValue::Unknown(99);
457        assert_eq!(format!("{v}"), "99");
458    }
459
460    #[test]
461    fn display_unknown_negative_shows_signed_integer() {
462        let v: EnumValue<Color> = EnumValue::Unknown(-1);
463        assert_eq!(format!("{v}"), "-1");
464    }
465
466    // ---- Default ---------------------------------------------------------
467
468    #[test]
469    fn default_produces_known_when_zero_is_valid() {
470        // Color::Red = 0, so the default should be Known(Red).
471        let v: EnumValue<Color> = EnumValue::default();
472        assert_eq!(v, EnumValue::Known(Color::Red));
473    }
474
475    #[test]
476    fn default_produces_unknown_when_zero_is_not_a_valid_variant() {
477        // An enum whose first valid variant is non-zero.
478        #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
479        enum Status {
480            Active,
481            Inactive,
482        }
483        impl Enumeration for Status {
484            fn from_i32(v: i32) -> Option<Self> {
485                match v {
486                    1 => Some(Status::Active),
487                    2 => Some(Status::Inactive),
488                    _ => None,
489                }
490            }
491            fn to_i32(&self) -> i32 {
492                match self {
493                    Status::Active => 1,
494                    Status::Inactive => 2,
495                }
496            }
497            fn proto_name(&self) -> &'static str {
498                match self {
499                    Status::Active => "ACTIVE",
500                    Status::Inactive => "INACTIVE",
501                }
502            }
503        }
504
505        // Default must be Unknown(0) when 0 is not a valid variant.
506        let v: EnumValue<Status> = EnumValue::default();
507        assert_eq!(v, EnumValue::Unknown(0));
508    }
509
510    // ---- is_known / is_unknown -------------------------------------------
511
512    #[test]
513    fn is_known_returns_true_for_known_variant() {
514        let v = EnumValue::Known(Color::Red);
515        assert!(v.is_known());
516        assert!(!v.is_unknown());
517    }
518
519    #[test]
520    fn is_unknown_returns_true_for_unknown_value() {
521        let v: EnumValue<Color> = EnumValue::Unknown(99);
522        assert!(v.is_unknown());
523        assert!(!v.is_known());
524    }
525
526    // ---- PartialEq<E> ----------------------------------------------------
527
528    #[test]
529    fn known_variant_equals_same_variant() {
530        let v = EnumValue::Known(Color::Green);
531        assert!(v == Color::Green);
532    }
533
534    #[test]
535    fn known_variant_not_equal_to_different_variant() {
536        let v = EnumValue::Known(Color::Red);
537        assert!(!(v == Color::Green));
538    }
539
540    #[test]
541    fn unknown_value_never_equals_known_variant() {
542        // Even if the numeric value matches, Unknown != any known variant.
543        let v: EnumValue<Color> = EnumValue::Unknown(1); // same wire value as Green
544        assert!(!(v == Color::Green));
545    }
546
547    #[test]
548    fn unknown_value_with_out_of_range_int_not_equal() {
549        let v: EnumValue<Color> = EnumValue::Unknown(99);
550        assert!(!(v == Color::Red));
551    }
552
553    // ---- serde -------------------------------------------------------
554
555    #[cfg(feature = "json")]
556    mod serde_tests {
557        use super::*;
558
559        #[test]
560        fn known_variant_serializes_as_proto_name() {
561            let v = EnumValue::Known(Color::Green);
562            assert_eq!(serde_json::to_string(&v).unwrap(), r#""GREEN""#);
563        }
564
565        #[test]
566        fn unknown_variant_serializes_as_integer() {
567            let v: EnumValue<Color> = EnumValue::Unknown(99);
568            assert_eq!(serde_json::to_string(&v).unwrap(), "99");
569        }
570
571        #[test]
572        fn deserialize_table() {
573            use EnumValue::{Known, Unknown};
574            // Some(v) = succeeds with v, None = is_err().
575            #[rustfmt::skip]
576            let cases: &[(&str, Option<EnumValue<Color>>)] = &[
577                (r#""RED""#,    Some(Known(Color::Red))),    // proto name string
578                ("1",           Some(Known(Color::Green))),  // integer (known)
579                ("99",          Some(Unknown(99))),          // integer (unknown)
580                ("null",        Some(Known(Color::Red))),    // null → default (Red = 0)
581                (r#""PURPLE""#, None),                       // unknown string → error
582                ("9223372036854775807", None),               // i64::MAX > i32 → error
583            ];
584            for &(json, expected) in cases {
585                let result = serde_json::from_str::<EnumValue<Color>>(json);
586                assert_eq!(result.ok(), expected, "input: {json}");
587            }
588        }
589
590        #[test]
591        fn deserialize_unknown_string_error_omits_the_value() {
592            let err = serde_json::from_str::<EnumValue<Color>>(r#""PURPLE""#).unwrap_err();
593            assert_eq!(err.to_string(), "unknown enum name at line 1 column 8");
594        }
595
596        #[test]
597        fn deserialize_unknown_string_returns_default_when_lenient() {
598            use crate::json::{with_json_parse_options, JsonParseOptions};
599            let opts = JsonParseOptions {
600                ignore_unknown_enum_values: true,
601                ..Default::default()
602            };
603            let v: EnumValue<Color> =
604                with_json_parse_options(&opts, || serde_json::from_str(r#""PURPLE""#).unwrap());
605            // Unknown string → default enum value (0 = Red).
606            assert_eq!(v, EnumValue::Known(Color::Red));
607        }
608
609        #[test]
610        fn deserialize_known_string_unaffected_by_lenient_mode() {
611            use crate::json::{with_json_parse_options, JsonParseOptions};
612            let opts = JsonParseOptions {
613                ignore_unknown_enum_values: true,
614                ..Default::default()
615            };
616            let v: EnumValue<Color> =
617                with_json_parse_options(&opts, || serde_json::from_str(r#""BLUE""#).unwrap());
618            assert_eq!(v, EnumValue::Known(Color::Blue));
619        }
620
621        #[test]
622        fn round_trip_known_variant() {
623            let original = EnumValue::Known(Color::Blue);
624            let json = serde_json::to_string(&original).unwrap();
625            let recovered: EnumValue<Color> = serde_json::from_str(&json).unwrap();
626            assert_eq!(original, recovered);
627        }
628    }
629}