prost_reflect/dynamic/
mod.rs

1/// Parsing and formatting for the protobuf [text format](https://developers.google.com/protocol-buffers/docs/text-format-spec).
2///
3/// This module contains options for customizing the text format output. See the associated functions [`DynamicMessage::parse_text_format()`] and
4/// [`DynamicMessage::to_text_format()`].
5#[cfg(feature = "text-format")]
6#[cfg_attr(docsrs, doc(cfg(feature = "text-format")))]
7pub mod text_format;
8
9mod fields;
10mod message;
11#[cfg(feature = "serde")]
12mod serde;
13#[cfg(not(feature = "text-format"))]
14mod text_format;
15mod unknown;
16
17use std::{borrow::Cow, collections::HashMap, error::Error, fmt};
18
19#[cfg(feature = "serde")]
20pub use self::serde::{DeserializeOptions, SerializeOptions};
21pub use self::unknown::UnknownField;
22
23pub(crate) use self::fields::FieldDescriptorLike;
24
25use prost::{
26    bytes::{Buf, Bytes},
27    DecodeError, Message,
28};
29
30use self::fields::DynamicMessageFieldSet;
31use crate::{
32    descriptor::Kind, ExtensionDescriptor, FieldDescriptor, MessageDescriptor, ReflectMessage,
33};
34
35/// [`DynamicMessage`] provides encoding, decoding and reflection of a protobuf message.
36///
37/// It wraps a [`MessageDescriptor`] and the [`Value`] for each field of the message, and implements
38/// [`Message`][`prost::Message`].
39#[derive(Debug, Clone, PartialEq)]
40pub struct DynamicMessage {
41    desc: MessageDescriptor,
42    fields: DynamicMessageFieldSet,
43}
44
45/// A dynamically-typed protobuf value.
46///
47/// Note this type may map to multiple possible protobuf wire formats, so it must be
48/// serialized as part of a DynamicMessage.
49#[derive(Debug, Clone, PartialEq)]
50pub enum Value {
51    /// A boolean value, encoded as the `bool` protobuf type.
52    Bool(bool),
53    /// A 32-bit signed integer, encoded as one of the `int32`, `sint32` or `sfixed32` protobuf types.
54    I32(i32),
55    /// A 64-bit signed integer, encoded as one of the `int64`, `sint64` or `sfixed64` protobuf types.
56    I64(i64),
57    /// A 32-bit unsigned integer, encoded as one of the `uint32` or `ufixed32` protobuf types.
58    U32(u32),
59    /// A 64-bit unsigned integer, encoded as one of the `uint64` or `ufixed64` protobuf types.
60    U64(u64),
61    /// A 32-bit floating point number, encoded as the `float` protobuf type.
62    F32(f32),
63    /// A 64-bit floating point number, encoded as the `double` protobuf type.
64    F64(f64),
65    /// A string, encoded as the `string` protobuf type.
66    String(String),
67    /// A byte string, encoded as the `bytes` protobuf type.
68    Bytes(Bytes),
69    /// An enumeration value, encoded as a protobuf enum.
70    EnumNumber(i32),
71    /// A protobuf message.
72    Message(DynamicMessage),
73    /// A list of values, encoded as a protobuf repeated field.
74    List(Vec<Value>),
75    /// A map of values, encoded as a protobuf map field.
76    Map(HashMap<MapKey, Value>),
77}
78
79/// A dynamically-typed key for a protobuf map.
80#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
81pub enum MapKey {
82    /// A boolean value, encoded as the `bool` protobuf type.
83    Bool(bool),
84    /// A 32-bit signed integer, encoded as one of the `int32`, `sint32` or `sfixed32` protobuf types.
85    I32(i32),
86    /// A 64-bit signed integer, encoded as one of the `int64`, `sint64` or `sfixed64` protobuf types.
87    I64(i64),
88    /// A 32-bit unsigned integer, encoded as one of the `uint32` or `ufixed32` protobuf types.
89    U32(u32),
90    /// A 64-bit unsigned integer, encoded as one of the `uint64` or `ufixed64` protobuf types.
91    U64(u64),
92    /// A string, encoded as the `string` protobuf type.
93    String(String),
94}
95
96/// Error type returned by [`DynamicMessage::try_set_field()`].
97#[derive(Debug, Clone, PartialEq)]
98pub enum SetFieldError {
99    /// The field was not found.
100    NotFound,
101    /// The value type was not compatible with the field type (see [`Value::is_valid_for_field`]).
102    InvalidType {
103        /// The descriptor for the field which could not be set.
104        field: FieldDescriptor,
105        /// The invalid value.
106        value: Value,
107    },
108}
109
110impl DynamicMessage {
111    /// Creates a new, empty instance of [`DynamicMessage`] for the message type specified by the [`MessageDescriptor`].
112    pub fn new(desc: MessageDescriptor) -> Self {
113        DynamicMessage {
114            fields: DynamicMessageFieldSet::default(),
115            desc,
116        }
117    }
118
119    /// Decodes an instance of the message type specified by the [`MessageDescriptor`] from the buffer and merges it into a
120    /// new instance of [`DynamicMessage`].
121    ///
122    /// # Examples
123    ///
124    /// ```
125    /// # use prost::Message;
126    /// # use prost_types::FileDescriptorSet;
127    /// # use prost_reflect::{DynamicMessage, DescriptorPool, Value};
128    /// # let pool = DescriptorPool::decode(include_bytes!("../file_descriptor_set.bin").as_ref()).unwrap();
129    /// # let message_descriptor = pool.get_message_by_name("package.MyMessage").unwrap();
130    /// let dynamic_message = DynamicMessage::decode(message_descriptor, b"\x08\x96\x01".as_ref()).unwrap();
131    /// assert_eq!(dynamic_message.get_field_by_name("foo").unwrap().as_ref(), &Value::I32(150));
132    /// ```
133    pub fn decode<B>(desc: MessageDescriptor, buf: B) -> Result<Self, DecodeError>
134    where
135        B: Buf,
136    {
137        let mut message = DynamicMessage::new(desc);
138        message.merge(buf)?;
139        Ok(message)
140    }
141
142    /// Returns `true` if this message has the given field set.
143    ///
144    /// If the field type supports distinguishing whether a value has been set (see [`supports_presence`][FieldDescriptor::supports_presence]),
145    /// such as for messages, then this method returns `true` only if a value has been set. For
146    /// other types, such as integers, it returns `true` if the value is set to a non-default value.
147    ///
148    /// If this method returns `false`, then the field will not be included in the encoded bytes
149    /// of this message.
150    ///
151    /// # Examples
152    ///
153    /// This example uses the following message definition:
154    ///
155    /// ```lang-protobuf
156    /// message MyMessage {
157    ///     int32 foo = 1;
158    ///
159    ///     oneof optional {
160    ///         int32 bar = 2;
161    ///     }
162    /// }
163    /// ```
164    ///
165    /// ```
166    /// # use prost::Message;
167    /// # use prost_types::FileDescriptorSet;
168    /// # use prost_reflect::{DynamicMessage, DescriptorPool, Value};
169    /// # let pool = DescriptorPool::decode(include_bytes!("../file_descriptor_set.bin").as_ref()).unwrap();
170    /// # let message_descriptor = pool.get_message_by_name("package.MyMessage").unwrap();
171    /// let foo = message_descriptor.get_field_by_name("foo").unwrap();
172    /// let bar = message_descriptor.get_field_by_name("bar").unwrap();
173    ///
174    /// assert!(!foo.supports_presence());
175    /// assert!(bar.supports_presence());
176    ///
177    /// let mut dynamic_message = DynamicMessage::new(message_descriptor);
178    /// assert!(!dynamic_message.has_field(&foo));
179    /// assert!(!dynamic_message.has_field(&bar));
180    ///
181    /// dynamic_message.set_field(&foo, Value::I32(0));
182    /// dynamic_message.set_field(&bar, Value::I32(0));
183    /// assert!(!dynamic_message.has_field(&foo));
184    /// assert!(dynamic_message.has_field(&bar));
185    ///
186    /// dynamic_message.set_field(&foo, Value::I32(5));
187    /// dynamic_message.set_field(&bar, Value::I32(6));
188    /// assert!(dynamic_message.has_field(&foo));
189    /// assert!(dynamic_message.has_field(&bar));
190    /// ```
191    pub fn has_field(&self, field_desc: &FieldDescriptor) -> bool {
192        self.fields.has(field_desc)
193    }
194
195    /// Gets the value of the given field, or the default value if it is unset.
196    pub fn get_field(&self, field_desc: &FieldDescriptor) -> Cow<'_, Value> {
197        self.fields.get(field_desc)
198    }
199
200    /// Gets a mutable reference to the value ofthe given field. If the field is not set,
201    /// it is inserted with its default value.
202    pub fn get_field_mut(&mut self, field_desc: &FieldDescriptor) -> &mut Value {
203        self.fields.get_mut(field_desc)
204    }
205
206    /// Sets the value of the given field.
207    ///
208    /// # Panics
209    ///
210    /// This method may panic if the value type is not compatible with the field type, as defined
211    /// by [`Value::is_valid_for_field`]. Consider using [`try_set_field()`](DynamicMessage::try_set_field)
212    /// for a non-panicking version.
213    pub fn set_field(&mut self, field_desc: &FieldDescriptor, value: Value) {
214        self.try_set_field(field_desc, value).unwrap()
215    }
216
217    /// Tries to set the value of the given field, returning an error if the value is an invalid type.
218    ///
219    /// # Examples
220    ///
221    /// ```
222    /// # use prost::Message;
223    /// # use prost_types::FileDescriptorSet;
224    /// # use prost_reflect::{DynamicMessage, DescriptorPool, Value, SetFieldError};
225    /// # let pool = DescriptorPool::decode(include_bytes!("../file_descriptor_set.bin").as_ref()).unwrap();
226    /// # let message_descriptor = pool.get_message_by_name("package.MyMessage").unwrap();
227    /// let mut dynamic_message = DynamicMessage::new(message_descriptor.clone());
228    /// let foo = message_descriptor.get_field_by_name("foo").unwrap();
229    /// assert_eq!(dynamic_message.try_set_field(&foo, Value::I32(5)), Ok(()));
230    /// assert_eq!(dynamic_message.try_set_field(&foo, Value::String("bar".to_owned())), Err(SetFieldError::InvalidType {
231    ///     field: foo,
232    ///     value: Value::String("bar".to_owned()),
233    /// }));
234    /// ```
235    pub fn try_set_field(
236        &mut self,
237        field_desc: &FieldDescriptor,
238        value: Value,
239    ) -> Result<(), SetFieldError> {
240        if value.is_valid_for_field(field_desc) {
241            self.fields.set(field_desc, value);
242            Ok(())
243        } else {
244            Err(SetFieldError::InvalidType {
245                field: field_desc.clone(),
246                value,
247            })
248        }
249    }
250
251    /// Clears the given field.
252    ///
253    /// After calling this method, `has_field` will return false for the field,
254    /// and it will not be included in the encoded bytes of this message.
255    pub fn clear_field(&mut self, field_desc: &FieldDescriptor) {
256        self.fields.clear(field_desc);
257    }
258
259    /// Returns `true` if this message has a field set with the given number.
260    ///
261    /// See [`has_field`][Self::has_field] for more details.
262    pub fn has_field_by_number(&self, number: u32) -> bool {
263        self.desc
264            .get_field(number)
265            .is_some_and(|field_desc| self.has_field(&field_desc))
266    }
267
268    /// Gets the value of the field with the given number, or the default value if it is unset.
269    ///
270    /// If the message has no field with the given number, `None` is returned.
271    ///
272    /// See [`get_field`][Self::get_field] for more details.
273    pub fn get_field_by_number(&self, number: u32) -> Option<Cow<'_, Value>> {
274        self.desc
275            .get_field(number)
276            .map(|field_desc| self.get_field(&field_desc))
277    }
278
279    /// Gets a mutable reference to the value of the field with the given number. If the field
280    /// is not set, it is inserted with its default value.
281    ///
282    /// If the message has no field with the given number, `None` is returned.
283    ///
284    /// See [`get_field_mut`][Self::get_field_mut] for more details.
285    pub fn get_field_by_number_mut(&mut self, number: u32) -> Option<&mut Value> {
286        self.desc
287            .get_field(number)
288            .map(move |field_desc| self.get_field_mut(&field_desc))
289    }
290
291    /// Sets the value of the field with number `number`.
292    ///
293    /// If no field with the given number exists, this method does nothing.
294    ///
295    /// See [`set_field`][Self::set_field] for more details.
296    pub fn set_field_by_number(&mut self, number: u32, value: Value) {
297        if let Some(field_desc) = self.desc.get_field(number) {
298            self.set_field(&field_desc, value)
299        }
300    }
301
302    /// Tries to set the value of the field with number `number`, returning an error if the value is an invalid type or does not exist.
303    ///
304    /// # Examples
305    ///
306    /// ```
307    /// # use prost::Message;
308    /// # use prost_types::FileDescriptorSet;
309    /// # use prost_reflect::{DynamicMessage, DescriptorPool, Value, SetFieldError};
310    /// # let pool = DescriptorPool::decode(include_bytes!("../file_descriptor_set.bin").as_ref()).unwrap();
311    /// # let message_descriptor = pool.get_message_by_name("package.MyMessage").unwrap();
312    /// let mut dynamic_message = DynamicMessage::new(message_descriptor.clone());
313    /// assert_eq!(dynamic_message.try_set_field_by_number(1, Value::I32(5)), Ok(()));
314    /// assert_eq!(dynamic_message.try_set_field_by_number(1, Value::String("bar".to_owned())), Err(SetFieldError::InvalidType {
315    ///     field: message_descriptor.get_field(1).unwrap(),
316    ///     value: Value::String("bar".to_owned()),
317    /// }));
318    /// assert_eq!(dynamic_message.try_set_field_by_number(42, Value::I32(5)), Err(SetFieldError::NotFound));
319    /// ```
320    pub fn try_set_field_by_number(
321        &mut self,
322        number: u32,
323        value: Value,
324    ) -> Result<(), SetFieldError> {
325        if let Some(field_desc) = self.desc.get_field(number) {
326            self.try_set_field(&field_desc, value)
327        } else {
328            Err(SetFieldError::NotFound)
329        }
330    }
331
332    /// Clears the field with the given number.
333    ///
334    /// If no field with the given number exists, this method does nothing.
335    ///
336    /// See [`clear_field`][Self::clear_field] for more details.
337    pub fn clear_field_by_number(&mut self, number: u32) {
338        if let Some(field_desc) = self.desc.get_field(number) {
339            self.clear_field(&field_desc);
340        }
341    }
342
343    /// Returns `true` if this message has a field set with the given name.
344    ///
345    /// See [`has_field`][Self::has_field] for more details.
346    pub fn has_field_by_name(&self, name: &str) -> bool {
347        self.desc
348            .get_field_by_name(name)
349            .is_some_and(|field_desc| self.has_field(&field_desc))
350    }
351
352    /// Gets the value of the field with the given name, or the default value if it is unset.
353    ///
354    /// If the message has no field with the given name, `None` is returned.
355    ///
356    /// See [`get_field`][Self::get_field] for more details.
357    pub fn get_field_by_name(&self, name: &str) -> Option<Cow<'_, Value>> {
358        self.desc
359            .get_field_by_name(name)
360            .map(|field_desc| self.get_field(&field_desc))
361    }
362
363    /// Gets a mutable reference to the value of the field with the given name. If the field
364    /// is not set, it is inserted with its default value.
365    ///
366    /// If the message has no field with the given name, `None` is returned.
367    ///
368    /// See [`get_field_mut`][Self::get_field_mut] for more details.
369    pub fn get_field_by_name_mut(&mut self, name: &str) -> Option<&mut Value> {
370        self.desc
371            .get_field_by_name(name)
372            .map(move |field_desc| self.get_field_mut(&field_desc))
373    }
374
375    /// Sets the value of the field with name `name`.
376    ///
377    /// If no field with the given name exists, this method does nothing.
378    ///
379    /// See [`set_field`][Self::set_field] for more details.
380    pub fn set_field_by_name(&mut self, name: &str, value: Value) {
381        if let Some(field_desc) = self.desc.get_field_by_name(name) {
382            self.set_field(&field_desc, value)
383        }
384    }
385
386    /// Tries to set the value of the field with name `name`, returning an error if the value is an invalid type or does not exist.
387    ///
388    /// # Examples
389    ///
390    /// ```
391    /// # use prost::Message;
392    /// # use prost_types::FileDescriptorSet;
393    /// # use prost_reflect::{DynamicMessage, DescriptorPool, Value, SetFieldError};
394    /// # let pool = DescriptorPool::decode(include_bytes!("../file_descriptor_set.bin").as_ref()).unwrap();
395    /// # let message_descriptor = pool.get_message_by_name("package.MyMessage").unwrap();
396    /// let mut dynamic_message = DynamicMessage::new(message_descriptor.clone());
397    /// assert_eq!(dynamic_message.try_set_field_by_name("foo", Value::I32(5)), Ok(()));
398    /// assert_eq!(dynamic_message.try_set_field_by_name("foo", Value::String("bar".to_owned())), Err(SetFieldError::InvalidType {
399    ///     field: message_descriptor.get_field_by_name("foo").unwrap(),
400    ///     value: Value::String("bar".to_owned()),
401    /// }));
402    /// assert_eq!(dynamic_message.try_set_field_by_name("notfound", Value::I32(5)), Err(SetFieldError::NotFound));
403    /// ```
404    pub fn try_set_field_by_name(&mut self, name: &str, value: Value) -> Result<(), SetFieldError> {
405        if let Some(field_desc) = self.desc.get_field_by_name(name) {
406            self.try_set_field(&field_desc, value)
407        } else {
408            Err(SetFieldError::NotFound)
409        }
410    }
411
412    /// Clears the field with the given name.
413    ///
414    /// If no field with the given name exists, this method does nothing.
415    ///
416    /// See [`clear_field`][Self::clear_field] for more details.
417    pub fn clear_field_by_name(&mut self, name: &str) {
418        if let Some(field_desc) = self.desc.get_field_by_name(name) {
419            self.clear_field(&field_desc);
420        }
421    }
422
423    /// Clears the value for the given field, and returns it.
424    ///
425    /// Returns the value if [`has_field`](Self::has_field) was `true`, or `None` otherwise.
426    pub fn take_field(&mut self, field_desc: &FieldDescriptor) -> Option<Value> {
427        self.fields.take(field_desc)
428    }
429
430    /// Clears the value for the field with the given name, and returns it.
431    ///
432    /// Returns the value if [`has_field_by_name`](Self::has_field_by_name) was `true`, or `None` otherwise.
433    pub fn take_field_by_name(&mut self, name: &str) -> Option<Value> {
434        if let Some(field_desc) = self.desc.get_field_by_name(name) {
435            self.fields.take(&field_desc)
436        } else {
437            None
438        }
439    }
440
441    /// Clears the value for the field with the given number, and returns it.
442    ///
443    /// Returns the value if [`has_field_by_number`](Self::has_field_by_number) was `true`, or `None` otherwise.
444    pub fn take_field_by_number(&mut self, number: u32) -> Option<Value> {
445        if let Some(field_desc) = self.desc.get_field(number) {
446            self.fields.take(&field_desc)
447        } else {
448            None
449        }
450    }
451
452    /// Returns `true` if this message has the given extension field set.
453    ///
454    /// See [`has_field`][Self::has_field] for more details.
455    pub fn has_extension(&self, extension_desc: &ExtensionDescriptor) -> bool {
456        self.fields.has(extension_desc)
457    }
458
459    /// Gets the value of the given extension field, or the default value if it is unset.
460    ///
461    /// See [`get_field`][Self::get_field] for more details.
462    pub fn get_extension(&self, extension_desc: &ExtensionDescriptor) -> Cow<'_, Value> {
463        self.fields.get(extension_desc)
464    }
465
466    /// Gets a mutable reference to the value of the given extension field. If the
467    /// field is not set, it is inserted with its default value.
468    ///
469    /// See [`get_field_mut`][Self::get_field_mut] for more details.
470    pub fn get_extension_mut(&mut self, extension_desc: &ExtensionDescriptor) -> &mut Value {
471        self.fields.get_mut(extension_desc)
472    }
473
474    /// Sets the value of the given extension field.
475    ///
476    /// See [`set_field`][Self::set_field] for more details.
477    pub fn set_extension(&mut self, extension_desc: &ExtensionDescriptor, value: Value) {
478        self.fields.set(extension_desc, value)
479    }
480
481    /// Clears the given extension field.
482    ///
483    /// See [`clear_field`][Self::clear_field] for more details.
484    pub fn clear_extension(&mut self, extension_desc: &ExtensionDescriptor) {
485        self.fields.clear(extension_desc)
486    }
487
488    /// Clears the value for the given extension field, and returns it.
489    ///
490    /// Returns the value if [`has_extension`](Self::has_extension) was `true`, or `None` otherwise.
491    pub fn take_extension(&mut self, extension_desc: &ExtensionDescriptor) -> Option<Value> {
492        self.fields.take(extension_desc)
493    }
494
495    /// Gets an iterator over all fields of this message.
496    ///
497    /// The iterator will yield all fields for which [`has_field`](Self::has_field) returns `true`.
498    pub fn fields(&self) -> impl Iterator<Item = (FieldDescriptor, &'_ Value)> {
499        self.fields.iter_fields(&self.desc)
500    }
501
502    /// Gets an iterator returning mutable references to all fields of this message.
503    ///
504    /// The iterator will yield all fields for which [`has_field`](Self::has_field) returns `true`.
505    pub fn fields_mut(&mut self) -> impl Iterator<Item = (FieldDescriptor, &'_ mut Value)> {
506        self.fields.iter_fields_mut(&self.desc)
507    }
508
509    /// Clears all fields from the message and returns an iterator yielding the values.
510    ///
511    /// The iterator will yield all fields for which [`has_field`](Self::has_field) returns `true`.
512    ///
513    /// If the iterator is dropped before completing the iteration, it is unspecified how many fields are removed.
514    pub fn take_fields(&mut self) -> impl Iterator<Item = (FieldDescriptor, Value)> + '_ {
515        self.fields.take_fields(&self.desc)
516    }
517
518    /// Gets an iterator over all extension fields of this message.
519    ///
520    /// The iterator will yield all extension fields for which [`has_extension`](Self::has_extension) returns `true`.
521    pub fn extensions(&self) -> impl Iterator<Item = (ExtensionDescriptor, &'_ Value)> {
522        self.fields.iter_extensions(&self.desc)
523    }
524
525    /// Gets an iterator returning mutable references to all extension fields of this message.
526    ///
527    /// The iterator will yield all extension fields for which [`has_extension`](Self::has_extension) returns `true`.
528    pub fn extensions_mut(&mut self) -> impl Iterator<Item = (ExtensionDescriptor, &'_ mut Value)> {
529        self.fields.iter_extensions_mut(&self.desc)
530    }
531
532    /// Clears all extension fields from the message and returns an iterator yielding the values.
533    ///
534    /// The iterator will yield all extension fields for which [`has_extension`](Self::has_extension) returns `true`.
535    ///
536    /// If the iterator is dropped before completing the iteration, it is unspecified how many fields are removed.
537    pub fn take_extensions(&mut self) -> impl Iterator<Item = (ExtensionDescriptor, Value)> + '_ {
538        self.fields.take_extensions(&self.desc)
539    }
540
541    /// Gets an iterator over unknown fields for this message.
542    ///
543    /// A field is unknown if the message descriptor does not contain a field with the given number. This is often the
544    /// result of a new field being added to the message definition.
545    ///
546    /// Unknown fields are preserved when decoding and re-encoding a message.
547    pub fn unknown_fields(&self) -> impl Iterator<Item = &'_ UnknownField> {
548        self.fields.iter_unknown()
549    }
550
551    /// Clears all unknown fields from the message and returns an iterator yielding the values.
552    ///
553    /// If the iterator is dropped before completing the iteration, it is unspecified how many fields are removed.
554    pub fn take_unknown_fields(&mut self) -> impl Iterator<Item = UnknownField> + '_ {
555        self.fields.take_unknown()
556    }
557
558    /// Merge a strongly-typed message into this one.
559    ///
560    /// The message should be compatible with the type specified by
561    /// [`descriptor`][Self::descriptor], or the merge will likely fail with
562    /// a [`DecodeError`].
563    pub fn transcode_from<T>(&mut self, value: &T) -> Result<(), DecodeError>
564    where
565        T: Message,
566    {
567        let buf = value.encode_to_vec();
568        self.merge(buf.as_slice())
569    }
570
571    /// Convert this dynamic message into a strongly typed value.
572    ///
573    /// The message should be compatible with the type specified by
574    /// [`descriptor`][Self::descriptor], or the conversion will likely fail with
575    /// a [`DecodeError`].
576    pub fn transcode_to<T>(&self) -> Result<T, DecodeError>
577    where
578        T: Message + Default,
579    {
580        let buf = self.encode_to_vec();
581        T::decode(buf.as_slice())
582    }
583}
584
585impl ReflectMessage for DynamicMessage {
586    fn descriptor(&self) -> MessageDescriptor {
587        self.desc.clone()
588    }
589
590    fn transcode_to_dynamic(&self) -> DynamicMessage
591    where
592        Self: Sized,
593    {
594        self.clone()
595    }
596}
597
598impl Value {
599    /// Returns the default value for the given protobuf field.
600    ///
601    /// This is equivalent to [`default_value`][Value::default_value] except for the following cases:
602    ///
603    /// * If the field is a map, an empty map is returned.
604    /// * If the field is `repeated`, an empty list is returned.
605    /// * If the field has a custom default value specified, that is returned (proto2 only).
606    pub fn default_value_for_field(field_desc: &FieldDescriptor) -> Self {
607        if field_desc.is_list() {
608            Value::List(Vec::default())
609        } else if field_desc.is_map() {
610            Value::Map(HashMap::default())
611        } else if let Some(default_value) = field_desc.default_value() {
612            default_value.clone()
613        } else {
614            Self::default_value(&field_desc.kind())
615        }
616    }
617
618    /// Returns the default value for the given protobuf extension field.
619    ///
620    /// See [`default_value_for_field`][Value::default_value_for_field] for more details.
621    pub fn default_value_for_extension(extension_desc: &ExtensionDescriptor) -> Self {
622        if extension_desc.is_list() {
623            Value::List(Vec::default())
624        } else if extension_desc.is_map() {
625            Value::Map(HashMap::default())
626        } else if let Some(default_value) = extension_desc.default_value() {
627            default_value.clone()
628        } else {
629            Self::default_value(&extension_desc.kind())
630        }
631    }
632
633    /// Returns the default value for the given protobuf type `kind`.
634    ///
635    /// Unlike [`default_value_for_field`](Value::default_value_for_field), this method does not
636    /// look at field cardinality, so it will never return a list or map.
637    pub fn default_value(kind: &Kind) -> Self {
638        match kind {
639            Kind::Message(desc) => Value::Message(DynamicMessage::new(desc.clone())),
640            Kind::Enum(enum_ty) => Value::EnumNumber(enum_ty.default_value().number()),
641            Kind::Double => Value::F64(0.0),
642            Kind::Float => Value::F32(0.0),
643            Kind::Int32 | Kind::Sint32 | Kind::Sfixed32 => Value::I32(0),
644            Kind::Int64 | Kind::Sint64 | Kind::Sfixed64 => Value::I64(0),
645            Kind::Uint32 | Kind::Fixed32 => Value::U32(0),
646            Kind::Uint64 | Kind::Fixed64 => Value::U64(0),
647            Kind::Bool => Value::Bool(false),
648            Kind::String => Value::String(String::default()),
649            Kind::Bytes => Value::Bytes(Bytes::default()),
650        }
651    }
652
653    /// Returns `true` if this is the default value for the given protobuf field.
654    pub fn is_default_for_field(&self, field_desc: &FieldDescriptor) -> bool {
655        *self == Value::default_value_for_field(field_desc)
656    }
657
658    /// Returns `true` if this is the default value for the given protobuf extension field.
659    pub fn is_default_for_extension(&self, extension_desc: &ExtensionDescriptor) -> bool {
660        *self == Value::default_value_for_extension(extension_desc)
661    }
662
663    /// Returns `true` if this is the default value for the given protobuf type `kind`.
664    pub fn is_default(&self, kind: &Kind) -> bool {
665        *self == Value::default_value(kind)
666    }
667
668    /// Returns `true` if this value can be set for a given field.
669    ///
670    /// Note this only checks if the value can be successfully encoded. It doesn't
671    /// check, for example, that enum values are in the defined range.
672    pub fn is_valid_for_field(&self, field_desc: &FieldDescriptor) -> bool {
673        match (self, field_desc.kind()) {
674            (Value::List(list), kind) if field_desc.is_list() => {
675                list.iter().all(|value| value.is_valid(&kind))
676            }
677            (Value::Map(map), Kind::Message(message_desc)) if field_desc.is_map() => {
678                let key_desc = message_desc.map_entry_key_field().kind();
679                let value_desc = message_desc.map_entry_value_field();
680                map.iter().all(|(key, value)| {
681                    key.is_valid(&key_desc) && value.is_valid_for_field(&value_desc)
682                })
683            }
684            (value, kind) => value.is_valid(&kind),
685        }
686    }
687
688    /// Returns `true` if this value can be set for a given extension field.
689    ///
690    /// See [`is_valid_for_field`][Value::is_valid_for_field] for more details.
691    pub fn is_valid_for_extension(&self, extension_desc: &ExtensionDescriptor) -> bool {
692        match (self, extension_desc.kind()) {
693            (Value::List(list), kind) if extension_desc.is_list() => {
694                list.iter().all(|value| value.is_valid(&kind))
695            }
696            (Value::Map(map), Kind::Message(message_desc)) if extension_desc.is_map() => {
697                let key_desc = message_desc.map_entry_key_field().kind();
698                let value_desc = message_desc.map_entry_value_field();
699                map.iter().all(|(key, value)| {
700                    key.is_valid(&key_desc) && value.is_valid_for_field(&value_desc)
701                })
702            }
703            (value, kind) => value.is_valid(&kind),
704        }
705    }
706
707    /// Returns `true` if this value can be encoded as the given [`Kind`].
708    ///
709    /// Unlike [`is_valid_for_field`](Value::is_valid_for_field), this method does not
710    /// look at field cardinality, so it will never return `true` for lists or maps.
711    pub fn is_valid(&self, kind: &Kind) -> bool {
712        matches!(
713            (self, kind),
714            (Value::Bool(_), Kind::Bool)
715                | (Value::I32(_), Kind::Int32 | Kind::Sint32 | Kind::Sfixed32)
716                | (Value::I64(_), Kind::Int64 | Kind::Sint64 | Kind::Sfixed64)
717                | (Value::U32(_), Kind::Uint32 | Kind::Fixed32)
718                | (Value::U64(_), Kind::Uint64 | Kind::Fixed64)
719                | (Value::F32(_), Kind::Float)
720                | (Value::F64(_), Kind::Double)
721                | (Value::String(_), Kind::String)
722                | (Value::Bytes(_), Kind::Bytes)
723                | (Value::EnumNumber(_), Kind::Enum(_))
724                | (Value::Message(_), Kind::Message(_))
725        )
726    }
727
728    /// Returns the value if it is a `Value::Bool`, or `None` if it is any other type.
729    pub fn as_bool(&self) -> Option<bool> {
730        match *self {
731            Value::Bool(value) => Some(value),
732            _ => None,
733        }
734    }
735
736    /// Returns a mutable reference to the value if it is a `Value::Bool`, or `None` if it is any other type.
737    pub fn as_bool_mut(&mut self) -> Option<&mut bool> {
738        match self {
739            Value::Bool(value) => Some(value),
740            _ => None,
741        }
742    }
743
744    /// Returns the value if it is a `Value::U32`, or `None` if it is any other type.
745    pub fn as_u32(&self) -> Option<u32> {
746        match *self {
747            Value::U32(value) => Some(value),
748            _ => None,
749        }
750    }
751
752    /// Returns a mutable reference to the value if it is a `Value::U32`, or `None` if it is any other type.
753    pub fn as_u32_mut(&mut self) -> Option<&mut u32> {
754        match self {
755            Value::U32(value) => Some(value),
756            _ => None,
757        }
758    }
759
760    /// Returns the value if it is a `Value::U64`, or `None` if it is any other type.
761    pub fn as_u64(&self) -> Option<u64> {
762        match *self {
763            Value::U64(value) => Some(value),
764            _ => None,
765        }
766    }
767
768    /// Returns a mutable reference to the value if it is a `Value::U64`, or `None` if it is any other type.
769    pub fn as_u64_mut(&mut self) -> Option<&mut u64> {
770        match self {
771            Value::U64(value) => Some(value),
772            _ => None,
773        }
774    }
775
776    /// Returns the value if it is a `Value::I64`, or `None` if it is any other type.
777    pub fn as_i64(&self) -> Option<i64> {
778        match *self {
779            Value::I64(value) => Some(value),
780            _ => None,
781        }
782    }
783
784    /// Returns a mutable reference to the value if it is a `Value::I64`, or `None` if it is any other type.
785    pub fn as_i64_mut(&mut self) -> Option<&mut i64> {
786        match self {
787            Value::I64(value) => Some(value),
788            _ => None,
789        }
790    }
791
792    /// Returns the value if it is a `Value::I32`, or `None` if it is any other type.
793    pub fn as_i32(&self) -> Option<i32> {
794        match *self {
795            Value::I32(value) => Some(value),
796            _ => None,
797        }
798    }
799
800    /// Returns a mutable reference to the value if it is a `Value::I32`, or `None` if it is any other type.
801    pub fn as_i32_mut(&mut self) -> Option<&mut i32> {
802        match self {
803            Value::I32(value) => Some(value),
804            _ => None,
805        }
806    }
807
808    /// Returns the value if it is a `Value::F32`, or `None` if it is any other type.
809    pub fn as_f32(&self) -> Option<f32> {
810        match *self {
811            Value::F32(value) => Some(value),
812            _ => None,
813        }
814    }
815
816    /// Returns a mutable reference to the value if it is a `Value::F32`, or `None` if it is any other type.
817    pub fn as_f32_mut(&mut self) -> Option<&mut f32> {
818        match self {
819            Value::F32(value) => Some(value),
820            _ => None,
821        }
822    }
823
824    /// Returns the value if it is a `Value::F64`, or `None` if it is any other type.
825    pub fn as_f64(&self) -> Option<f64> {
826        match *self {
827            Value::F64(value) => Some(value),
828            _ => None,
829        }
830    }
831
832    /// Returns a mutable reference to the value if it is a `Value::F64`, or `None` if it is any other type.
833    pub fn as_f64_mut(&mut self) -> Option<&mut f64> {
834        match self {
835            Value::F64(value) => Some(value),
836            _ => None,
837        }
838    }
839
840    /// Returns the value if it is a `Value::EnumNumber`, or `None` if it is any other type.
841    pub fn as_enum_number(&self) -> Option<i32> {
842        match *self {
843            Value::EnumNumber(value) => Some(value),
844            _ => None,
845        }
846    }
847
848    /// Returns a mutable reference to the value if it is a `Value::EnumNumber`, or `None` if it is any other type.
849    pub fn as_enum_number_mut(&mut self) -> Option<&mut i32> {
850        match self {
851            Value::EnumNumber(value) => Some(value),
852            _ => None,
853        }
854    }
855
856    /// Returns the value if it is a `Value::String`, or `None` if it is any other type.
857    pub fn as_str(&self) -> Option<&str> {
858        match self {
859            Value::String(value) => Some(value),
860            _ => None,
861        }
862    }
863
864    /// Returns a mutable reference to the value if it is a `Value::String`, or `None` if it is any other type.
865    pub fn as_string_mut(&mut self) -> Option<&mut String> {
866        match self {
867            Value::String(value) => Some(value),
868            _ => None,
869        }
870    }
871
872    /// Returns the value if it is a `Value::Bytes`, or `None` if it is any other type.
873    pub fn as_bytes(&self) -> Option<&Bytes> {
874        match self {
875            Value::Bytes(value) => Some(value),
876            _ => None,
877        }
878    }
879
880    /// Returns a mutable reference to the value if it is a `Value::Bytes`, or `None` if it is any other type.
881    pub fn as_bytes_mut(&mut self) -> Option<&mut Bytes> {
882        match self {
883            Value::Bytes(value) => Some(value),
884            _ => None,
885        }
886    }
887
888    /// Returns a a reference to the value if it is a `Value::Message`, or `None` if it is any other type.
889    pub fn as_message(&self) -> Option<&DynamicMessage> {
890        match self {
891            Value::Message(value) => Some(value),
892            _ => None,
893        }
894    }
895
896    /// Returns a mutable reference to the value if it is a `Value::Message`, or `None` if it is any other type.
897    pub fn as_message_mut(&mut self) -> Option<&mut DynamicMessage> {
898        match self {
899            Value::Message(value) => Some(value),
900            _ => None,
901        }
902    }
903
904    /// Returns a a reference to the value if it is a `Value::List`, or `None` if it is any other type.
905    pub fn as_list(&self) -> Option<&[Value]> {
906        match self {
907            Value::List(value) => Some(value),
908            _ => None,
909        }
910    }
911
912    /// Returns a mutable reference to the value if it is a `Value::List`, or `None` if it is any other type.
913    pub fn as_list_mut(&mut self) -> Option<&mut Vec<Value>> {
914        match self {
915            Value::List(value) => Some(value),
916            _ => None,
917        }
918    }
919
920    /// Returns a a reference to the value if it is a `Value::Map`, or `None` if it is any other type.
921    pub fn as_map(&self) -> Option<&HashMap<MapKey, Value>> {
922        match self {
923            Value::Map(value) => Some(value),
924            _ => None,
925        }
926    }
927
928    /// Returns a mutable reference to the value if it is a `Value::Map`, or `None` if it is any other type.
929    pub fn as_map_mut(&mut self) -> Option<&mut HashMap<MapKey, Value>> {
930        match self {
931            Value::Map(value) => Some(value),
932            _ => None,
933        }
934    }
935
936    /// Converts this value into a [`MapKey`], or `None` if it is not a valid map key type.
937    ///
938    /// # Examples
939    ///
940    /// ```
941    /// # use prost_reflect::{Value, MapKey, bytes::Bytes};
942    /// assert_eq!(Value::I32(5).into_map_key(), Some(MapKey::I32(5)));
943    /// assert_eq!(Value::String("foo".to_owned()).into_map_key(), Some(MapKey::String("foo".to_owned())));
944    /// assert_eq!(Value::Bytes(Bytes::from_static(b"bytes")).into_map_key(), None);
945    /// ```
946    pub fn into_map_key(self) -> Option<MapKey> {
947        match self {
948            Value::Bool(value) => Some(MapKey::Bool(value)),
949            Value::I32(value) => Some(MapKey::I32(value)),
950            Value::I64(value) => Some(MapKey::I64(value)),
951            Value::U32(value) => Some(MapKey::U32(value)),
952            Value::U64(value) => Some(MapKey::U64(value)),
953            Value::String(value) => Some(MapKey::String(value)),
954            _ => None,
955        }
956    }
957}
958
959impl MapKey {
960    /// Returns the default value for the given protobuf type `kind`.
961    ///
962    /// # Panics
963    ///
964    /// Panics if `kind` is not a valid map key type (an integral type or string).
965    pub fn default_value(kind: &Kind) -> Self {
966        match *kind {
967            Kind::Int32 | Kind::Sint32 | Kind::Sfixed32 => MapKey::I32(0),
968            Kind::Int64 | Kind::Sint64 | Kind::Sfixed64 => MapKey::I64(0),
969            Kind::Uint32 | Kind::Fixed32 => MapKey::U32(0),
970            Kind::Uint64 | Kind::Fixed64 => MapKey::U64(0),
971            Kind::Bool => MapKey::Bool(false),
972            Kind::String => MapKey::String(String::default()),
973            _ => panic!("invalid type for map key"),
974        }
975    }
976
977    /// Returns `true` if this is the default value for the given protobuf type `kind`.
978    ///
979    /// # Panics
980    ///
981    /// Panics if `kind` is not a valid map key type (an integral type or string).
982    pub fn is_default(&self, kind: &Kind) -> bool {
983        *self == MapKey::default_value(kind)
984    }
985
986    /// Returns `true` if this map key can be encoded as the given [`Kind`].
987    pub fn is_valid(&self, kind: &Kind) -> bool {
988        matches!(
989            (self, kind),
990            (MapKey::Bool(_), Kind::Bool)
991                | (MapKey::I32(_), Kind::Int32 | Kind::Sint32 | Kind::Sfixed32)
992                | (MapKey::I64(_), Kind::Int64 | Kind::Sint64 | Kind::Sfixed64)
993                | (MapKey::U32(_), Kind::Uint32 | Kind::Fixed32)
994                | (MapKey::U64(_), Kind::Uint64 | Kind::Fixed64)
995                | (MapKey::String(_), Kind::String)
996        )
997    }
998
999    /// Returns the value if it is a `MapKey::Bool`, or `None` if it is any other type.
1000    pub fn as_bool(&self) -> Option<bool> {
1001        match *self {
1002            MapKey::Bool(value) => Some(value),
1003            _ => None,
1004        }
1005    }
1006
1007    /// Returns a mutable reference to the value if it is a `MapKey::Bool`, or `None` if it is any other type.
1008    pub fn as_bool_mut(&mut self) -> Option<&mut bool> {
1009        match self {
1010            MapKey::Bool(value) => Some(value),
1011            _ => None,
1012        }
1013    }
1014
1015    /// Returns the value if it is a `MapKey::U32`, or `None` if it is any other type.
1016    pub fn as_u32(&self) -> Option<u32> {
1017        match *self {
1018            MapKey::U32(value) => Some(value),
1019            _ => None,
1020        }
1021    }
1022
1023    /// Returns a mutable reference to the value if it is a `MapKey::U32`, or `None` if it is any other type.
1024    pub fn as_u32_mut(&mut self) -> Option<&mut u32> {
1025        match self {
1026            MapKey::U32(value) => Some(value),
1027            _ => None,
1028        }
1029    }
1030
1031    /// Returns the value if it is a `MapKey::U64`, or `None` if it is any other type.
1032    pub fn as_u64(&self) -> Option<u64> {
1033        match *self {
1034            MapKey::U64(value) => Some(value),
1035            _ => None,
1036        }
1037    }
1038
1039    /// Returns a mutable reference to the value if it is a `MapKey::U64`, or `None` if it is any other type.
1040    pub fn as_u64_mut(&mut self) -> Option<&mut u64> {
1041        match self {
1042            MapKey::U64(value) => Some(value),
1043            _ => None,
1044        }
1045    }
1046
1047    /// Returns the value if it is a `MapKey::I64`, or `None` if it is any other type.
1048    pub fn as_i64(&self) -> Option<i64> {
1049        match *self {
1050            MapKey::I64(value) => Some(value),
1051            _ => None,
1052        }
1053    }
1054
1055    /// Returns a mutable reference to the value if it is a `MapKey::I64`, or `None` if it is any other type.
1056    pub fn as_i64_mut(&mut self) -> Option<&mut i64> {
1057        match self {
1058            MapKey::I64(value) => Some(value),
1059            _ => None,
1060        }
1061    }
1062
1063    /// Returns the value if it is a `MapKey::I32`, or `None` if it is any other type.
1064    pub fn as_i32(&self) -> Option<i32> {
1065        match *self {
1066            MapKey::I32(value) => Some(value),
1067            _ => None,
1068        }
1069    }
1070
1071    /// Returns a mutable reference to the value if it is a `MapKey::I32`, or `None` if it is any other type.
1072    pub fn as_i32_mut(&mut self) -> Option<&mut i32> {
1073        match self {
1074            MapKey::I32(value) => Some(value),
1075            _ => None,
1076        }
1077    }
1078
1079    /// Returns the value if it is a `MapKey::String`, or `None` if it is any other type.
1080    pub fn as_str(&self) -> Option<&str> {
1081        match self {
1082            MapKey::String(value) => Some(value),
1083            _ => None,
1084        }
1085    }
1086
1087    /// Returns a mutable reference to the value if it is a `MapKey::String`, or `None` if it is any other type.
1088    pub fn as_string_mut(&mut self) -> Option<&mut String> {
1089        match self {
1090            MapKey::String(value) => Some(value),
1091            _ => None,
1092        }
1093    }
1094}
1095
1096impl From<MapKey> for Value {
1097    fn from(value: MapKey) -> Self {
1098        match value {
1099            MapKey::Bool(value) => Value::Bool(value),
1100            MapKey::I32(value) => Value::I32(value),
1101            MapKey::I64(value) => Value::I64(value),
1102            MapKey::U32(value) => Value::U32(value),
1103            MapKey::U64(value) => Value::U64(value),
1104            MapKey::String(value) => Value::String(value),
1105        }
1106    }
1107}
1108
1109impl fmt::Display for SetFieldError {
1110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1111        match self {
1112            SetFieldError::NotFound => write!(f, "field not found"),
1113            SetFieldError::InvalidType { field, value } => {
1114                write!(f, "expected a value of type '")?;
1115                if field.is_map() {
1116                    let entry = field.kind();
1117                    let entry = entry.as_message().unwrap();
1118                    write!(
1119                        f,
1120                        "map<{:?}, {:?}>",
1121                        entry.map_entry_key_field().kind(),
1122                        entry.map_entry_value_field().kind()
1123                    )?;
1124                } else if field.is_list() {
1125                    write!(f, "repeated {:?}", field.kind())?;
1126                } else {
1127                    write!(f, "{:?}", field.kind())?;
1128                }
1129                write!(f, "', but found '{}'", value)
1130            }
1131        }
1132    }
1133}
1134
1135impl Error for SetFieldError {}
1136
1137pub(crate) fn fmt_string(f: &mut impl fmt::Write, bytes: &[u8]) -> fmt::Result {
1138    f.write_char('"')?;
1139    for &ch in bytes {
1140        match ch {
1141            b'\t' => f.write_str("\\t")?,
1142            b'\r' => f.write_str("\\r")?,
1143            b'\n' => f.write_str("\\n")?,
1144            b'\\' => f.write_str("\\\\")?,
1145            b'\'' => f.write_str("\\'")?,
1146            b'"' => f.write_str("\\\"")?,
1147            b'\x20'..=b'\x7e' => f.write_char(ch as char)?,
1148            _ => {
1149                write!(f, "\\{:03o}", ch)?;
1150            }
1151        }
1152    }
1153    f.write_char('"')
1154}
1155
1156impl fmt::Display for DynamicMessage {
1157    /// Formats this message using the protobuf text format.
1158    ///
1159    /// # Examples
1160    ///
1161    /// ```
1162    /// # use prost::Message;
1163    /// # use prost_types::FileDescriptorSet;
1164    /// # use prost_reflect::{DynamicMessage, DescriptorPool, Value};
1165    /// # let pool = DescriptorPool::decode(include_bytes!("../file_descriptor_set.bin").as_ref()).unwrap();
1166    /// # let message_descriptor = pool.get_message_by_name("package.MyMessage").unwrap();
1167    /// let dynamic_message = DynamicMessage::decode(message_descriptor, b"\x08\x96\x01\x1a\x02\x10\x42".as_ref()).unwrap();
1168    /// assert_eq!(format!("{}", dynamic_message), "foo:150,nested{bar:66}");
1169    /// // The alternate format specifier may be used to pretty-print the output
1170    /// assert_eq!(format!("{:#}", dynamic_message), "foo: 150\nnested {\n  bar: 66\n}");
1171    /// ```
1172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1173        text_format::Writer::new(text_format::FormatOptions::new().pretty(f.alternate()), f)
1174            .fmt_message(self)
1175    }
1176}
1177
1178impl fmt::Display for Value {
1179    /// Formats this value using the protobuf text format.
1180    ///
1181    /// # Examples
1182    ///
1183    /// ```
1184    /// # use std::{collections::HashMap, iter::FromIterator};
1185    /// # use prost_reflect::{MapKey, Value};
1186    /// assert_eq!(format!("{}", Value::String("hello".to_owned())), "\"hello\"");
1187    /// assert_eq!(format!("{}", Value::List(vec![Value::I32(1), Value::I32(2)])), "[1,2]");
1188    /// assert_eq!(format!("{}", Value::Map(HashMap::from_iter([(MapKey::I32(1), Value::U32(2))]))), "[{key:1,value:2}]");
1189    /// // The alternate format specifier may be used to indent the output
1190    /// assert_eq!(format!("{:#}", Value::Map(HashMap::from_iter([(MapKey::I32(1), Value::U32(2))]))), "[{\n  key: 1\n  value: 2\n}]");
1191    /// ```
1192    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1193        text_format::Writer::new(text_format::FormatOptions::new().pretty(f.alternate()), f)
1194            .fmt_value(self, None)
1195    }
1196}
1197
1198#[test]
1199fn type_sizes() {
1200    assert_eq!(std::mem::size_of::<DynamicMessage>(), 40);
1201    assert_eq!(std::mem::size_of::<Value>(), 56);
1202}
1203
1204pub(crate) enum Either<L, R> {
1205    Left(L),
1206    Right(R),
1207}
1208
1209impl<L: Iterator, R: Iterator<Item = L::Item>> Iterator for Either<L, R> {
1210    type Item = L::Item;
1211
1212    fn next(&mut self) -> Option<Self::Item> {
1213        match self {
1214            Either::Left(left) => left.next(),
1215            Either::Right(right) => right.next(),
1216        }
1217    }
1218}
1219
1220fn get_type_url_message_name(type_url: &str) -> Result<&str, String> {
1221    let (_type_domain_name, message_name) = type_url
1222        .rsplit_once('/')
1223        .ok_or_else(|| format!("unsupported type url '{type_url}': missing at least one '/'",))?;
1224
1225    Ok(message_name)
1226}
1227
1228#[test]
1229fn test_get_type_url_message_name() {
1230    assert_eq!(
1231        get_type_url_message_name("type.googleapis.com/my.messages.Message"),
1232        Ok("my.messages.Message")
1233    );
1234    assert_eq!(
1235        get_type_url_message_name("type.googleprod.com/my.messages.Message"),
1236        Ok("my.messages.Message")
1237    );
1238    assert_eq!(
1239        get_type_url_message_name("/my.messages.Message"),
1240        Ok("my.messages.Message")
1241    );
1242    assert_eq!(
1243        get_type_url_message_name("any.url.com/my.messages.Message"),
1244        Ok("my.messages.Message")
1245    );
1246    assert_eq!(
1247        get_type_url_message_name("http://even.multiple/slashes/my.messages.Message"),
1248        Ok("my.messages.Message")
1249    );
1250    assert_eq!(
1251        get_type_url_message_name("/any.type.isAlsoValid"),
1252        Ok("any.type.isAlsoValid")
1253    );
1254    assert_eq!(
1255        get_type_url_message_name("my.messages.Message"),
1256        Err("unsupported type url 'my.messages.Message': missing at least one '/'".to_owned())
1257    );
1258}