zvariant_utils-3.1.0/.cargo_vcs_info.json0000644000000001540000000000100141130ustar { "git": { "sha1": "a27276a7b908106bba9d08165a1d7d74560cf9f8" }, "path_in_vcs": "zvariant_utils" }zvariant_utils-3.1.0/Cargo.toml0000644000000030500000000000100121070ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.77" name = "zvariant_utils" version = "3.1.0" authors = [ "Zeeshan Ali Khan ", "turbocooler ", ] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Various utilities used internally by the zvariant crate." readme = "README.md" keywords = [ "D-Bus", "DBus", "IPC", "GVariant", ] categories = [ "data-structures", "encoding", "parsing", ] license = "MIT" repository = "https://github.com/dbus2/zbus/" [lib] name = "zvariant_utils" path = "src/lib.rs" [dependencies.proc-macro2] version = "1.0.81" [dependencies.quote] version = "1.0.36" [dependencies.serde] version = "1.0.200" [dependencies.static_assertions] version = "1.1.0" [dependencies.syn] version = "2.0.64" features = [ "extra-traits", "full", ] [dependencies.winnow] version = "0.6" [dev-dependencies] [features] default = [] gvariant = [] [lints.rust.unexpected_cfgs] level = "warn" priority = 0 check-cfg = ["cfg(tokio_unstable)"] zvariant_utils-3.1.0/Cargo.toml.orig000064400000000000000000000014111046102023000155670ustar 00000000000000[package] name = "zvariant_utils" version = "3.1.0" authors = [ "Zeeshan Ali Khan ", "turbocooler ", ] edition = "2021" rust-version = { workspace = true } description = "Various utilities used internally by the zvariant crate." repository = "https://github.com/dbus2/zbus/" keywords = ["D-Bus", "DBus", "IPC", "GVariant"] license = "MIT" categories = ["data-structures", "encoding", "parsing"] readme = "README.md" [features] default = [] gvariant = [] [dependencies] proc-macro2 = "1.0.81" syn = { version = "2.0.64", features = ["extra-traits", "full"] } quote = "1.0.36" static_assertions = "1.1.0" serde = "1.0.200" winnow = "0.6" [dev-dependencies] zvariant = { path = "../zvariant" } [lints] workspace = true zvariant_utils-3.1.0/LICENSE000064400000000000000000000017771046102023000137240ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. zvariant_utils-3.1.0/README.md000064400000000000000000000007021046102023000141610ustar 00000000000000# zvariant_utils [![](https://docs.rs/zvariant_utils/badge.svg)](https://docs.rs/zvariant_utils/) [![](https://img.shields.io/crates/v/zvariant_utils)](https://crates.io/crates/zvariant_utils) This crate provides various utilities for [`zvariant`]. ## Stability The API is NOT expected to be stable. The crate, however, will follow semver rules: breaking changes would cause a major version bump. [`zvariant`]: https://crates.io/crates/zvariant zvariant_utils-3.1.0/src/case.rs000064400000000000000000000055411046102023000147600ustar 00000000000000//! Contains utilities used to convert strings between different cases. /// Convert to pascal or camel case, assuming snake or kebab case. /// /// If `s` is already in pascal or camel case, should yield the same result. pub fn pascal_or_camel_case(s: &str, is_pascal_case: bool) -> String { let mut result = String::new(); let mut capitalize = is_pascal_case; let mut first = true; for ch in s.chars() { if ch == '_' || ch == '-' { capitalize = true; } else if capitalize { result.push(ch.to_ascii_uppercase()); capitalize = false; } else if first && !is_pascal_case { result.push(ch.to_ascii_lowercase()); } else { result.push(ch); } if first { first = false; } } result } /// Convert to snake or kebab case, assuming camel or Pascal case. /// /// If `s` is already in snake or kebab case, should yield the same result. pub fn snake_or_kebab_case(s: &str, is_snake_case: bool) -> String { let mut result = String::new(); for ch in s.chars() { if ch.is_ascii_uppercase() && !result.is_empty() { if is_snake_case { result.push('_'); } else { result.push('-'); } }; if ch == '_' || ch == '-' { if is_snake_case { result.push('_'); } else { result.push('-'); } } else { result.push(ch.to_ascii_lowercase()); } } result } #[cfg(test)] mod tests { use super::*; #[test] fn test_pascal_case() { assert_eq!("FooBar", pascal_or_camel_case("foo_bar", true)); assert_eq!("FooBar", pascal_or_camel_case("fooBar", true)); assert_eq!("FooBar", pascal_or_camel_case("foo-bar", true)); assert_eq!("FooBar", pascal_or_camel_case("FooBar", true)); } #[test] fn test_camel_case() { assert_eq!("fooBar", pascal_or_camel_case("foo_bar", false)); assert_eq!("fooBar", pascal_or_camel_case("fooBar", false)); assert_eq!("fooBar", pascal_or_camel_case("foo-bar", false)); assert_eq!("fooBar", pascal_or_camel_case("FooBar", false)); } #[test] fn test_snake_case() { assert_eq!("foo_bar", snake_or_kebab_case("foo_bar", true)); assert_eq!("foo_bar", snake_or_kebab_case("fooBar", true)); assert_eq!("foo_bar", snake_or_kebab_case("foo-bar", true)); assert_eq!("foo_bar", snake_or_kebab_case("FooBar", true)); } #[test] fn test_kebab_case() { assert_eq!("foo-bar", snake_or_kebab_case("foo_bar", false)); assert_eq!("foo-bar", snake_or_kebab_case("fooBar", false)); assert_eq!("foo-bar", snake_or_kebab_case("foo-bar", false)); assert_eq!("foo-bar", snake_or_kebab_case("FooBar", false)); } } zvariant_utils-3.1.0/src/lib.rs000064400000000000000000000002051046102023000146030ustar 00000000000000//! Various utilities used by the `zvariant` crate and others. pub mod case; pub mod macros; pub mod serialized; pub mod signature; zvariant_utils-3.1.0/src/macros.rs000064400000000000000000000404471046102023000153350ustar 00000000000000use syn::{ punctuated::Punctuated, spanned::Spanned, Attribute, Expr, Lit, LitBool, LitStr, Meta, MetaList, Result, Token, Type, TypePath, }; // find the #[@attr_name] attribute in @attrs fn find_attribute_meta(attrs: &[Attribute], attr_names: &[&str]) -> Result> { // Find attribute with path matching one of the allowed attribute names, let search_result = attrs.iter().find_map(|a| { attr_names .iter() .find_map(|attr_name| a.path().is_ident(attr_name).then_some((attr_name, a))) }); let (attr_name, meta) = match search_result { Some((attr_name, a)) => (attr_name, &a.meta), _ => return Ok(None), }; match meta.require_list() { Ok(n) => Ok(Some(n.clone())), _ => Err(syn::Error::new( meta.span(), format!("{attr_name} meta must specify a meta list"), )), } } fn get_meta_value<'a>(meta: &'a Meta, attr: &str) -> Result<&'a Lit> { let meta = meta.require_name_value()?; get_expr_lit(&meta.value, attr) } fn get_expr_lit<'a>(expr: &'a Expr, attr: &str) -> Result<&'a Lit> { match expr { Expr::Lit(l) => Ok(&l.lit), // Macro variables are put in a group. Expr::Group(group) => get_expr_lit(&group.expr, attr), expr => Err(syn::Error::new( expr.span(), format!("attribute `{attr}`'s value must be a literal"), )), } } /// Compares `ident` and `attr` and in case they match ensures `value` is `Some` and contains a /// [`struct@LitStr`]. Returns `true` in case `ident` and `attr` match, otherwise false. /// /// # Errors /// /// Returns an error in case `ident` and `attr` match but the value is not `Some` or is not a /// [`struct@LitStr`]. pub fn match_attribute_with_str_value<'a>( meta: &'a Meta, attr: &str, ) -> Result> { if !meta.path().is_ident(attr) { return Ok(None); } match get_meta_value(meta, attr)? { Lit::Str(value) => Ok(Some(value)), _ => Err(syn::Error::new( meta.span(), format!("value of the `{attr}` attribute must be a string literal"), )), } } /// Compares `ident` and `attr` and in case they match ensures `value` is `Some` and contains a /// [`struct@LitBool`]. Returns `true` in case `ident` and `attr` match, otherwise false. /// /// # Errors /// /// Returns an error in case `ident` and `attr` match but the value is not `Some` or is not a /// [`struct@LitBool`]. pub fn match_attribute_with_bool_value<'a>( meta: &'a Meta, attr: &str, ) -> Result> { if meta.path().is_ident(attr) { match get_meta_value(meta, attr)? { Lit::Bool(value) => Ok(Some(value)), other => Err(syn::Error::new( other.span(), format!("value of the `{attr}` attribute must be a boolean literal"), )), } } else { Ok(None) } } pub fn match_attribute_with_str_list_value(meta: &Meta, attr: &str) -> Result>> { if meta.path().is_ident(attr) { let list = meta.require_list()?; let values = list .parse_args_with(Punctuated::::parse_terminated)? .into_iter() .map(|s| s.value()) .collect(); Ok(Some(values)) } else { Ok(None) } } /// Compares `ident` and `attr` and in case they match ensures `value` is `None`. Returns `true` in /// case `ident` and `attr` match, otherwise false. /// /// # Errors /// /// Returns an error in case `ident` and `attr` match but the value is not `None`. pub fn match_attribute_without_value(meta: &Meta, attr: &str) -> Result { if meta.path().is_ident(attr) { meta.require_path_only()?; Ok(true) } else { Ok(false) } } /// Returns an iterator over the contents of all [`MetaList`]s with the specified identifier in an /// array of [`Attribute`]s. pub fn iter_meta_lists( attrs: &[Attribute], list_names: &[&str], ) -> Result> { let meta = find_attribute_meta(attrs, list_names)?; Ok(meta .map(|meta| meta.parse_args_with(Punctuated::::parse_terminated)) .transpose()? .into_iter() .flatten()) } /// Generates one or more structures used for parsing attributes in proc macros. /// /// Generated structures have one static method called parse that accepts a slice of [`Attribute`]s. /// The method finds attributes that contain meta lists (look like `#[your_custom_ident(...)]`) and /// fills a newly allocated structure with values of the attributes if any. /// /// The expected input looks as follows: /// /// ``` /// # use zvariant_utils::def_attrs; /// def_attrs! { /// crate zvariant; /// /// /// A comment. /// pub StructAttributes("struct") { foo str, bar str, baz none }; /// #[derive(Hash)] /// FieldAttributes("field") { field_attr bool }; /// } /// ``` /// /// Here we see multiple entries: an entry for an attributes group called `StructAttributes` and /// another one for `FieldAttributes`. The former has three defined attributes: `foo`, `bar` and /// `baz`. The generated structures will look like this in that case: /// /// ``` /// /// A comment. /// #[derive(Default, Clone, Debug)] /// pub struct StructAttributes { /// foo: Option, /// bar: Option, /// baz: bool, /// } /// /// #[derive(Hash)] /// #[derive(Default, Clone, Debug)] /// struct FieldAttributes { /// field_attr: Option, /// } /// ``` /// /// `foo` and `bar` attributes got translated to fields with `Option` type which contain the /// value of the attribute when one is specified. They are marked with `str` keyword which stands /// for string literals. The `baz` attribute, on the other hand, has `bool` type because it's an /// attribute without value marked by the `none` keyword. /// /// Currently the following literals are supported: /// /// * `str` - string literals; /// * `bool` - boolean literals; /// * `[str]` - lists of string literals (`#[macro_name(foo("bar", "baz"))]`); /// * `none` - no literal at all, the attribute is specified alone. /// /// The strings between braces are embedded into error messages produced when an attribute defined /// for one attribute group is used on another group where it is not defined. For example, if the /// `field_attr` attribute was encountered by the generated `StructAttributes::parse` method, the /// error message would say that it "is not allowed on structs". /// /// # Nested attribute lists /// /// It is possible to create nested lists for specific attributes. This is done as follows: /// /// ``` /// # use zvariant_utils::def_attrs; /// def_attrs! { /// crate zvariant; /// /// pub OuterAttributes("outer") { /// simple_attr bool, /// nested_attr { /// /// An example of nested attributes. /// pub InnerAttributes("inner") { /// inner_attr str /// } /// } /// }; /// } /// ``` /// /// The syntax for inner attributes is the same as for the outer attributes, but you can specify /// only one inner attribute per outer attribute. /// /// # Using attribute names for attribute lists /// /// It is possible to use multiple different "crate" names as follows: /// /// ``` /// # use zvariant_utils::def_attrs; /// def_attrs! { /// crate zvariant, zbus; /// /// pub FooAttributes("foo") { /// simple_attr bool /// }; /// } /// ``` /// /// It will be possible to use both `#[zvariant(...)]` and `#[zbus(...)]` attributes with /// `FooAttributes`. /// /// Don't forget to add all the supported attributes to your proc macro definition. /// /// # Calling the macro multiple times /// /// The macro generates static variables with hardcoded names. Calling the macro twice in the same /// scope will cause a name alias and thus will fail to compile. You need to place each macro /// invocation into a module in that case. /// /// # Errors /// /// The generated parse method checks for some error conditions: /// /// 1. Unknown attributes. When multiple attribute groups are defined in the same macro invocation, /// one gets a different error message when providing an attribute from a different attribute /// group. /// 2. Duplicate attributes. /// 3. Missing attribute value or present attribute value when none is expected. /// 4. Invalid literal type for attributes with values. #[macro_export] macro_rules! def_attrs { (@attr_ty str) => {::std::option::Option<::std::string::String>}; (@attr_ty bool) => {::std::option::Option}; (@attr_ty [str]) => {::std::option::Option<::std::vec::Vec<::std::string::String>>}; (@attr_ty none) => {bool}; (@attr_ty { $(#[$m:meta])* $vis:vis $name:ident($what:literal) { $($attr_name:ident $kind:tt),+ } }) => {::std::option::Option<$name>}; (@match_attr_with $attr_name:ident, $meta:ident, $self:ident, $matched:expr) => { if let ::std::option::Option::Some(value) = $matched? { if $self.$attr_name.is_some() { return ::std::result::Result::Err(::syn::Error::new( $meta.span(), ::std::concat!("duplicate `", ::std::stringify!($attr_name), "` attribute") )); } $self.$attr_name = ::std::option::Option::Some(value.value()); return Ok(()); } }; (@match_attr str $attr_name:ident, $meta:ident, $self:ident) => { $crate::def_attrs!( @match_attr_with $attr_name, $meta, $self, $crate::macros::match_attribute_with_str_value( $meta, ::std::stringify!($attr_name), ) ) }; (@match_attr bool $attr_name:ident, $meta:ident, $self:ident) => { $crate::def_attrs!( @match_attr_with $attr_name, $meta, $self, $crate::macros::match_attribute_with_bool_value( $meta, ::std::stringify!($attr_name), ) ) }; (@match_attr [str] $attr_name:ident, $meta:ident, $self:ident) => { if let Some(list) = $crate::macros::match_attribute_with_str_list_value( $meta, ::std::stringify!($attr_name), )? { if $self.$attr_name.is_some() { return ::std::result::Result::Err(::syn::Error::new( $meta.span(), concat!("duplicate `", stringify!($attr_name), "` attribute") )); } $self.$attr_name = Some(list); return Ok(()); } }; (@match_attr none $attr_name:ident, $meta:ident, $self:ident) => { if $crate::macros::match_attribute_without_value( $meta, ::std::stringify!($attr_name), )? { if $self.$attr_name { return ::std::result::Result::Err(::syn::Error::new( $meta.span(), concat!("duplicate `", stringify!($attr_name), "` attribute") )); } $self.$attr_name = true; return Ok(()); } }; (@match_attr { $(#[$m:meta])* $vis:vis $name:ident($what:literal) $body:tt } $attr_name:ident, $meta:expr, $self:ident) => { if $meta.path().is_ident(::std::stringify!($attr_name)) { if $self.$attr_name.is_some() { return ::std::result::Result::Err(::syn::Error::new( $meta.span(), concat!("duplicate `", stringify!($attr_name), "` attribute") )); } return match $meta { ::syn::Meta::List(meta) => { $self.$attr_name = ::std::option::Option::Some($name::parse_nested_metas( meta.parse_args_with(::syn::punctuated::Punctuated::<::syn::Meta, ::syn::Token![,]>::parse_terminated)? )?); ::std::result::Result::Ok(()) } ::syn::Meta::Path(_) => { $self.$attr_name = ::std::option::Option::Some($name::default()); ::std::result::Result::Ok(()) } ::syn::Meta::NameValue(_) => Err(::syn::Error::new( $meta.span(), ::std::format!(::std::concat!( "attribute `", ::std::stringify!($attr_name), "` must be either a list or a path" )), )) }; } }; (@def_ty str) => {}; (@def_ty bool) => {}; (@def_ty [str]) => {}; (@def_ty none) => {}; ( @def_ty { $(#[$m:meta])* $vis:vis $name:ident($what:literal) { $($attr_name:ident $kind:tt),+ } } ) => { // Recurse further to potentially define nested lists. $($crate::def_attrs!(@def_ty $kind);)+ $crate::def_attrs!( @def_struct $(#[$m])* $vis $name($what) { $($attr_name $kind),+ } ); }; ( @def_struct $(#[$m:meta])* $vis:vis $name:ident($what:literal) { $($attr_name:ident $kind:tt),+ } ) => { $(#[$m])* #[derive(Default, Clone, Debug)] $vis struct $name { $(pub $attr_name: $crate::def_attrs!(@attr_ty $kind)),+ } impl $name { pub fn parse_meta( &mut self, meta: &::syn::Meta ) -> ::syn::Result<()> { use ::syn::spanned::Spanned; // This creates subsequent if blocks for simplicity. Any block that is taken // either returns an error or sets the attribute field and returns success. $( $crate::def_attrs!(@match_attr $kind $attr_name, meta, self); )+ // None of the if blocks have been taken, return the appropriate error. let err = if ALLOWED_ATTRS.iter().any(|attr| meta.path().is_ident(attr)) { ::std::format!( ::std::concat!("attribute `{}` is not allowed on ", $what), meta.path().get_ident().unwrap() ) } else { ::std::format!("unknown attribute `{}`", meta.path().get_ident().unwrap()) }; return ::std::result::Result::Err(::syn::Error::new(meta.span(), err)); } pub fn parse_nested_metas(iter: I) -> syn::Result where I: ::std::iter::IntoIterator { let mut parsed = $name::default(); for nested_meta in iter { parsed.parse_meta(&nested_meta)?; } Ok(parsed) } pub fn parse(attrs: &[::syn::Attribute]) -> ::syn::Result { let mut parsed = $name::default(); for nested_meta in $crate::macros::iter_meta_lists( attrs, ALLOWED_LISTS, )? { parsed.parse_meta(&nested_meta)?; } Ok(parsed) } } }; ( crate $($list_name:ident),+; $( $(#[$m:meta])* $vis:vis $name:ident($what:literal) { $($attr_name:ident $kind:tt),+ } );+; ) => { static ALLOWED_ATTRS: &[&'static str] = &[ $($(::std::stringify!($attr_name),)+)+ ]; static ALLOWED_LISTS: &[&'static str] = &[ $(::std::stringify!($list_name),)+ ]; $( $crate::def_attrs!( @def_ty { $(#[$m])* $vis $name($what) { $($attr_name $kind),+ } } ); )+ } } /// Checks if a [`Type`]'s identifier is "Option". pub fn ty_is_option(ty: &Type) -> bool { match ty { Type::Path(TypePath { path: syn::Path { segments, .. }, .. }) => segments.last().unwrap().ident == "Option", _ => false, } } zvariant_utils-3.1.0/src/serialized.rs000064400000000000000000000013641046102023000161770ustar 00000000000000use static_assertions::assert_impl_all; /// The encoding format. #[derive(Debug, Default, PartialEq, Eq, Copy, Clone)] pub enum Format { /// [D-Bus](https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-marshaling) /// format. #[default] DBus, /// [GVariant](https://developer.gnome.org/glib/stable/glib-GVariant.html) format. #[cfg(feature = "gvariant")] GVariant, } assert_impl_all!(Format: Send, Sync, Unpin); impl std::fmt::Display for Format { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Format::DBus => write!(f, "D-Bus"), #[cfg(feature = "gvariant")] Format::GVariant => write!(f, "GVariant"), } } } zvariant_utils-3.1.0/src/signature/child.rs000064400000000000000000000023701046102023000171260ustar 00000000000000use std::ops::Deref; use super::Signature; /// A child signature of a container signature. #[derive(Debug, Clone)] pub enum Child { /// A static child signature. Static { child: &'static Signature }, /// A dynamic child signature. Dynamic { child: Box }, } static_assertions::assert_impl_all!(Child: Send, Sync, Unpin); impl Child { /// The underlying child `Signature`. pub const fn signature(&self) -> &Signature { match self { Child::Static { child } => child, Child::Dynamic { child } => child, } } /// The length of the child signature in string form. pub const fn string_len(&self) -> usize { self.signature().string_len() } } impl Deref for Child { type Target = Signature; fn deref(&self) -> &Self::Target { self.signature() } } impl From> for Child { fn from(child: Box) -> Self { Child::Dynamic { child } } } impl From for Child { fn from(child: Signature) -> Self { Child::Dynamic { child: Box::new(child), } } } impl From<&'static Signature> for Child { fn from(child: &'static Signature) -> Self { Child::Static { child } } } zvariant_utils-3.1.0/src/signature/error.rs000064400000000000000000000006061046102023000171740ustar 00000000000000use core::fmt; /// Error you get on failure to parse a signature string. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Error { /// Invalid signature. InvalidSignature, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::InvalidSignature => write!(f, "Invalid signature"), } } } zvariant_utils-3.1.0/src/signature/fields.rs000064400000000000000000000040311046102023000173050ustar 00000000000000use super::Signature; /// Signatures of the fields of a [`Signature::Structure`]. #[derive(Debug, Clone)] pub enum Fields { Static { fields: &'static [&'static Signature], }, Dynamic { fields: Box<[Signature]>, }, } static_assertions::assert_impl_all!(Fields: Send, Sync, Unpin); impl Fields { /// A iterator over the fields' signatures. pub fn iter(&self) -> impl Iterator { use std::slice::Iter; enum Fields<'a> { Static(Iter<'static, &'static Signature>), Dynamic(Iter<'a, Signature>), } impl<'a> Iterator for Fields<'a> { type Item = &'a Signature; fn next(&mut self) -> Option { match self { Fields::Static(iter) => iter.next().copied(), Fields::Dynamic(iter) => iter.next(), } } } match self { Self::Static { fields } => Fields::Static(fields.iter()), Self::Dynamic { fields } => Fields::Dynamic(fields.iter()), } } /// The number of fields. pub const fn len(&self) -> usize { match self { Self::Static { fields } => fields.len(), Self::Dynamic { fields } => fields.len(), } } /// Whether there are no fields. pub fn is_empty(&self) -> bool { self.len() == 0 } } impl From> for Fields { fn from(fields: Box<[Signature]>) -> Self { Fields::Dynamic { fields } } } impl From> for Fields { fn from(fields: Vec) -> Self { Fields::Dynamic { fields: fields.into(), } } } impl From<[Signature; N]> for Fields { fn from(fields: [Signature; N]) -> Self { Fields::Dynamic { fields: fields.into(), } } } impl From<&'static [&'static Signature]> for Fields { fn from(fields: &'static [&'static Signature]) -> Self { Fields::Static { fields } } } zvariant_utils-3.1.0/src/signature/mod.rs000064400000000000000000000633141046102023000166270ustar 00000000000000mod child; pub use child::Child; mod fields; pub use fields::Fields; mod error; pub use error::Error; use serde::{Deserialize, Serialize}; use core::fmt; use std::{ fmt::{Display, Formatter}, hash::Hash, str::FromStr, }; use crate::serialized::Format; /// A D-Bus signature in parsed form. /// /// This is similar to the [`zvariant::Signature`] type, but unlike `zvariant::Signature`, this is a /// parsed representation of a signature. Our (de)serialization API primarily uses this type for /// efficiency. /// /// # Examples /// /// Typically, you'd create a `Signature` from a string: /// /// ``` /// use std::str::FromStr; /// use zvariant::Signature; /// /// let sig = Signature::from_str("a{sv}").unwrap(); /// assert_eq!(sig.to_string(), "a{sv}"); /// /// let sig = Signature::from_str("(xa{bs}as)").unwrap(); /// assert_eq!(sig.to_string(), "(xa{bs}as)"); /// ``` /// /// [`zvariant::Signature`]: https://docs.rs/zvariant/latest/zvariant/struct.Signature.html #[derive(Debug, Default, Clone)] pub enum Signature { // Basic types /// The signature for the unit type (`()`). This is not a valid D-Bus signature, but is used to /// represnt "no data" (for example, a D-Bus method call without any arguments will have this /// as its body signature). /// /// # Warning /// /// This variant only exists for convenience and must only be used as a top-level signature. If /// used inside container signatures, it will cause errors and in somce cases, panics. It's /// best to not use it directly. #[default] Unit, /// The signature for an 8-bit unsigned integer (AKA a byte). U8, /// The signature for a boolean. Bool, /// The signature for a 16-bit signed integer. I16, /// The signature for a 16-bit unsigned integer. U16, /// The signature for a 32-bit signed integer. I32, /// The signature for a 32-bit unsigned integer. U32, /// The signature for a 64-bit signed integer. I64, /// The signature for a 64-bit unsigned integer. U64, /// The signature for a 64-bit floating point number. F64, /// The signature for a string. Str, /// The signature for a signature. Signature, /// The signature for an object path. ObjectPath, /// The signature for a variant. Variant, /// The signature for a file descriptor. #[cfg(unix)] Fd, // Container types /// The signature for an array. Array(Child), /// The signature for a dictionary. Dict { /// The signature for the key. key: Child, /// The signature for the value. value: Child, }, /// The signature for a structure. Structure(Fields), /// The signature for a maybe type (gvariant-specific). #[cfg(feature = "gvariant")] Maybe(Child), } impl Signature { /// The size of the string form of `self`. pub const fn string_len(&self) -> usize { match self { Signature::Unit => 0, Signature::U8 | Signature::Bool | Signature::I16 | Signature::U16 | Signature::I32 | Signature::U32 | Signature::I64 | Signature::U64 | Signature::F64 | Signature::Str | Signature::Signature | Signature::ObjectPath | Signature::Variant => 1, #[cfg(unix)] Signature::Fd => 1, Signature::Array(child) => 1 + child.string_len(), Signature::Dict { key, value } => 3 + key.string_len() + value.string_len(), Signature::Structure(fields) => { let mut len = 2; let mut i = 0; while i < fields.len() { len += match fields { Fields::Static { fields } => fields[i].string_len(), Fields::Dynamic { fields } => fields[i].string_len(), }; i += 1; } len } #[cfg(feature = "gvariant")] Signature::Maybe(child) => 1 + child.string_len(), } } /// Write the string form of `self` to the given formatter. /// /// This produces the same output as the `Display::fmt`, unless `self` is a /// [`Signature::Structure`], in which case the written string will **not** be wrapped in /// parenthesis (`()`). pub fn write_as_string_no_parens(&self, write: &mut impl std::fmt::Write) -> fmt::Result { self.write_as_string(write, false) } /// Convert `self` to a string, without any enclosing parenthesis. /// /// This produces the same output as the [`Signature::to_string`], unless `self` is a /// [`Signature::Structure`], in which case the written string will **not** be wrapped in /// parenthesis (`()`). pub fn to_string_no_parens(&self) -> String { let mut s = String::with_capacity(self.string_len()); self.write_as_string(&mut s, false).unwrap(); s } /// Convert `self` to a string. /// /// This produces the same output as the `ToString::to_string`, except it preallocates the /// required memory and hence avoids reallocations and moving of data. #[allow(clippy::inherent_to_string_shadow_display)] pub fn to_string(&self) -> String { let mut s = String::with_capacity(self.string_len()); self.write_as_string(&mut s, true).unwrap(); s } /// Parse signature from a byte slice. pub fn from_bytes(bytes: &[u8]) -> Result { parse(bytes, false) } /// Create a `Signature::Structure` for a given set of field signatures. pub fn structure(fields: F) -> Self where F: Into, { Signature::Structure(fields.into()) } /// Create a `Signature::Structure` for a given set of static field signatures. pub const fn static_structure(fields: &'static [&'static Signature]) -> Self { Signature::Structure(Fields::Static { fields }) } /// Create a `Signature::Array` for a given child signature. pub fn array(child: C) -> Self where C: Into, { Signature::Array(child.into()) } /// Create a `Signature::Array` for a given static child signature. pub const fn static_array(child: &'static Signature) -> Self { Signature::Array(Child::Static { child }) } /// Create a `Signature::Dict` for a given key and value signatures. pub fn dict(key: K, value: V) -> Self where K: Into, V: Into, { Signature::Dict { key: key.into(), value: value.into(), } } /// Create a `Signature::Dict` for a given static key and value signatures. pub const fn static_dict(key: &'static Signature, value: &'static Signature) -> Self { Signature::Dict { key: Child::Static { child: key }, value: Child::Static { child: value }, } } /// Create a `Signature::Maybe` for a given child signature. #[cfg(feature = "gvariant")] pub fn maybe(child: C) -> Self where C: Into, { Signature::Maybe(child.into()) } /// Create a `Signature::Maybe` for a given static child signature. #[cfg(feature = "gvariant")] pub const fn static_maybe(child: &'static Signature) -> Self { Signature::Maybe(Child::Static { child }) } /// The required padding alignment for the given format. pub fn alignment(&self, format: Format) -> usize { match format { Format::DBus => self.alignment_dbus(), #[cfg(feature = "gvariant")] Format::GVariant => self.alignment_gvariant(), } } fn alignment_dbus(&self) -> usize { match self { Signature::U8 | Signature::Variant | Signature::Signature => 1, Signature::I16 | Signature::U16 => 2, Signature::I32 | Signature::U32 | Signature::Bool | Signature::Str | Signature::ObjectPath | Signature::Array(_) | Signature::Dict { .. } => 4, Signature::I64 | Signature::U64 | Signature::F64 | Signature::Unit | Signature::Structure(_) => 8, #[cfg(unix)] Signature::Fd => 4, #[cfg(feature = "gvariant")] Signature::Maybe(_) => unreachable!("Maybe type is not supported in D-Bus"), } } #[cfg(feature = "gvariant")] fn alignment_gvariant(&self) -> usize { use std::cmp::max; match self { Signature::Unit | Signature::U8 | Signature::I16 | Signature::U16 | Signature::I32 | Signature::U32 | Signature::F64 | Signature::Bool | Signature::I64 | Signature::U64 | Signature::Signature => self.alignment_dbus(), #[cfg(unix)] Signature::Fd => self.alignment_dbus(), Signature::Str | Signature::ObjectPath => 1, Signature::Variant => 8, Signature::Array(child) | Signature::Maybe(child) => child.alignment_gvariant(), Signature::Dict { key, value } => { max(key.alignment_gvariant(), value.alignment_gvariant()) } Signature::Structure(fields) => fields .iter() .map(Signature::alignment_gvariant) .max() .unwrap_or(1), } } /// Check if the signature is of a fixed-sized type. #[cfg(feature = "gvariant")] pub fn is_fixed_sized(&self) -> bool { match self { Signature::Unit | Signature::U8 | Signature::Bool | Signature::I16 | Signature::U16 | Signature::I32 | Signature::U32 | Signature::I64 | Signature::U64 | Signature::F64 => true, #[cfg(unix)] Signature::Fd => true, Signature::Str | Signature::Signature | Signature::ObjectPath | Signature::Variant | Signature::Array(_) | Signature::Dict { .. } | Signature::Maybe(_) => false, Signature::Structure(fields) => fields.iter().all(|f| f.is_fixed_sized()), } } fn write_as_string(&self, w: &mut impl std::fmt::Write, outer_parens: bool) -> fmt::Result { match self { Signature::Unit => write!(w, ""), Signature::U8 => write!(w, "y"), Signature::Bool => write!(w, "b"), Signature::I16 => write!(w, "n"), Signature::U16 => write!(w, "q"), Signature::I32 => write!(w, "i"), Signature::U32 => write!(w, "u"), Signature::I64 => write!(w, "x"), Signature::U64 => write!(w, "t"), Signature::F64 => write!(w, "d"), Signature::Str => write!(w, "s"), Signature::Signature => write!(w, "g"), Signature::ObjectPath => write!(w, "o"), Signature::Variant => write!(w, "v"), #[cfg(unix)] Signature::Fd => write!(w, "h"), Signature::Array(array) => write!(w, "a{}", **array), Signature::Dict { key, value } => { write!(w, "a{{")?; write!(w, "{}{}", **key, **value)?; write!(w, "}}") } Signature::Structure(fields) => { if outer_parens { write!(w, "(")?; } for field in fields.iter() { write!(w, "{}", field)?; } if outer_parens { write!(w, ")")?; } Ok(()) } #[cfg(feature = "gvariant")] Signature::Maybe(maybe) => write!(w, "m{}", **maybe), } } } impl Display for Signature { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { self.write_as_string(f, true) } } impl FromStr for Signature { type Err = Error; fn from_str(s: &str) -> Result { parse(s.as_bytes(), false) } } impl TryFrom<&str> for Signature { type Error = Error; fn try_from(value: &str) -> Result { Signature::from_str(value) } } impl TryFrom<&[u8]> for Signature { type Error = Error; fn try_from(value: &[u8]) -> Result { parse(value, false) } } /// Validate the given signature string. pub fn validate(bytes: &[u8]) -> Result<(), Error> { parse(bytes, true).map(|_| ()) } /// Parse a signature string into a `Signature`. /// /// When `check_only` is true, the function will not allocate memory for the dynamic types. /// Instead it will return dummy values in the parsed Signature. fn parse(bytes: &[u8], check_only: bool) -> Result { use winnow::{ combinator::{alt, delimited, empty, eof, fail, repeat}, dispatch, token::any, Parser, }; let unit = eof.map(|_| Signature::Unit); // `many1` allocates so we only want to use it when `check_only == false` type ManyError = winnow::error::ErrMode<()>; fn many(bytes: &mut &[u8], check_only: bool, top_level: bool) -> Result { let parser = |s: &mut _| parse_signature(s, check_only); if check_only { return repeat(1.., parser) .map(|_: ()| Signature::Unit) .parse_next(bytes); } // Avoid the allocation of `Vec` in case of a single signature on the top-level. // This is a a very common case, especially in variants, where the signature needs to be // parsed at runtime. enum SignatureList { Unit, One(Signature), Structure(Vec), } repeat(1.., parser) .fold( || SignatureList::Unit, |acc, signature| match acc { // On the top-level, we want to return the signature directly if there is only // one. SignatureList::Unit if top_level => SignatureList::One(signature), SignatureList::Unit => SignatureList::Structure(vec![signature]), SignatureList::One(one) => SignatureList::Structure(vec![one, signature]), SignatureList::Structure(mut signatures) => { signatures.push(signature); SignatureList::Structure(signatures) } }, ) .map(|sig_list| match sig_list { SignatureList::Unit => Signature::Unit, SignatureList::One(sig) => sig, SignatureList::Structure(signatures) => Signature::structure(signatures), }) .parse_next(bytes) } fn parse_signature(bytes: &mut &[u8], check_only: bool) -> Result { let parse_with_context = |bytes: &mut _| parse_signature(bytes, check_only); let simple_type = dispatch! {any; b'y' => empty.value(Signature::U8), b'b' => empty.value(Signature::Bool), b'n' => empty.value(Signature::I16), b'q' => empty.value(Signature::U16), b'i' => empty.value(Signature::I32), b'u' => empty.value(Signature::U32), b'x' => empty.value(Signature::I64), b't' => empty.value(Signature::U64), b'd' => empty.value(Signature::F64), b's' => empty.value(Signature::Str), b'g' => empty.value(Signature::Signature), b'o' => empty.value(Signature::ObjectPath), b'v' => empty.value(Signature::Variant), _ => fail, }; let dict = ( b'a', delimited(b'{', (parse_with_context, parse_with_context), b'}'), ) .map(|(_, (key, value))| { if check_only { return Signature::Dict { key: Signature::Unit.into(), value: Signature::Unit.into(), }; } Signature::Dict { key: key.into(), value: value.into(), } }); let array = (b'a', parse_with_context).map(|(_, child)| { if check_only { return Signature::Array(Signature::Unit.into()); } Signature::Array(child.into()) }); let structure = delimited(b'(', |s: &mut _| many(s, check_only, false), b')'); #[cfg(feature = "gvariant")] let maybe = (b'm', parse_with_context).map(|(_, child)| { if check_only { return Signature::Maybe(Signature::Unit.into()); } Signature::Maybe(child.into()) }); alt(( simple_type, dict, array, structure, #[cfg(feature = "gvariant")] maybe, // FIXME: Should be part of `simple_type` but that's not possible right now: // https://github.com/winnow-rs/winnow/issues/609 #[cfg(unix)] b'h'.map(|_| Signature::Fd), )) .parse_next(bytes) } let signature = alt((unit, |s: &mut _| many(s, check_only, true))) .parse(bytes) .map_err(|_| Error::InvalidSignature)?; Ok(signature) } impl PartialEq for Signature { fn eq(&self, other: &Self) -> bool { match (self, other) { (Signature::Unit, Signature::Unit) | (Signature::U8, Signature::U8) | (Signature::Bool, Signature::Bool) | (Signature::I16, Signature::I16) | (Signature::U16, Signature::U16) | (Signature::I32, Signature::I32) | (Signature::U32, Signature::U32) | (Signature::I64, Signature::I64) | (Signature::U64, Signature::U64) | (Signature::F64, Signature::F64) | (Signature::Str, Signature::Str) | (Signature::Signature, Signature::Signature) | (Signature::ObjectPath, Signature::ObjectPath) | (Signature::Variant, Signature::Variant) => true, #[cfg(unix)] (Signature::Fd, Signature::Fd) => true, (Signature::Array(a), Signature::Array(b)) => a.eq(&**b), ( Signature::Dict { key: key_a, value: value_a, }, Signature::Dict { key: key_b, value: value_b, }, ) => key_a.eq(&**key_b) && value_a.eq(&**value_b), (Signature::Structure(a), Signature::Structure(b)) => a.iter().eq(b.iter()), #[cfg(feature = "gvariant")] (Signature::Maybe(a), Signature::Maybe(b)) => a.eq(&**b), _ => false, } } } impl Eq for Signature {} impl PartialEq<&str> for Signature { fn eq(&self, other: &&str) -> bool { match self { Signature::Unit => other.is_empty(), Self::Bool => *other == "b", Self::U8 => *other == "y", Self::I16 => *other == "n", Self::U16 => *other == "q", Self::I32 => *other == "i", Self::U32 => *other == "u", Self::I64 => *other == "x", Self::U64 => *other == "t", Self::F64 => *other == "d", Self::Str => *other == "s", Self::Signature => *other == "g", Self::ObjectPath => *other == "o", Self::Variant => *other == "v", #[cfg(unix)] Self::Fd => *other == "h", Self::Array(child) => { if other.len() < 2 || !other.starts_with('a') { return false; } child.eq(&other[1..]) } Self::Dict { key, value } => { if other.len() < 4 || !other.starts_with("a{") || !other.ends_with('}') { return false; } let (key_str, value_str) = other[2..other.len() - 1].split_at(1); key.eq(key_str) && value.eq(value_str) } Self::Structure(fields) => { let string_len = self.string_len(); // self.string_len() will always take `()` into account so it can't be a smaller // number than `other.len()`. if string_len < other.len() // Their length is either equal (i-e `other` has outer `()`) or `other` has no // outer `()`. || (string_len != other.len() && string_len != other.len() + 2) { return false; } let fields_str = if string_len == other.len() { &other[1..other.len() - 1] } else { // No outer `()`. if other.is_empty() { return false; } other }; let mut start = 0; for field in fields.iter() { let len = field.string_len(); let end = start + len; if end > fields_str.len() { return false; } if !field.eq(&fields_str[start..end]) { return false; } start += len; } true } #[cfg(feature = "gvariant")] Self::Maybe(child) => { if other.len() < 2 || !other.starts_with('m') { return false; } child.eq(&other[1..]) } } } } impl PartialEq for Signature { fn eq(&self, other: &str) -> bool { self.eq(&other) } } impl PartialOrd for Signature { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Ord for Signature { fn cmp(&self, other: &Self) -> std::cmp::Ordering { match (self, other) { (Signature::Unit, Signature::Unit) | (Signature::U8, Signature::U8) | (Signature::Bool, Signature::Bool) | (Signature::I16, Signature::I16) | (Signature::U16, Signature::U16) | (Signature::I32, Signature::I32) | (Signature::U32, Signature::U32) | (Signature::I64, Signature::I64) | (Signature::U64, Signature::U64) | (Signature::F64, Signature::F64) | (Signature::Str, Signature::Str) | (Signature::Signature, Signature::Signature) | (Signature::ObjectPath, Signature::ObjectPath) | (Signature::Variant, Signature::Variant) => std::cmp::Ordering::Equal, #[cfg(unix)] (Signature::Fd, Signature::Fd) => std::cmp::Ordering::Equal, (Signature::Array(a), Signature::Array(b)) => a.cmp(b), ( Signature::Dict { key: key_a, value: value_a, }, Signature::Dict { key: key_b, value: value_b, }, ) => match key_a.cmp(key_b) { std::cmp::Ordering::Equal => value_a.cmp(value_b), other => other, }, (Signature::Structure(a), Signature::Structure(b)) => a.iter().cmp(b.iter()), #[cfg(feature = "gvariant")] (Signature::Maybe(a), Signature::Maybe(b)) => a.cmp(b), (_, _) => std::cmp::Ordering::Equal, } } } impl Serialize for Signature { fn serialize(&self, serializer: S) -> Result { serializer.serialize_str(&self.to_string()) } } impl<'de> Deserialize<'de> for Signature { fn deserialize>(deserializer: D) -> Result { <&str>::deserialize(deserializer).and_then(|s| { Signature::from_str(s).map_err(|e| serde::de::Error::custom(e.to_string())) }) } } impl Hash for Signature { fn hash(&self, state: &mut H) { match self { Signature::Unit => 0.hash(state), Signature::U8 => 1.hash(state), Signature::Bool => 2.hash(state), Signature::I16 => 3.hash(state), Signature::U16 => 4.hash(state), Signature::I32 => 5.hash(state), Signature::U32 => 6.hash(state), Signature::I64 => 7.hash(state), Signature::U64 => 8.hash(state), Signature::F64 => 9.hash(state), Signature::Str => 10.hash(state), Signature::Signature => 11.hash(state), Signature::ObjectPath => 12.hash(state), Signature::Variant => 13.hash(state), #[cfg(unix)] Signature::Fd => 14.hash(state), Signature::Array(child) => { 15.hash(state); child.hash(state); } Signature::Dict { key, value } => { 16.hash(state); key.hash(state); value.hash(state); } Signature::Structure(fields) => { 17.hash(state); fields.iter().for_each(|f| f.hash(state)); } #[cfg(feature = "gvariant")] Signature::Maybe(child) => { 18.hash(state); child.hash(state); } } } } impl From<&Signature> for Signature { fn from(value: &Signature) -> Self { value.clone() } } #[cfg(test)] mod tests; zvariant_utils-3.1.0/src/signature/tests.rs000064400000000000000000000134071046102023000172100ustar 00000000000000use super::*; use std::{ hash::{DefaultHasher, Hash, Hasher}, str::FromStr, }; macro_rules! validate { ($($signature:literal => $expected:expr),+) => { $( assert!(validate($signature.as_bytes()).is_ok()); let parsed = Signature::from_str($signature).unwrap(); assert_eq!(parsed, $expected); assert_eq!(parsed, $signature); match parsed { Signature::Structure(_) => { assert!( $signature.len() == parsed.string_len() - 2 || $signature.len() == parsed.string_len() ); } _ => { assert_eq!(parsed.string_len(), $signature.len()); } } )+ }; } #[test] fn validate_strings() { validate!( "" => Signature::Unit, "y" => Signature::U8, "b" => Signature::Bool, "n" => Signature::I16, "q" => Signature::U16, "i" => Signature::I32, "u" => Signature::U32, "x" => Signature::I64, "t" => Signature::U64, "d" => Signature::F64, "s" => Signature::Str, "g" => Signature::Signature, "o" => Signature::ObjectPath, "v" => Signature::Variant, "xs" => Signature::structure(&[&Signature::I64, &Signature::Str][..]), "(ysa{sd})" => Signature::static_structure( &[ &Signature::U8, &Signature::Str, &Signature::Dict { key: Child::Static { child: &Signature::Str }, value: Child::Static { child: &Signature::F64 }, }, ] ), "a(y)" => Signature::static_array( &Signature::Structure(Fields::Static { fields: &[&Signature::U8] }), ), "a{yy}" => Signature::static_dict(&Signature::U8, &Signature::U8), "(yy)" => Signature::static_structure(&[&Signature::U8, &Signature::U8]), "a{sd}" => Signature::static_dict(&Signature::Str, &Signature::F64), "a{yy}" => Signature::static_dict(&Signature::U8, &Signature::U8), "a{sv}" => Signature::static_dict(&Signature::Str, &Signature::Variant), "a{sa{sv}}" => Signature::static_dict( &Signature::Str, &Signature::Dict { key: Child::Static { child: &Signature::Str, }, value: Child::Static { child: &Signature::Variant } }, ), "a{sa(ux)}" => Signature::static_dict( &Signature::Str, &Signature::Array(Child::Static { child: &Signature::Structure(Fields::Static { fields: &[&Signature::U32, &Signature::I64] }), }), ), "(x)" => Signature::static_structure(&[&Signature::I64]), "(x(isy))" => Signature::static_structure(&[ &Signature::I64, &Signature::Structure(Fields::Static { fields: &[&Signature::I32, &Signature::Str, &Signature::U8] }), ]), "(xa(isy))" => Signature::static_structure(&[ &Signature::I64, &Signature::Array(Child::Static { child: &Signature::Structure(Fields::Static { fields: &[&Signature::I32, &Signature::Str, &Signature::U8] }), }), ]), "(xa(s))" => Signature::static_structure(&[ &Signature::I64, &Signature::Array(Child::Static { child: &Signature::Structure(Fields::Static { fields: &[&Signature::Str] }), }), ]), "((yyyyuu)a(yv))" => Signature::static_structure(&[ &Signature::Structure(Fields::Static { fields: &[ &Signature::U8, &Signature::U8, &Signature::U8, &Signature::U8, &Signature::U32, &Signature::U32, ], }), &Signature::Array(Child::Static { child: &Signature::Structure(Fields::Static { fields: &[&Signature::U8, &Signature::Variant], }), }), ]) ); #[cfg(unix)] validate!("h" => Signature::Fd); } macro_rules! invalidate { ($($signature:literal),+) => { $( assert!(validate($signature.as_bytes()).is_err()); )+ }; } #[test] fn invalid_strings() { invalidate!( "a", "a{}", "a{y", "a{y}", "a{y}a{y}", "a{y}a{y}a{y}", "z", "()", "(x", "(x())", "(xa()", "(xa(s)", "(xs", "xs)", "s/", "a{yz}" ); } #[test] fn hash() { // We need to test if all variants of Signature hold this invariant: test_hash(&Signature::U16, &Signature::U16); test_hash( &Signature::array(Signature::U16), &Signature::static_array(&Signature::U16), ); test_hash( &Signature::dict(Signature::U32, Signature::Str), &Signature::static_dict(&Signature::U32, &Signature::Str), ); test_hash( &Signature::structure([Signature::Str, Signature::U64]), &Signature::static_structure(&[&Signature::Str, &Signature::U64]), ); } fn test_hash(signature1: &Signature, signature2: &Signature) { assert_eq!(signature1, signature2); let mut hasher = DefaultHasher::new(); signature1.hash(&mut hasher); let hash1 = hasher.finish(); let mut hasher = DefaultHasher::new(); signature2.hash(&mut hasher); let hash2 = hasher.finish(); assert_eq!(hash1, hash2); }