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 /// See [FieldDescriptor::default_value] for more details.
602 pub fn default_value_for_field(field_desc: &FieldDescriptor) -> Self {
603 field_desc.default_value()
604 }
605
606 /// Returns the default value for the given protobuf extension field.
607 ///
608 /// See [ExtensionDescriptor::default_value] for more details.
609 pub fn default_value_for_extension(extension_desc: &ExtensionDescriptor) -> Self {
610 extension_desc.default_value()
611 }
612
613 /// Returns the default value for the given protobuf type `kind`.
614 ///
615 /// See [Kind::default_value] for more details.
616 pub fn default_value(kind: &Kind) -> Self {
617 kind.default_value()
618 }
619
620 /// Returns `true` if this is the default value for the given protobuf field.
621 pub fn is_default_for_field(&self, field_desc: &FieldDescriptor) -> bool {
622 *self == Value::default_value_for_field(field_desc)
623 }
624
625 /// Returns `true` if this is the default value for the given protobuf extension field.
626 pub fn is_default_for_extension(&self, extension_desc: &ExtensionDescriptor) -> bool {
627 *self == Value::default_value_for_extension(extension_desc)
628 }
629
630 /// Returns `true` if this is the default value for the given protobuf type `kind`.
631 pub fn is_default(&self, kind: &Kind) -> bool {
632 *self == kind.default_value()
633 }
634
635 /// Returns `true` if this value can be set for a given field.
636 ///
637 /// Note this only checks if the value can be successfully encoded. It doesn't
638 /// check, for example, that enum values are in the defined range.
639 pub fn is_valid_for_field(&self, field_desc: &FieldDescriptor) -> bool {
640 match (self, field_desc.kind()) {
641 (Value::List(list), kind) if field_desc.is_list() => {
642 list.iter().all(|value| value.is_valid(&kind))
643 }
644 (Value::Map(map), Kind::Message(message_desc)) if field_desc.is_map() => {
645 let key_desc = message_desc.map_entry_key_field().kind();
646 let value_desc = message_desc.map_entry_value_field();
647 map.iter().all(|(key, value)| {
648 key.is_valid(&key_desc) && value.is_valid_for_field(&value_desc)
649 })
650 }
651 (value, kind) => value.is_valid(&kind),
652 }
653 }
654
655 /// Returns `true` if this value can be set for a given extension field.
656 ///
657 /// See [`is_valid_for_field`][Value::is_valid_for_field] for more details.
658 pub fn is_valid_for_extension(&self, extension_desc: &ExtensionDescriptor) -> bool {
659 match (self, extension_desc.kind()) {
660 (Value::List(list), kind) if extension_desc.is_list() => {
661 list.iter().all(|value| value.is_valid(&kind))
662 }
663 (Value::Map(map), Kind::Message(message_desc)) if extension_desc.is_map() => {
664 let key_desc = message_desc.map_entry_key_field().kind();
665 let value_desc = message_desc.map_entry_value_field();
666 map.iter().all(|(key, value)| {
667 key.is_valid(&key_desc) && value.is_valid_for_field(&value_desc)
668 })
669 }
670 (value, kind) => value.is_valid(&kind),
671 }
672 }
673
674 /// Returns `true` if this value can be encoded as the given [`Kind`].
675 ///
676 /// Unlike [`is_valid_for_field`](Value::is_valid_for_field), this method does not
677 /// look at field cardinality, so it will never return `true` for lists or maps.
678 pub fn is_valid(&self, kind: &Kind) -> bool {
679 matches!(
680 (self, kind),
681 (Value::Bool(_), Kind::Bool)
682 | (Value::I32(_), Kind::Int32 | Kind::Sint32 | Kind::Sfixed32)
683 | (Value::I64(_), Kind::Int64 | Kind::Sint64 | Kind::Sfixed64)
684 | (Value::U32(_), Kind::Uint32 | Kind::Fixed32)
685 | (Value::U64(_), Kind::Uint64 | Kind::Fixed64)
686 | (Value::F32(_), Kind::Float)
687 | (Value::F64(_), Kind::Double)
688 | (Value::String(_), Kind::String)
689 | (Value::Bytes(_), Kind::Bytes)
690 | (Value::EnumNumber(_), Kind::Enum(_))
691 | (Value::Message(_), Kind::Message(_))
692 )
693 }
694
695 /// Returns the value if it is a `Value::Bool`, or `None` if it is any other type.
696 pub fn as_bool(&self) -> Option<bool> {
697 match *self {
698 Value::Bool(value) => Some(value),
699 _ => None,
700 }
701 }
702
703 /// Returns a mutable reference to the value if it is a `Value::Bool`, or `None` if it is any other type.
704 pub fn as_bool_mut(&mut self) -> Option<&mut bool> {
705 match self {
706 Value::Bool(value) => Some(value),
707 _ => None,
708 }
709 }
710
711 /// Returns the value if it is a `Value::U32`, or `None` if it is any other type.
712 pub fn as_u32(&self) -> Option<u32> {
713 match *self {
714 Value::U32(value) => Some(value),
715 _ => None,
716 }
717 }
718
719 /// Returns a mutable reference to the value if it is a `Value::U32`, or `None` if it is any other type.
720 pub fn as_u32_mut(&mut self) -> Option<&mut u32> {
721 match self {
722 Value::U32(value) => Some(value),
723 _ => None,
724 }
725 }
726
727 /// Returns the value if it is a `Value::U64`, or `None` if it is any other type.
728 pub fn as_u64(&self) -> Option<u64> {
729 match *self {
730 Value::U64(value) => Some(value),
731 _ => None,
732 }
733 }
734
735 /// Returns a mutable reference to the value if it is a `Value::U64`, or `None` if it is any other type.
736 pub fn as_u64_mut(&mut self) -> Option<&mut u64> {
737 match self {
738 Value::U64(value) => Some(value),
739 _ => None,
740 }
741 }
742
743 /// Returns the value if it is a `Value::I64`, or `None` if it is any other type.
744 pub fn as_i64(&self) -> Option<i64> {
745 match *self {
746 Value::I64(value) => Some(value),
747 _ => None,
748 }
749 }
750
751 /// Returns a mutable reference to the value if it is a `Value::I64`, or `None` if it is any other type.
752 pub fn as_i64_mut(&mut self) -> Option<&mut i64> {
753 match self {
754 Value::I64(value) => Some(value),
755 _ => None,
756 }
757 }
758
759 /// Returns the value if it is a `Value::I32`, or `None` if it is any other type.
760 pub fn as_i32(&self) -> Option<i32> {
761 match *self {
762 Value::I32(value) => Some(value),
763 _ => None,
764 }
765 }
766
767 /// Returns a mutable reference to the value if it is a `Value::I32`, or `None` if it is any other type.
768 pub fn as_i32_mut(&mut self) -> Option<&mut i32> {
769 match self {
770 Value::I32(value) => Some(value),
771 _ => None,
772 }
773 }
774
775 /// Returns the value if it is a `Value::F32`, or `None` if it is any other type.
776 pub fn as_f32(&self) -> Option<f32> {
777 match *self {
778 Value::F32(value) => Some(value),
779 _ => None,
780 }
781 }
782
783 /// Returns a mutable reference to the value if it is a `Value::F32`, or `None` if it is any other type.
784 pub fn as_f32_mut(&mut self) -> Option<&mut f32> {
785 match self {
786 Value::F32(value) => Some(value),
787 _ => None,
788 }
789 }
790
791 /// Returns the value if it is a `Value::F64`, or `None` if it is any other type.
792 pub fn as_f64(&self) -> Option<f64> {
793 match *self {
794 Value::F64(value) => Some(value),
795 _ => None,
796 }
797 }
798
799 /// Returns a mutable reference to the value if it is a `Value::F64`, or `None` if it is any other type.
800 pub fn as_f64_mut(&mut self) -> Option<&mut f64> {
801 match self {
802 Value::F64(value) => Some(value),
803 _ => None,
804 }
805 }
806
807 /// Returns the value if it is a `Value::EnumNumber`, or `None` if it is any other type.
808 pub fn as_enum_number(&self) -> Option<i32> {
809 match *self {
810 Value::EnumNumber(value) => Some(value),
811 _ => None,
812 }
813 }
814
815 /// Returns a mutable reference to the value if it is a `Value::EnumNumber`, or `None` if it is any other type.
816 pub fn as_enum_number_mut(&mut self) -> Option<&mut i32> {
817 match self {
818 Value::EnumNumber(value) => Some(value),
819 _ => None,
820 }
821 }
822
823 /// Returns the value if it is a `Value::String`, or `None` if it is any other type.
824 pub fn as_str(&self) -> Option<&str> {
825 match self {
826 Value::String(value) => Some(value),
827 _ => None,
828 }
829 }
830
831 /// Returns a mutable reference to the value if it is a `Value::String`, or `None` if it is any other type.
832 pub fn as_string_mut(&mut self) -> Option<&mut String> {
833 match self {
834 Value::String(value) => Some(value),
835 _ => None,
836 }
837 }
838
839 /// Returns the value if it is a `Value::Bytes`, or `None` if it is any other type.
840 pub fn as_bytes(&self) -> Option<&Bytes> {
841 match self {
842 Value::Bytes(value) => Some(value),
843 _ => None,
844 }
845 }
846
847 /// Returns a mutable reference to the value if it is a `Value::Bytes`, or `None` if it is any other type.
848 pub fn as_bytes_mut(&mut self) -> Option<&mut Bytes> {
849 match self {
850 Value::Bytes(value) => Some(value),
851 _ => None,
852 }
853 }
854
855 /// Returns a a reference to the value if it is a `Value::Message`, or `None` if it is any other type.
856 pub fn as_message(&self) -> Option<&DynamicMessage> {
857 match self {
858 Value::Message(value) => Some(value),
859 _ => None,
860 }
861 }
862
863 /// Returns a mutable reference to the value if it is a `Value::Message`, or `None` if it is any other type.
864 pub fn as_message_mut(&mut self) -> Option<&mut DynamicMessage> {
865 match self {
866 Value::Message(value) => Some(value),
867 _ => None,
868 }
869 }
870
871 /// Returns a a reference to the value if it is a `Value::List`, or `None` if it is any other type.
872 pub fn as_list(&self) -> Option<&[Value]> {
873 match self {
874 Value::List(value) => Some(value),
875 _ => None,
876 }
877 }
878
879 /// Returns a mutable reference to the value if it is a `Value::List`, or `None` if it is any other type.
880 pub fn as_list_mut(&mut self) -> Option<&mut Vec<Value>> {
881 match self {
882 Value::List(value) => Some(value),
883 _ => None,
884 }
885 }
886
887 /// Returns a a reference to the value if it is a `Value::Map`, or `None` if it is any other type.
888 pub fn as_map(&self) -> Option<&HashMap<MapKey, Value>> {
889 match self {
890 Value::Map(value) => Some(value),
891 _ => None,
892 }
893 }
894
895 /// Returns a mutable reference to the value if it is a `Value::Map`, or `None` if it is any other type.
896 pub fn as_map_mut(&mut self) -> Option<&mut HashMap<MapKey, Value>> {
897 match self {
898 Value::Map(value) => Some(value),
899 _ => None,
900 }
901 }
902
903 /// Converts this value into a [`MapKey`], or `None` if it is not a valid map key type.
904 ///
905 /// # Examples
906 ///
907 /// ```
908 /// # use prost_reflect::{Value, MapKey, bytes::Bytes};
909 /// assert_eq!(Value::I32(5).into_map_key(), Some(MapKey::I32(5)));
910 /// assert_eq!(Value::String("foo".to_owned()).into_map_key(), Some(MapKey::String("foo".to_owned())));
911 /// assert_eq!(Value::Bytes(Bytes::from_static(b"bytes")).into_map_key(), None);
912 /// ```
913 pub fn into_map_key(self) -> Option<MapKey> {
914 match self {
915 Value::Bool(value) => Some(MapKey::Bool(value)),
916 Value::I32(value) => Some(MapKey::I32(value)),
917 Value::I64(value) => Some(MapKey::I64(value)),
918 Value::U32(value) => Some(MapKey::U32(value)),
919 Value::U64(value) => Some(MapKey::U64(value)),
920 Value::String(value) => Some(MapKey::String(value)),
921 _ => None,
922 }
923 }
924}
925
926impl MapKey {
927 /// Returns the default value for the given protobuf type `kind`.
928 ///
929 /// # Panics
930 ///
931 /// Panics if `kind` is not a valid map key type (an integral type or string).
932 pub fn default_value(kind: &Kind) -> Self {
933 match *kind {
934 Kind::Int32 | Kind::Sint32 | Kind::Sfixed32 => MapKey::I32(0),
935 Kind::Int64 | Kind::Sint64 | Kind::Sfixed64 => MapKey::I64(0),
936 Kind::Uint32 | Kind::Fixed32 => MapKey::U32(0),
937 Kind::Uint64 | Kind::Fixed64 => MapKey::U64(0),
938 Kind::Bool => MapKey::Bool(false),
939 Kind::String => MapKey::String(String::default()),
940 _ => panic!("invalid type for map key"),
941 }
942 }
943
944 /// Returns `true` if this is the default value for the given protobuf type `kind`.
945 ///
946 /// # Panics
947 ///
948 /// Panics if `kind` is not a valid map key type (an integral type or string).
949 pub fn is_default(&self, kind: &Kind) -> bool {
950 *self == MapKey::default_value(kind)
951 }
952
953 /// Returns `true` if this map key can be encoded as the given [`Kind`].
954 pub fn is_valid(&self, kind: &Kind) -> bool {
955 matches!(
956 (self, kind),
957 (MapKey::Bool(_), Kind::Bool)
958 | (MapKey::I32(_), Kind::Int32 | Kind::Sint32 | Kind::Sfixed32)
959 | (MapKey::I64(_), Kind::Int64 | Kind::Sint64 | Kind::Sfixed64)
960 | (MapKey::U32(_), Kind::Uint32 | Kind::Fixed32)
961 | (MapKey::U64(_), Kind::Uint64 | Kind::Fixed64)
962 | (MapKey::String(_), Kind::String)
963 )
964 }
965
966 /// Returns the value if it is a `MapKey::Bool`, or `None` if it is any other type.
967 pub fn as_bool(&self) -> Option<bool> {
968 match *self {
969 MapKey::Bool(value) => Some(value),
970 _ => None,
971 }
972 }
973
974 /// Returns a mutable reference to the value if it is a `MapKey::Bool`, or `None` if it is any other type.
975 pub fn as_bool_mut(&mut self) -> Option<&mut bool> {
976 match self {
977 MapKey::Bool(value) => Some(value),
978 _ => None,
979 }
980 }
981
982 /// Returns the value if it is a `MapKey::U32`, or `None` if it is any other type.
983 pub fn as_u32(&self) -> Option<u32> {
984 match *self {
985 MapKey::U32(value) => Some(value),
986 _ => None,
987 }
988 }
989
990 /// Returns a mutable reference to the value if it is a `MapKey::U32`, or `None` if it is any other type.
991 pub fn as_u32_mut(&mut self) -> Option<&mut u32> {
992 match self {
993 MapKey::U32(value) => Some(value),
994 _ => None,
995 }
996 }
997
998 /// Returns the value if it is a `MapKey::U64`, or `None` if it is any other type.
999 pub fn as_u64(&self) -> Option<u64> {
1000 match *self {
1001 MapKey::U64(value) => Some(value),
1002 _ => None,
1003 }
1004 }
1005
1006 /// Returns a mutable reference to the value if it is a `MapKey::U64`, or `None` if it is any other type.
1007 pub fn as_u64_mut(&mut self) -> Option<&mut u64> {
1008 match self {
1009 MapKey::U64(value) => Some(value),
1010 _ => None,
1011 }
1012 }
1013
1014 /// Returns the value if it is a `MapKey::I64`, or `None` if it is any other type.
1015 pub fn as_i64(&self) -> Option<i64> {
1016 match *self {
1017 MapKey::I64(value) => Some(value),
1018 _ => None,
1019 }
1020 }
1021
1022 /// Returns a mutable reference to the value if it is a `MapKey::I64`, or `None` if it is any other type.
1023 pub fn as_i64_mut(&mut self) -> Option<&mut i64> {
1024 match self {
1025 MapKey::I64(value) => Some(value),
1026 _ => None,
1027 }
1028 }
1029
1030 /// Returns the value if it is a `MapKey::I32`, or `None` if it is any other type.
1031 pub fn as_i32(&self) -> Option<i32> {
1032 match *self {
1033 MapKey::I32(value) => Some(value),
1034 _ => None,
1035 }
1036 }
1037
1038 /// Returns a mutable reference to the value if it is a `MapKey::I32`, or `None` if it is any other type.
1039 pub fn as_i32_mut(&mut self) -> Option<&mut i32> {
1040 match self {
1041 MapKey::I32(value) => Some(value),
1042 _ => None,
1043 }
1044 }
1045
1046 /// Returns the value if it is a `MapKey::String`, or `None` if it is any other type.
1047 pub fn as_str(&self) -> Option<&str> {
1048 match self {
1049 MapKey::String(value) => Some(value),
1050 _ => None,
1051 }
1052 }
1053
1054 /// Returns a mutable reference to the value if it is a `MapKey::String`, or `None` if it is any other type.
1055 pub fn as_string_mut(&mut self) -> Option<&mut String> {
1056 match self {
1057 MapKey::String(value) => Some(value),
1058 _ => None,
1059 }
1060 }
1061}
1062
1063impl From<MapKey> for Value {
1064 fn from(value: MapKey) -> Self {
1065 match value {
1066 MapKey::Bool(value) => Value::Bool(value),
1067 MapKey::I32(value) => Value::I32(value),
1068 MapKey::I64(value) => Value::I64(value),
1069 MapKey::U32(value) => Value::U32(value),
1070 MapKey::U64(value) => Value::U64(value),
1071 MapKey::String(value) => Value::String(value),
1072 }
1073 }
1074}
1075
1076impl fmt::Display for SetFieldError {
1077 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1078 match self {
1079 SetFieldError::NotFound => write!(f, "field not found"),
1080 SetFieldError::InvalidType { field, value } => {
1081 write!(f, "expected a value of type '")?;
1082 if field.is_map() {
1083 let entry = field.kind();
1084 let entry = entry.as_message().unwrap();
1085 write!(
1086 f,
1087 "map<{:?}, {:?}>",
1088 entry.map_entry_key_field().kind(),
1089 entry.map_entry_value_field().kind()
1090 )?;
1091 } else if field.is_list() {
1092 write!(f, "repeated {:?}", field.kind())?;
1093 } else {
1094 write!(f, "{:?}", field.kind())?;
1095 }
1096 write!(f, "', but found '{value}'")
1097 }
1098 }
1099 }
1100}
1101
1102impl Error for SetFieldError {}
1103
1104pub(crate) fn fmt_string(f: &mut impl fmt::Write, bytes: &[u8]) -> fmt::Result {
1105 f.write_char('"')?;
1106 for &ch in bytes {
1107 match ch {
1108 b'\t' => f.write_str("\\t")?,
1109 b'\r' => f.write_str("\\r")?,
1110 b'\n' => f.write_str("\\n")?,
1111 b'\\' => f.write_str("\\\\")?,
1112 b'\'' => f.write_str("\\'")?,
1113 b'"' => f.write_str("\\\"")?,
1114 b'\x20'..=b'\x7e' => f.write_char(ch as char)?,
1115 _ => {
1116 write!(f, "\\{ch:03o}")?;
1117 }
1118 }
1119 }
1120 f.write_char('"')
1121}
1122
1123impl fmt::Display for DynamicMessage {
1124 /// Formats this message using the protobuf text format.
1125 ///
1126 /// # Examples
1127 ///
1128 /// ```
1129 /// # use prost::Message;
1130 /// # use prost_types::FileDescriptorSet;
1131 /// # use prost_reflect::{DynamicMessage, DescriptorPool, Value};
1132 /// # let pool = DescriptorPool::decode(include_bytes!("../file_descriptor_set.bin").as_ref()).unwrap();
1133 /// # let message_descriptor = pool.get_message_by_name("package.MyMessage").unwrap();
1134 /// let dynamic_message = DynamicMessage::decode(message_descriptor, b"\x08\x96\x01\x1a\x02\x10\x42".as_ref()).unwrap();
1135 /// assert_eq!(format!("{}", dynamic_message), "foo:150,nested{bar:66}");
1136 /// // The alternate format specifier may be used to pretty-print the output
1137 /// assert_eq!(format!("{:#}", dynamic_message), "foo: 150\nnested {\n bar: 66\n}");
1138 /// ```
1139 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1140 text_format::Writer::new(text_format::FormatOptions::new().pretty(f.alternate()), f)
1141 .fmt_message(self)
1142 }
1143}
1144
1145impl fmt::Display for Value {
1146 /// Formats this value using the protobuf text format.
1147 ///
1148 /// # Examples
1149 ///
1150 /// ```
1151 /// # use std::{collections::HashMap, iter::FromIterator};
1152 /// # use prost_reflect::{MapKey, Value};
1153 /// assert_eq!(format!("{}", Value::String("hello".to_owned())), "\"hello\"");
1154 /// assert_eq!(format!("{}", Value::List(vec![Value::I32(1), Value::I32(2)])), "[1,2]");
1155 /// assert_eq!(format!("{}", Value::Map(HashMap::from_iter([(MapKey::I32(1), Value::U32(2))]))), "[{key:1,value:2}]");
1156 /// // The alternate format specifier may be used to indent the output
1157 /// assert_eq!(format!("{:#}", Value::Map(HashMap::from_iter([(MapKey::I32(1), Value::U32(2))]))), "[{\n key: 1\n value: 2\n}]");
1158 /// ```
1159 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1160 text_format::Writer::new(text_format::FormatOptions::new().pretty(f.alternate()), f)
1161 .fmt_value(self, None)
1162 }
1163}
1164
1165#[test]
1166#[cfg(target_arch = "x86_64")]
1167fn type_sizes() {
1168 assert_eq!(std::mem::size_of::<DynamicMessage>(), 40);
1169 assert_eq!(std::mem::size_of::<Value>(), 56);
1170}
1171
1172pub(crate) enum Either<L, R> {
1173 Left(L),
1174 Right(R),
1175}
1176
1177impl<L: Iterator, R: Iterator<Item = L::Item>> Iterator for Either<L, R> {
1178 type Item = L::Item;
1179
1180 fn next(&mut self) -> Option<Self::Item> {
1181 match self {
1182 Either::Left(left) => left.next(),
1183 Either::Right(right) => right.next(),
1184 }
1185 }
1186}
1187
1188fn get_type_url_message_name(type_url: &str) -> Result<&str, String> {
1189 let (_type_domain_name, message_name) = type_url
1190 .rsplit_once('/')
1191 .ok_or_else(|| format!("unsupported type url '{type_url}': missing at least one '/'",))?;
1192
1193 Ok(message_name)
1194}
1195
1196#[test]
1197fn test_get_type_url_message_name() {
1198 assert_eq!(
1199 get_type_url_message_name("type.googleapis.com/my.messages.Message"),
1200 Ok("my.messages.Message")
1201 );
1202 assert_eq!(
1203 get_type_url_message_name("type.googleprod.com/my.messages.Message"),
1204 Ok("my.messages.Message")
1205 );
1206 assert_eq!(
1207 get_type_url_message_name("/my.messages.Message"),
1208 Ok("my.messages.Message")
1209 );
1210 assert_eq!(
1211 get_type_url_message_name("any.url.com/my.messages.Message"),
1212 Ok("my.messages.Message")
1213 );
1214 assert_eq!(
1215 get_type_url_message_name("http://even.multiple/slashes/my.messages.Message"),
1216 Ok("my.messages.Message")
1217 );
1218 assert_eq!(
1219 get_type_url_message_name("/any.type.isAlsoValid"),
1220 Ok("any.type.isAlsoValid")
1221 );
1222 assert_eq!(
1223 get_type_url_message_name("my.messages.Message"),
1224 Err("unsupported type url 'my.messages.Message': missing at least one '/'".to_owned())
1225 );
1226}