1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
use crate::{parse_msg::match_lines, DataType, Error, FieldInfo, MessagePath, Result, Value};
use serde_derive::{Deserialize, Serialize};
use std::collections::HashMap;
use std::convert::TryFrom;
use std::fmt;
use std::fmt::Formatter;
/// A ROS message parsed from a `msg` file.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(into = "MsgSerde")]
#[serde(try_from = "MsgSerde")]
pub struct Msg {
path: MessagePath,
fields: Vec<FieldInfo>,
source: String,
}
impl fmt::Display for Msg {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
self.source.fmt(f)
}
}
impl Msg {
/// Create a message from a passed in path and source.
///
/// # Errors
///
/// Returns an error if there is an error parsing the message source.
///
/// # Examples
///
/// ```
/// # use ros_message::Msg;
/// # use std::convert::TryInto;
/// #
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let message = Msg::new(
/// "foo/Bar".try_into()?,
/// r#"# a comment that is ignored
/// Header header
/// uint32 a
/// byte[16] b
/// geometry_msgs/Point[] point
/// uint32 FOO=5
/// string SOME_TEXT=this is # some text, don't be fooled by the hash
/// "#,
/// )?;
///
/// assert_eq!(message.path(), &"foo/Bar".try_into()?);
/// assert_eq!(message.fields().len(), 6);
/// # Ok(())
/// # }
/// ```
pub fn new(path: MessagePath, source: &str) -> Result<Msg> {
let source = source.trim().to_owned();
let fields = match_lines(&source)?;
Ok(Msg {
path,
fields,
source,
})
}
/// Returns a map of all constant fields inside the message, with their values parsed.
///
/// # Examples
///
/// ```
/// # use ros_message::{Msg, Value};
/// # use std::convert::TryInto;
/// #
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let message = Msg::new(
/// "foo/Bar".try_into()?,
/// r#"# a comment that is ignored
/// Header header
/// uint32 a
/// byte[16] b
/// geometry_msgs/Point[] point
/// uint32 FOO=5
/// string SOME_TEXT=this is # some text, don't be fooled by the hash
/// "#,
/// )?;
///
/// let constants = message.constants();
///
/// assert_eq!(constants.len(), 2);
/// assert_eq!(constants.get("FOO"), Some(&Value::U32(5)));
/// assert_eq!(
/// constants.get("SOME_TEXT"),
/// Some(&Value::String("this is # some text, don't be fooled by the hash".into())),
/// );
/// # Ok(())
/// # }
/// ```
pub fn constants(&self) -> HashMap<String, Value> {
self.fields
.iter()
.filter_map(|field| {
let value = field.const_value()?.clone();
Some((field.name().into(), value))
})
.collect()
}
/// Returns the path of the message.
pub fn path(&self) -> &MessagePath {
&self.path
}
/// Returns a slice of all fields.
pub fn fields(&self) -> &[FieldInfo] {
&self.fields
}
/// Returns the original source.
pub fn source(&self) -> &str {
&self.source
}
/// Returns a all message paths that this message directly depends upon.
///
/// They are listed in the order that they appear in in the message, and duplicates
/// are allowed.
///
/// Indirect dependencies are not included, and if you want an exhaustive list of all
/// dependencies, you have to manually traverse every message being depended upon.
/// # Examples
///
/// ```
/// # use ros_message::Msg;
/// # use std::convert::TryInto;
/// #
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let message = Msg::new(
/// "foo/Bar".try_into()?,
/// r#"
/// Header header
/// geometry_msgs/Point[] point1
/// Point[] point2
/// foo/Point[] point2_but_with_global_path
/// foo/Baz[] baz
/// "#,
/// )?;
///
/// let dependencies = message.dependencies();
///
/// assert_eq!(dependencies, vec![
/// "std_msgs/Header".try_into()?,
/// "geometry_msgs/Point".try_into()?,
/// "foo/Point".try_into()?,
/// "foo/Point".try_into()?,
/// "foo/Baz".try_into()?,
/// ]);
/// # Ok(())
/// # }
/// ```
pub fn dependencies(&self) -> Vec<MessagePath> {
self.fields
.iter()
.filter_map(|field| match field.datatype() {
DataType::LocalMessage(ref name) => Some(self.path.peer(name)),
DataType::GlobalMessage(ref message) => Some(message.clone()),
_ => None,
})
.collect()
}
/// Returns the MD5 sum of this message.
///
/// Any direct dependency must have its MD5 sum provided in the passed in hashes.
///
/// All direct dependencies are returned by the `dependencies()` method.
///
/// # Errors
///
/// An error is returned if some dependency is missing in the hashes.
#[cfg(test)]
pub fn calculate_md5(&self, hashes: &HashMap<MessagePath, String>) -> Result<String> {
use md5::{Digest, Md5};
let mut hasher = Md5::new();
hasher.update(&self.get_md5_representation(hashes)?);
Ok(hex::encode(hasher.finalize()))
}
/// Returns the full MD5 representation of the message.
///
/// This is the string that is sent to the MD5 hasher to digest.
///
/// # Errors
///
/// An error is returned if some dependency is missing in the hashes.
///
/// # Examples
///
/// ```
/// # use ros_message::Msg;
/// # use std::convert::TryInto;
/// # use std::collections::HashMap;
/// #
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let message = Msg::new(
/// "foo/Bar".try_into()?,
/// r#"# a comment that is ignored
/// Header header
/// uint32 a
/// byte[16] b
/// geometry_msgs/Point[] point
/// Baz baz
/// uint32 FOO=5
/// string SOME_TEXT=this is # some text, don't be fooled by the hash
/// "#,
/// )?;
///
/// let mut hashes = HashMap::new();
/// hashes.insert("std_msgs/Header".try_into()?, "hash1".into());
/// hashes.insert("geometry_msgs/Point".try_into()?, "hash2".into());
/// hashes.insert("foo/Baz".try_into()?, "hash3".into());
///
/// let representation = message.get_md5_representation(&hashes)?;
///
/// assert_eq!(
/// representation,
/// r#"uint32 FOO=5
/// string SOME_TEXT=this is # some text, don't be fooled by the hash
/// hash1 header
/// uint32 a
/// byte[16] b
/// hash2 point
/// hash3 baz"#);
/// # Ok(())
/// # }
/// ```
pub fn get_md5_representation(&self, hashes: &HashMap<MessagePath, String>) -> Result<String> {
let constants = self
.fields
.iter()
.filter(|v| v.is_constant())
.map(|v| v.md5_string(self.path.package(), hashes))
.collect::<Result<Vec<String>>>()?;
let fields = self
.fields
.iter()
.filter(|v| !v.is_constant())
.map(|v| v.md5_string(self.path.package(), hashes))
.collect::<Result<Vec<String>>>()?;
let representation = constants
.into_iter()
.chain(fields)
.collect::<Vec<_>>()
.join("\n");
Ok(representation)
}
/// Returns true if the message has a header field.
///
/// A header field is a unit value named `header` of type `std_msgs/Header`.
/// The package can be elided in this special case, no matter the package that
/// the containing message is located in.
pub fn has_header(&self) -> bool {
self.fields.iter().any(FieldInfo::is_header)
}
}
#[derive(Serialize, Deserialize)]
struct MsgSerde {
path: MessagePath,
source: String,
}
impl TryFrom<MsgSerde> for Msg {
type Error = Error;
fn try_from(src: MsgSerde) -> Result<Self> {
Self::new(src.path, &src.source)
}
}
impl From<Msg> for MsgSerde {
fn from(src: Msg) -> Self {
Self {
path: src.path,
source: src.source,
}
}
}