Struct prost_reflect::DynamicMessage
source · pub struct DynamicMessage { /* private fields */ }
Expand description
DynamicMessage
provides encoding, decoding and reflection of a protobuf message.
It wraps a MessageDescriptor
and the Value
for each field of the message, and implements
Message
.
Implementations§
source§impl DynamicMessage
impl DynamicMessage
sourcepub fn parse_text_format(
desc: MessageDescriptor,
input: &str
) -> Result<Self, ParseError>
Available on crate feature text-format
only.
pub fn parse_text_format( desc: MessageDescriptor, input: &str ) -> Result<Self, ParseError>
text-format
only.Parse a DynamicMessage
from the given message encoded using the text format.
Examples
let dynamic_message = DynamicMessage::parse_text_format(message_descriptor, "foo: 150").unwrap();
assert_eq!(dynamic_message.get_field_by_name("foo").unwrap().as_ref(), &Value::I32(150));
sourcepub fn merge_text_format(&mut self, input: &str) -> Result<(), ParseError>
Available on crate feature text-format
only.
pub fn merge_text_format(&mut self, input: &str) -> Result<(), ParseError>
text-format
only.Merges the given message encoded using the text format into this message.
Examples
let mut dynamic_message = DynamicMessage::new(message_descriptor);
dynamic_message.merge_text_format("foo: 150").unwrap();
assert_eq!(dynamic_message.get_field_by_name("foo").unwrap().as_ref(), &Value::I32(150));
sourcepub fn to_text_format(&self) -> String
Available on crate feature text-format
only.
pub fn to_text_format(&self) -> String
text-format
only.Formats this dynamic message using the protobuf text format, with default options.
Examples
let dynamic_message = DynamicMessage::decode(message_descriptor, b"\x08\x96\x01\x1a\x02\x10\x42".as_ref()).unwrap();
assert_eq!(dynamic_message.to_text_format(), "foo:150,nested{bar:66}");
sourcepub fn to_text_format_with_options(&self, options: &FormatOptions) -> String
Available on crate feature text-format
only.
pub fn to_text_format_with_options(&self, options: &FormatOptions) -> String
text-format
only.Formats this dynamic message using the protobuf text format, with custom options.
Examples
let dynamic_message = DynamicMessage::decode(message_descriptor, b"\x08\x96\x01\x1a\x02\x10\x42".as_ref()).unwrap();
let options = FormatOptions::new().pretty(true);
assert_eq!(dynamic_message.to_text_format_with_options(&options), "foo: 150\nnested {\n bar: 66\n}");
source§impl DynamicMessage
impl DynamicMessage
sourcepub fn serialize_with_options<S>(
&self,
serializer: S,
options: &SerializeOptions
) -> Result<S::Ok, S::Error>where
S: Serializer,
Available on crate feature serde
only.
pub fn serialize_with_options<S>( &self, serializer: S, options: &SerializeOptions ) -> Result<S::Ok, S::Error>where S: Serializer,
serde
only.Serialize this message into serializer
using the encoding specified by options
.
Examples
let dynamic_message = DynamicMessage::new(message_descriptor);
let mut serializer = serde_json::Serializer::new(vec![]);
let mut options = SerializeOptions::new().skip_default_fields(false);
dynamic_message.serialize_with_options(&mut serializer, &options).unwrap();
assert_eq!(serializer.into_inner(), b"{\"foo\":0}");
sourcepub fn deserialize<'de, D>(
desc: MessageDescriptor,
deserializer: D
) -> Result<Self, D::Error>where
D: Deserializer<'de>,
Available on crate feature serde
only.
pub fn deserialize<'de, D>( desc: MessageDescriptor, deserializer: D ) -> Result<Self, D::Error>where D: Deserializer<'de>,
serde
only.Deserialize an instance of the message type described by desc
from deserializer
.
Examples
let json = r#"{ "foo": 150 }"#;
let mut deserializer = serde_json::de::Deserializer::from_str(json);
let dynamic_message = DynamicMessage::deserialize(message_descriptor, &mut deserializer).unwrap();
deserializer.end().unwrap();
assert_eq!(dynamic_message.get_field_by_name("foo").unwrap().as_ref(), &Value::I32(150));
sourcepub fn deserialize_with_options<'de, D>(
desc: MessageDescriptor,
deserializer: D,
options: &DeserializeOptions
) -> Result<Self, D::Error>where
D: Deserializer<'de>,
Available on crate feature serde
only.
pub fn deserialize_with_options<'de, D>( desc: MessageDescriptor, deserializer: D, options: &DeserializeOptions ) -> Result<Self, D::Error>where D: Deserializer<'de>,
serde
only.Deserialize an instance of the message type described by desc
from deserializer
, using
the encoding specified by options
.
Examples
let json = r#"{ "foo": 150, "unknown": true }"#;
let mut deserializer = serde_json::de::Deserializer::from_str(json);
let options = DeserializeOptions::new().deny_unknown_fields(false);
let dynamic_message = DynamicMessage::deserialize_with_options(message_descriptor, &mut deserializer, &options).unwrap();
deserializer.end().unwrap();
assert_eq!(dynamic_message.get_field_by_name("foo").unwrap().as_ref(), &Value::I32(150));
source§impl DynamicMessage
impl DynamicMessage
sourcepub fn new(desc: MessageDescriptor) -> Self
pub fn new(desc: MessageDescriptor) -> Self
Creates a new, empty instance of DynamicMessage
for the message type specified by the MessageDescriptor
.
sourcepub fn decode<B>(desc: MessageDescriptor, buf: B) -> Result<Self, DecodeError>where
B: Buf,
pub fn decode<B>(desc: MessageDescriptor, buf: B) -> Result<Self, DecodeError>where B: Buf,
Decodes an instance of the message type specified by the MessageDescriptor
from the buffer and merges it into a
new instance of DynamicMessage
.
Examples
let dynamic_message = DynamicMessage::decode(message_descriptor, b"\x08\x96\x01".as_ref()).unwrap();
assert_eq!(dynamic_message.get_field_by_name("foo").unwrap().as_ref(), &Value::I32(150));
sourcepub fn has_field(&self, field_desc: &FieldDescriptor) -> bool
pub fn has_field(&self, field_desc: &FieldDescriptor) -> bool
Returns true
if this message has the given field set.
If the field type supports distinguishing whether a value has been set (see supports_presence
),
such as for messages, then this method returns true
only if a value has been set. For
other types, such as integers, it returns true
if the value is set to a non-default value.
If this method returns false
, then the field will not be included in the encoded bytes
of this message.
Examples
This example uses the following message definition:
message MyMessage {
int32 foo = 1;
oneof optional {
int32 bar = 2;
}
}
let foo = message_descriptor.get_field_by_name("foo").unwrap();
let bar = message_descriptor.get_field_by_name("bar").unwrap();
assert!(!foo.supports_presence());
assert!(bar.supports_presence());
let mut dynamic_message = DynamicMessage::new(message_descriptor);
assert!(!dynamic_message.has_field(&foo));
assert!(!dynamic_message.has_field(&bar));
dynamic_message.set_field(&foo, Value::I32(0));
dynamic_message.set_field(&bar, Value::I32(0));
assert!(!dynamic_message.has_field(&foo));
assert!(dynamic_message.has_field(&bar));
dynamic_message.set_field(&foo, Value::I32(5));
dynamic_message.set_field(&bar, Value::I32(6));
assert!(dynamic_message.has_field(&foo));
assert!(dynamic_message.has_field(&bar));
sourcepub fn get_field(&self, field_desc: &FieldDescriptor) -> Cow<'_, Value>
pub fn get_field(&self, field_desc: &FieldDescriptor) -> Cow<'_, Value>
Gets the value of the given field, or the default value if it is unset.
sourcepub fn get_field_mut(&mut self, field_desc: &FieldDescriptor) -> &mut Value
pub fn get_field_mut(&mut self, field_desc: &FieldDescriptor) -> &mut Value
Gets a mutable reference to the value ofthe given field. If the field is not set, it is inserted with its default value.
sourcepub fn set_field(&mut self, field_desc: &FieldDescriptor, value: Value)
pub fn set_field(&mut self, field_desc: &FieldDescriptor, value: Value)
Sets the value of the given field.
Panics
This method may panic if the value type is not compatible with the field type, as defined
by Value::is_valid_for_field
. Consider using try_set_field()
for a non-panicking version.
sourcepub fn try_set_field(
&mut self,
field_desc: &FieldDescriptor,
value: Value
) -> Result<(), SetFieldError>
pub fn try_set_field( &mut self, field_desc: &FieldDescriptor, value: Value ) -> Result<(), SetFieldError>
Tries to set the value of the given field, returning an error if the value is an invalid type.
Examples
let mut dynamic_message = DynamicMessage::new(message_descriptor.clone());
let foo = message_descriptor.get_field_by_name("foo").unwrap();
assert_eq!(dynamic_message.try_set_field(&foo, Value::I32(5)), Ok(()));
assert_eq!(dynamic_message.try_set_field(&foo, Value::String("bar".to_owned())), Err(SetFieldError::InvalidType {
field: foo,
value: Value::String("bar".to_owned()),
}));
sourcepub fn clear_field(&mut self, field_desc: &FieldDescriptor)
pub fn clear_field(&mut self, field_desc: &FieldDescriptor)
Clears the given field.
After calling this method, has_field
will return false for the field,
and it will not be included in the encoded bytes of this message.
sourcepub fn has_field_by_number(&self, number: u32) -> bool
pub fn has_field_by_number(&self, number: u32) -> bool
Returns true
if this message has a field set with the given number.
See has_field
for more details.
sourcepub fn get_field_by_number(&self, number: u32) -> Option<Cow<'_, Value>>
pub fn get_field_by_number(&self, number: u32) -> Option<Cow<'_, Value>>
Gets the value of the field with the given number, or the default value if it is unset.
If the message has no field with the given number, None
is returned.
See get_field
for more details.
sourcepub fn get_field_by_number_mut(&mut self, number: u32) -> Option<&mut Value>
pub fn get_field_by_number_mut(&mut self, number: u32) -> Option<&mut Value>
Gets a mutable reference to the value of the field with the given number. If the field is not set, it is inserted with its default value.
If the message has no field with the given number, None
is returned.
See get_field_mut
for more details.
sourcepub fn set_field_by_number(&mut self, number: u32, value: Value)
pub fn set_field_by_number(&mut self, number: u32, value: Value)
Sets the value of the field with number number
.
If no field with the given number exists, this method does nothing.
See set_field
for more details.
sourcepub fn try_set_field_by_number(
&mut self,
number: u32,
value: Value
) -> Result<(), SetFieldError>
pub fn try_set_field_by_number( &mut self, number: u32, value: Value ) -> Result<(), SetFieldError>
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.
Examples
let mut dynamic_message = DynamicMessage::new(message_descriptor.clone());
assert_eq!(dynamic_message.try_set_field_by_number(1, Value::I32(5)), Ok(()));
assert_eq!(dynamic_message.try_set_field_by_number(1, Value::String("bar".to_owned())), Err(SetFieldError::InvalidType {
field: message_descriptor.get_field(1).unwrap(),
value: Value::String("bar".to_owned()),
}));
assert_eq!(dynamic_message.try_set_field_by_number(42, Value::I32(5)), Err(SetFieldError::NotFound));
sourcepub fn clear_field_by_number(&mut self, number: u32)
pub fn clear_field_by_number(&mut self, number: u32)
Clears the field with the given number.
If no field with the given number exists, this method does nothing.
See clear_field
for more details.
sourcepub fn has_field_by_name(&self, name: &str) -> bool
pub fn has_field_by_name(&self, name: &str) -> bool
Returns true
if this message has a field set with the given name.
See has_field
for more details.
sourcepub fn get_field_by_name(&self, name: &str) -> Option<Cow<'_, Value>>
pub fn get_field_by_name(&self, name: &str) -> Option<Cow<'_, Value>>
Gets the value of the field with the given name, or the default value if it is unset.
If the message has no field with the given name, None
is returned.
See get_field
for more details.
sourcepub fn get_field_by_name_mut(&mut self, name: &str) -> Option<&mut Value>
pub fn get_field_by_name_mut(&mut self, name: &str) -> Option<&mut Value>
Gets a mutable reference to the value of the field with the given name. If the field is not set, it is inserted with its default value.
If the message has no field with the given name, None
is returned.
See get_field_mut
for more details.
sourcepub fn set_field_by_name(&mut self, name: &str, value: Value)
pub fn set_field_by_name(&mut self, name: &str, value: Value)
Sets the value of the field with name name
.
If no field with the given name exists, this method does nothing.
See set_field
for more details.
sourcepub fn try_set_field_by_name(
&mut self,
name: &str,
value: Value
) -> Result<(), SetFieldError>
pub fn try_set_field_by_name( &mut self, name: &str, value: Value ) -> Result<(), SetFieldError>
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.
Examples
let mut dynamic_message = DynamicMessage::new(message_descriptor.clone());
assert_eq!(dynamic_message.try_set_field_by_name("foo", Value::I32(5)), Ok(()));
assert_eq!(dynamic_message.try_set_field_by_name("foo", Value::String("bar".to_owned())), Err(SetFieldError::InvalidType {
field: message_descriptor.get_field_by_name("foo").unwrap(),
value: Value::String("bar".to_owned()),
}));
assert_eq!(dynamic_message.try_set_field_by_name("notfound", Value::I32(5)), Err(SetFieldError::NotFound));
sourcepub fn clear_field_by_name(&mut self, name: &str)
pub fn clear_field_by_name(&mut self, name: &str)
Clears the field with the given name.
If no field with the given name exists, this method does nothing.
See clear_field
for more details.
sourcepub fn take_field(&mut self, field_desc: &FieldDescriptor) -> Option<Value>
pub fn take_field(&mut self, field_desc: &FieldDescriptor) -> Option<Value>
Clears the value for the given field, and returns it.
Returns the value if has_field
was true
, or None
otherwise.
sourcepub fn take_field_by_name(&mut self, name: &str) -> Option<Value>
pub fn take_field_by_name(&mut self, name: &str) -> Option<Value>
Clears the value for the field with the given name, and returns it.
Returns the value if has_field_by_name
was true
, or None
otherwise.
sourcepub fn take_field_by_number(&mut self, number: u32) -> Option<Value>
pub fn take_field_by_number(&mut self, number: u32) -> Option<Value>
Clears the value for the field with the given number, and returns it.
Returns the value if has_field_by_number
was true
, or None
otherwise.
sourcepub fn has_extension(&self, extension_desc: &ExtensionDescriptor) -> bool
pub fn has_extension(&self, extension_desc: &ExtensionDescriptor) -> bool
Returns true
if this message has the given extension field set.
See has_field
for more details.
sourcepub fn get_extension(
&self,
extension_desc: &ExtensionDescriptor
) -> Cow<'_, Value>
pub fn get_extension( &self, extension_desc: &ExtensionDescriptor ) -> Cow<'_, Value>
Gets the value of the given extension field, or the default value if it is unset.
See get_field
for more details.
sourcepub fn get_extension_mut(
&mut self,
extension_desc: &ExtensionDescriptor
) -> &mut Value
pub fn get_extension_mut( &mut self, extension_desc: &ExtensionDescriptor ) -> &mut Value
Gets a mutable reference to the value of the given extension field. If the field is not set, it is inserted with its default value.
See get_field_mut
for more details.
sourcepub fn set_extension(
&mut self,
extension_desc: &ExtensionDescriptor,
value: Value
)
pub fn set_extension( &mut self, extension_desc: &ExtensionDescriptor, value: Value )
Sets the value of the given extension field.
See set_field
for more details.
sourcepub fn clear_extension(&mut self, extension_desc: &ExtensionDescriptor)
pub fn clear_extension(&mut self, extension_desc: &ExtensionDescriptor)
Clears the given extension field.
See clear_field
for more details.
sourcepub fn take_extension(
&mut self,
extension_desc: &ExtensionDescriptor
) -> Option<Value>
pub fn take_extension( &mut self, extension_desc: &ExtensionDescriptor ) -> Option<Value>
Clears the value for the given extension field, and returns it.
Returns the value if has_extension
was true
, or None
otherwise.
sourcepub fn fields(&self) -> impl Iterator<Item = (FieldDescriptor, &Value)>
pub fn fields(&self) -> impl Iterator<Item = (FieldDescriptor, &Value)>
Gets an iterator over all fields of this message.
The iterator will yield all fields for which has_field
returns true
.
sourcepub fn fields_mut(
&mut self
) -> impl Iterator<Item = (FieldDescriptor, &mut Value)>
pub fn fields_mut( &mut self ) -> impl Iterator<Item = (FieldDescriptor, &mut Value)>
Gets an iterator returning mutable references to all fields of this message.
The iterator will yield all fields for which has_field
returns true
.
sourcepub fn take_fields(
&mut self
) -> impl Iterator<Item = (FieldDescriptor, Value)> + '_
pub fn take_fields( &mut self ) -> impl Iterator<Item = (FieldDescriptor, Value)> + '_
Clears all fields from the message and returns an iterator yielding the values.
The iterator will yield all fields for which has_field
returns true
.
If the iterator is dropped before completing the iteration, it is unspecified how many fields are removed.
sourcepub fn extensions(&self) -> impl Iterator<Item = (ExtensionDescriptor, &Value)>
pub fn extensions(&self) -> impl Iterator<Item = (ExtensionDescriptor, &Value)>
Gets an iterator over all extension fields of this message.
The iterator will yield all extension fields for which has_extension
returns true
.
sourcepub fn extensions_mut(
&mut self
) -> impl Iterator<Item = (ExtensionDescriptor, &mut Value)>
pub fn extensions_mut( &mut self ) -> impl Iterator<Item = (ExtensionDescriptor, &mut Value)>
Gets an iterator returning mutable references to all extension fields of this message.
The iterator will yield all extension fields for which has_extension
returns true
.
sourcepub fn take_extensions(
&mut self
) -> impl Iterator<Item = (ExtensionDescriptor, Value)> + '_
pub fn take_extensions( &mut self ) -> impl Iterator<Item = (ExtensionDescriptor, Value)> + '_
Clears all extension fields from the message and returns an iterator yielding the values.
The iterator will yield all extension fields for which has_extension
returns true
.
If the iterator is dropped before completing the iteration, it is unspecified how many fields are removed.
sourcepub fn unknown_fields(&self) -> impl Iterator<Item = &UnknownField>
pub fn unknown_fields(&self) -> impl Iterator<Item = &UnknownField>
Gets an iterator over unknown fields for this message.
A field is unknown if the message descriptor does not contain a field with the given number. This is often the result of a new field being added to the message definition.
Unknown fields are preserved when decoding and re-encoding a message.
sourcepub fn take_unknown_fields(&mut self) -> impl Iterator<Item = UnknownField> + '_
pub fn take_unknown_fields(&mut self) -> impl Iterator<Item = UnknownField> + '_
Clears all unknown fields from the message and returns an iterator yielding the values.
If the iterator is dropped before completing the iteration, it is unspecified how many fields are removed.
sourcepub fn transcode_from<T>(&mut self, value: &T) -> Result<(), DecodeError>where
T: Message,
pub fn transcode_from<T>(&mut self, value: &T) -> Result<(), DecodeError>where T: Message,
Merge a strongly-typed message into this one.
The message should be compatible with the type specified by
descriptor
, or the merge will likely fail with
a DecodeError
.
sourcepub fn transcode_to<T>(&self) -> Result<T, DecodeError>where
T: Message + Default,
pub fn transcode_to<T>(&self) -> Result<T, DecodeError>where T: Message + Default,
Convert this dynamic message into a strongly typed value.
The message should be compatible with the type specified by
descriptor
, or the conversion will likely fail with
a DecodeError
.
Trait Implementations§
source§impl Clone for DynamicMessage
impl Clone for DynamicMessage
source§fn clone(&self) -> DynamicMessage
fn clone(&self) -> DynamicMessage
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read moresource§impl Debug for DynamicMessage
impl Debug for DynamicMessage
source§impl Display for DynamicMessage
impl Display for DynamicMessage
source§fn fmt(&self, f: &mut Formatter<'_>) -> Result
fn fmt(&self, f: &mut Formatter<'_>) -> Result
Formats this message using the protobuf text format.
Examples
let dynamic_message = DynamicMessage::decode(message_descriptor, b"\x08\x96\x01\x1a\x02\x10\x42".as_ref()).unwrap();
assert_eq!(format!("{}", dynamic_message), "foo:150,nested{bar:66}");
// The alternate format specifier may be used to pretty-print the output
assert_eq!(format!("{:#}", dynamic_message), "foo: 150\nnested {\n bar: 66\n}");
source§impl Message for DynamicMessage
impl Message for DynamicMessage
source§fn encoded_len(&self) -> usize
fn encoded_len(&self) -> usize
source§fn encode<B>(&self, buf: &mut B) -> Result<(), EncodeError>where
B: BufMut,
Self: Sized,
fn encode<B>(&self, buf: &mut B) -> Result<(), EncodeError>where B: BufMut, Self: Sized,
source§fn encode_to_vec(&self) -> Vec<u8, Global>where
Self: Sized,
fn encode_to_vec(&self) -> Vec<u8, Global>where Self: Sized,
source§fn encode_length_delimited<B>(&self, buf: &mut B) -> Result<(), EncodeError>where
B: BufMut,
Self: Sized,
fn encode_length_delimited<B>(&self, buf: &mut B) -> Result<(), EncodeError>where B: BufMut, Self: Sized,
source§fn encode_length_delimited_to_vec(&self) -> Vec<u8, Global>where
Self: Sized,
fn encode_length_delimited_to_vec(&self) -> Vec<u8, Global>where Self: Sized,
source§fn merge<B>(&mut self, buf: B) -> Result<(), DecodeError>where
B: Buf,
Self: Sized,
fn merge<B>(&mut self, buf: B) -> Result<(), DecodeError>where B: Buf, Self: Sized,
self
. Read moresource§fn merge_length_delimited<B>(&mut self, buf: B) -> Result<(), DecodeError>where
B: Buf,
Self: Sized,
fn merge_length_delimited<B>(&mut self, buf: B) -> Result<(), DecodeError>where B: Buf, Self: Sized,
self
.source§impl PartialEq<DynamicMessage> for DynamicMessage
impl PartialEq<DynamicMessage> for DynamicMessage
source§fn eq(&self, other: &DynamicMessage) -> bool
fn eq(&self, other: &DynamicMessage) -> bool
self
and other
values to be equal, and is used
by ==
.source§impl ReflectMessage for DynamicMessage
impl ReflectMessage for DynamicMessage
source§fn descriptor(&self) -> MessageDescriptor
fn descriptor(&self) -> MessageDescriptor
MessageDescriptor
describing the type of this message.source§fn transcode_to_dynamic(&self) -> DynamicMessagewhere
Self: Sized,
fn transcode_to_dynamic(&self) -> DynamicMessagewhere Self: Sized,
DynamicMessage
by going
through the byte representation.source§impl Serialize for DynamicMessage
Available on crate feature serde
only.
impl Serialize for DynamicMessage
serde
only.source§fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>where
S: Serializer,
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>where S: Serializer,
Serialize this message into serializer
using the canonical JSON encoding.
Examples
let dynamic_message = DynamicMessage::decode(message_descriptor, b"\x08\x96\x01".as_ref()).unwrap();
let mut serializer = serde_json::Serializer::new(vec![]);
dynamic_message.serialize(&mut serializer).unwrap();
assert_eq!(serializer.into_inner(), b"{\"foo\":150}");