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

source

pub fn parse_text_format( desc: MessageDescriptor, input: &str, ) -> Result<Self, ParseError>

Available on crate feature 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));
source

pub fn merge_text_format(&mut self, input: &str) -> Result<(), ParseError>

Available on crate feature 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));
source

pub fn to_text_format(&self) -> String

Available on crate feature 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}");
source

pub fn to_text_format_with_options(&self, options: &FormatOptions) -> String

Available on crate feature 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

source

pub fn serialize_with_options<S>( &self, serializer: S, options: &SerializeOptions, ) -> Result<S::Ok, S::Error>
where S: Serializer,

Available on crate feature 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}");
source

pub fn deserialize<'de, D>( desc: MessageDescriptor, deserializer: D, ) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Available on crate feature 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));
source

pub 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.

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

source

pub fn new(desc: MessageDescriptor) -> Self

Creates a new, empty instance of DynamicMessage for the message type specified by the MessageDescriptor.

source

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));
source

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));
source

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.

source

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.

source

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.

source

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()),
}));
source

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.

source

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.

source

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.

source

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.

source

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.

source

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));
source

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.

source

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.

source

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.

source

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.

source

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.

source

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));
source

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.

source

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.

source

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.

source

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.

source

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.

source

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.

source

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.

source

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.

source

pub fn clear_extension(&mut self, extension_desc: &ExtensionDescriptor)

Clears the given extension field.

See clear_field for more details.

source

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.

source

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.

source

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.

source

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.

source

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.

source

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.

source

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.

source

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.

source

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.

source

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.

source

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

source§

fn clone(&self) -> DynamicMessage

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for DynamicMessage

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Display for DynamicMessage

source§

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

source§

fn encoded_len(&self) -> usize

Returns the encoded length of the message without a length delimiter.
source§

fn clear(&mut self)

Clears the message, resetting all fields to their default.
source§

fn encode(&self, buf: &mut impl BufMut) -> Result<(), EncodeError>
where Self: Sized,

Encodes the message to a buffer. Read more
source§

fn encode_to_vec(&self) -> Vec<u8>
where Self: Sized,

Encodes the message to a newly allocated buffer.
source§

fn encode_length_delimited( &self, buf: &mut impl BufMut, ) -> Result<(), EncodeError>
where Self: Sized,

Encodes the message with a length-delimiter to a buffer. Read more
source§

fn encode_length_delimited_to_vec(&self) -> Vec<u8>
where Self: Sized,

Encodes the message with a length-delimiter to a newly allocated buffer.
source§

fn merge(&mut self, buf: impl Buf) -> Result<(), DecodeError>
where Self: Sized,

Decodes an instance of the message from a buffer, and merges it into self. Read more
source§

fn merge_length_delimited(&mut self, buf: impl Buf) -> Result<(), DecodeError>
where Self: Sized,

Decodes a length-delimited instance of the message from buffer, and merges it into self.
source§

impl PartialEq for DynamicMessage

source§

fn eq(&self, other: &DynamicMessage) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl ReflectMessage for DynamicMessage

source§

fn descriptor(&self) -> MessageDescriptor

Gets a MessageDescriptor describing the type of this message.
source§

fn transcode_to_dynamic(&self) -> DynamicMessage
where Self: Sized,

Converts this message into an instance of DynamicMessage by going through the byte representation.
source§

impl Serialize for DynamicMessage

Available on crate feature serde only.
source§

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}");
source§

impl StructuralPartialEq for DynamicMessage

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CloneToUninit for T
where T: Clone,

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for T
where T: Clone,

source§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

source§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.