Fix clippy warnings

This commit is contained in:
aeon 2022-11-25 00:40:39 +08:00
parent abdf2f5343
commit 6096deec5b
9 changed files with 77 additions and 73 deletions

View File

@ -1,5 +1,5 @@
/// The status of a goal. /// The status of a goal.
#[derive(Debug, Copy, Clone, PartialEq)] #[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum GoalStatus { pub enum GoalStatus {
Unknown, Unknown,
Accepted, Accepted,

View File

@ -113,7 +113,7 @@ impl UntypedClient_ {
&mut self, &mut self,
msg: serde_json::Value, msg: serde_json::Value,
) -> Result<impl Future<Output = Result<Result<serde_json::Value>>>> { ) -> Result<impl Future<Output = Result<Result<serde_json::Value>>>> {
let mut native_msg = (self.service_type.make_request_msg)(); let native_msg = (self.service_type.make_request_msg)();
native_msg.from_json(msg)?; native_msg.from_json(msg)?;
let mut seq_no = 0i64; let mut seq_no = 0i64;

View File

@ -102,7 +102,7 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_context_drop() -> () { fn test_context_drop() {
{ {
let ctx = Context::create().unwrap(); let ctx = Context::create().unwrap();
assert!(ctx.is_valid()); assert!(ctx.is_valid());

View File

@ -196,7 +196,7 @@ impl UntypedActionSupport {
serde_json::from_value(goal).expect("TODO: move this error handling"); serde_json::from_value(goal).expect("TODO: move this error handling");
let request_msg = T::make_goal_request_msg(goal_id, goal_msg); let request_msg = T::make_goal_request_msg(goal_id, goal_msg);
let json = serde_json::to_value(request_msg).expect("TODO: move this error handling"); let json = serde_json::to_value(request_msg).expect("TODO: move this error handling");
let mut native_untyped = WrappedNativeMsgUntyped::new::< let native_untyped = WrappedNativeMsgUntyped::new::<
<<T as WrappedActionTypeSupport>::SendGoal as WrappedServiceTypeSupport>::Request, <<T as WrappedActionTypeSupport>::SendGoal as WrappedServiceTypeSupport>::Request,
>(); >();
native_untyped native_untyped
@ -239,7 +239,7 @@ impl UntypedActionSupport {
let request_msg = T::make_result_request_msg(uuid_msg); let request_msg = T::make_result_request_msg(uuid_msg);
let json = serde_json::to_value(request_msg).expect("TODO: move this error handling"); let json = serde_json::to_value(request_msg).expect("TODO: move this error handling");
let mut native_untyped = WrappedNativeMsgUntyped::new::< let native_untyped = WrappedNativeMsgUntyped::new::<
<<T as WrappedActionTypeSupport>::GetResult as WrappedServiceTypeSupport>::Request, <<T as WrappedActionTypeSupport>::GetResult as WrappedServiceTypeSupport>::Request,
>(); >();
@ -322,7 +322,7 @@ impl WrappedNativeMsgUntyped {
}) })
} }
pub fn from_json(&mut self, json: serde_json::Value) -> Result<()> { pub fn from_json(&self, json: serde_json::Value) -> Result<()> {
(self.msg_from_json)(self.msg, json).map_err(|serde_err| Error::SerdeError { (self.msg_from_json)(self.msg, json).map_err(|serde_err| Error::SerdeError {
err: serde_err.to_string(), err: serde_err.to_string(),
}) })
@ -556,7 +556,7 @@ mod tests {
msg.positions.push(39.0); msg.positions.push(39.0);
msg.positions.push(34.0); msg.positions.push(34.0);
let mut new_native = WrappedNativeMsg::<JointTrajectoryPoint>::from(&msg); let mut new_native = WrappedNativeMsg::<JointTrajectoryPoint>::from(&msg);
unsafe { *((*new_native).positions.data) = 88.9 }; unsafe { *new_native.positions.data = 88.9 };
let new_msg = JointTrajectoryPoint::from_native(&new_native); let new_msg = JointTrajectoryPoint::from_native(&new_native);
println!("{:#?}", new_msg); println!("{:#?}", new_msg);
assert_ne!(msg, new_msg); assert_ne!(msg, new_msg);
@ -569,7 +569,7 @@ mod tests {
msg.positions.push(34.0); msg.positions.push(34.0);
let json = serde_json::to_value(msg.clone()).unwrap(); let json = serde_json::to_value(msg.clone()).unwrap();
let mut native = let native =
WrappedNativeMsgUntyped::new_from("trajectory_msgs/msg/JointTrajectoryPoint").unwrap(); WrappedNativeMsgUntyped::new_from("trajectory_msgs/msg/JointTrajectoryPoint").unwrap();
native.from_json(json.clone()).unwrap(); native.from_json(json.clone()).unwrap();
let json2 = native.to_json().unwrap(); let json2 = native.to_json().unwrap();
@ -597,14 +597,13 @@ mod tests {
"float32_value": 3.14 "float32_value": 3.14
}"#; }"#;
let mut native = let native = WrappedNativeMsgUntyped::new_from("test_msgs/msg/Defaults").unwrap();
WrappedNativeMsgUntyped::new_from("test_msgs/msg/Defaults").unwrap();
let v: serde_json::Value = serde_json::from_str(json).unwrap(); let v: serde_json::Value = serde_json::from_str(json).unwrap();
native.from_json(v).expect("could make default msg"); native.from_json(v).expect("could make default msg");
let json2 = native.to_json().unwrap(); let json2 = native.to_json().unwrap();
let msg2: test_msgs::msg::Defaults = serde_json::from_value(json2).unwrap(); let msg2: test_msgs::msg::Defaults = serde_json::from_value(json2).unwrap();
assert_eq!(msg2.bool_value, true); // the default assert!(msg2.bool_value); // the default
assert_eq!(msg2.byte_value, 255); // from our json assert_eq!(msg2.byte_value, 255); // from our json
assert_eq!(msg2.char_value, 100); // the default assert_eq!(msg2.char_value, 100); // the default
assert_eq!(msg2.float32_value, 3.14); // from our json assert_eq!(msg2.float32_value, 3.14); // from our json
@ -612,7 +611,7 @@ mod tests {
#[cfg(r2r__test_msgs__msg__Arrays)] #[cfg(r2r__test_msgs__msg__Arrays)]
#[test] #[test]
fn test_test_msgs_array() -> () { fn test_test_msgs_array() {
let mut msg = test_msgs::msg::Arrays::default(); let mut msg = test_msgs::msg::Arrays::default();
println!("msg: {:?}", msg.string_values); println!("msg: {:?}", msg.string_values);
msg.string_values = vec!["hej".to_string(), "hopp".to_string(), "stropp".to_string()]; msg.string_values = vec!["hej".to_string(), "hopp".to_string(), "stropp".to_string()];
@ -626,7 +625,7 @@ mod tests {
#[cfg(r2r__test_msgs__msg__Arrays)] #[cfg(r2r__test_msgs__msg__Arrays)]
#[test] #[test]
#[should_panic] #[should_panic]
fn test_test_msgs_array_too_few_elems() -> () { fn test_test_msgs_array_too_few_elems() {
let mut msg = test_msgs::msg::Arrays::default(); let mut msg = test_msgs::msg::Arrays::default();
println!("msg: {:?}", msg.string_values); println!("msg: {:?}", msg.string_values);
msg.string_values = vec!["hej".to_string(), "hopp".to_string()]; msg.string_values = vec!["hej".to_string(), "hopp".to_string()];
@ -635,7 +634,7 @@ mod tests {
#[cfg(r2r__test_msgs__msg__WStrings)] #[cfg(r2r__test_msgs__msg__WStrings)]
#[test] #[test]
fn test_test_msgs_wstring() -> () { fn test_test_msgs_wstring() {
let mut msg = test_msgs::msg::WStrings::default(); let mut msg = test_msgs::msg::WStrings::default();
let rust_str = "ハローワールド"; let rust_str = "ハローワールド";
msg.wstring_value = rust_str.to_string(); msg.wstring_value = rust_str.to_string();
@ -649,15 +648,19 @@ mod tests {
#[test] #[test]
fn test_service_msgs() { fn test_service_msgs() {
use example_interfaces::srv::AddTwoInts; use example_interfaces::srv::AddTwoInts;
let mut req = AddTwoInts::Request::default(); let req = AddTwoInts::Request {
req.a = 5; a: 5,
..Default::default()
};
let rn = WrappedNativeMsg::<_>::from(&req); let rn = WrappedNativeMsg::<_>::from(&req);
let req2 = AddTwoInts::Request::from_native(&rn); let req2 = AddTwoInts::Request::from_native(&rn);
println!("req2 {:?}", req2); println!("req2 {:?}", req2);
assert_eq!(req, req2); assert_eq!(req, req2);
let mut resp = AddTwoInts::Response::default(); let resp = AddTwoInts::Response {
resp.sum = 5; sum: 5,
..Default::default()
};
let rn = WrappedNativeMsg::<_>::from(&resp); let rn = WrappedNativeMsg::<_>::from(&resp);
let resp2 = AddTwoInts::Response::from_native(&rn); let resp2 = AddTwoInts::Response::from_native(&rn);
println!("resp {:?}", resp2); println!("resp {:?}", resp2);
@ -678,22 +681,23 @@ mod tests {
#[test] #[test]
fn test_action_msgs() { fn test_action_msgs() {
use example_interfaces::action::Fibonacci; use example_interfaces::action::Fibonacci;
let mut goal = Fibonacci::Goal::default(); let goal = Fibonacci::Goal { order: 5 };
goal.order = 5;
let gn = WrappedNativeMsg::<_>::from(&goal); let gn = WrappedNativeMsg::<_>::from(&goal);
let goal2 = Fibonacci::Goal::from_native(&gn); let goal2 = Fibonacci::Goal::from_native(&gn);
println!("goal2 {:?}", goal2); println!("goal2 {:?}", goal2);
assert_eq!(goal, goal2); assert_eq!(goal, goal2);
let mut res = Fibonacci::Result::default(); let res = Fibonacci::Result {
res.sequence = vec![1, 2, 3]; sequence: vec![1, 2, 3],
};
let rn = WrappedNativeMsg::<_>::from(&res); let rn = WrappedNativeMsg::<_>::from(&res);
let res2 = Fibonacci::Result::from_native(&rn); let res2 = Fibonacci::Result::from_native(&rn);
println!("res2 {:?}", res2); println!("res2 {:?}", res2);
assert_eq!(res, res2); assert_eq!(res, res2);
let mut fb = Fibonacci::Feedback::default(); let fb = Fibonacci::Feedback {
fb.sequence = vec![4, 3, 6]; sequence: vec![4, 3, 6],
};
let fbn = WrappedNativeMsg::<_>::from(&fb); let fbn = WrappedNativeMsg::<_>::from(&fb);
let fb2 = Fibonacci::Feedback::from_native(&fbn); let fb2 = Fibonacci::Feedback::from_native(&fbn);
println!("feedback2 {:?}", fb2); println!("feedback2 {:?}", fb2);

View File

@ -145,7 +145,7 @@ impl Node {
for (s, v) in param_names.iter().zip(param_values) { for (s, v) in param_names.iter().zip(param_values) {
let s = unsafe { CStr::from_ptr(*s) }; let s = unsafe { CStr::from_ptr(*s) };
let key = s.to_str().unwrap_or(""); let key = s.to_str().unwrap_or("");
let val = ParameterValue::from_rcl(&*v); let val = ParameterValue::from_rcl(v);
params.insert(key.to_owned(), val); params.insert(key.to_owned(), val);
} }
} }
@ -939,7 +939,7 @@ impl Node {
let topic_types: Vec<String> = unsafe { let topic_types: Vec<String> = unsafe {
topic_types topic_types
.iter() .iter()
.map(|t| CStr::from_ptr(*((*t).data)).to_str().unwrap().to_owned()) .map(|t| CStr::from_ptr(*(t.data)).to_str().unwrap().to_owned())
.collect() .collect()
}; };
res.insert(topic_name, topic_types); res.insert(topic_name, topic_types);

View File

@ -112,7 +112,7 @@ impl PublisherUntyped {
.upgrade() .upgrade()
.ok_or(Error::RCL_RET_PUBLISHER_INVALID)?; .ok_or(Error::RCL_RET_PUBLISHER_INVALID)?;
let mut native_msg = WrappedNativeMsgUntyped::new_from(&self.type_)?; let native_msg = WrappedNativeMsgUntyped::new_from(&self.type_)?;
native_msg.from_json(msg)?; native_msg.from_json(msg)?;
let result = unsafe { let result = unsafe {

View File

@ -27,31 +27,21 @@ async fn tokio_testing() -> Result<(), Box<dyn std::error::Error>> {
}); });
task::spawn(async move { task::spawn(async move {
loop { while let Some(msg) = s_the_no.next().await {
match s_the_no.next().await { p_new_no
Some(msg) => { .publish(&r2r::std_msgs::msg::Int32 {
p_new_no data: msg.data + 10,
.publish(&r2r::std_msgs::msg::Int32 { })
data: msg.data + 10, .unwrap();
})
.unwrap();
}
None => break,
}
} }
}); });
let s = state.clone(); let s = state.clone();
task::spawn(async move { task::spawn(async move {
loop { while let Some(msg) = s_new_no.next().await {
match s_new_no.next().await { let i = msg.data;
Some(msg) => { if i == 19 {
let i = msg.data; *s.lock().unwrap() = 19;
if i == 19 {
*s.lock().unwrap() = 19;
}
}
None => break,
} }
} }
}); });

View File

@ -1,9 +1,9 @@
use itertools::Itertools;
use std::collections::HashMap; use std::collections::HashMap;
use std::env;
use std::fs::{self, File}; use std::fs::{self, File};
use std::io::Read; use std::io::Read;
use std::path::Path; use std::path::Path;
use std::env;
use itertools::Itertools;
pub fn print_cargo_watches() { pub fn print_cargo_watches() {
println!("cargo:rerun-if-env-changed=AMENT_PREFIX_PATH"); println!("cargo:rerun-if-env-changed=AMENT_PREFIX_PATH");
@ -50,14 +50,16 @@ pub fn setup_bindgen_builder() -> bindgen::Builder {
let entries = std::fs::read_dir(path.clone()); let entries = std::fs::read_dir(path.clone());
if let Ok(e) = entries { if let Ok(e) = entries {
let dirs = e.filter_map(|a| { let dirs = e
let path = a.unwrap().path(); .filter_map(|a| {
if path.is_dir() { let path = a.unwrap().path();
Some(path) if path.is_dir() {
} else { Some(path)
None } else {
} None
}).collect::<Vec<_>>(); }
})
.collect::<Vec<_>>();
builder = dirs.iter().fold(builder, |builder, d| { builder = dirs.iter().fold(builder, |builder, d| {
// Hack to build rolling after https://github.com/ros2/rcl/pull/959 was merged. // Hack to build rolling after https://github.com/ros2/rcl/pull/959 was merged.
@ -84,18 +86,20 @@ pub fn setup_bindgen_builder() -> bindgen::Builder {
let temp = d.parent().unwrap().to_str().unwrap(); let temp = d.parent().unwrap().to_str().unwrap();
builder.clang_arg(format!("-I{}", temp)) builder.clang_arg(format!("-I{}", temp))
} }
} else { builder } } else {
builder
}
}); });
} }
let lib_path = Path::new(p).join("lib"); let lib_path = Path::new(p).join("lib");
lib_path.to_str().map(|s| { if let Some(s) = lib_path.to_str() {
println!("cargo:rustc-link-search=native={}", s); println!("cargo:rustc-link-search=native={}", s)
}); }
} }
} }
return builder; builder
} }
pub fn get_wanted_messages() -> Vec<RosMsg> { pub fn get_wanted_messages() -> Vec<RosMsg> {
@ -103,7 +107,8 @@ pub fn get_wanted_messages() -> Vec<RosMsg> {
// CMAKE_PACKAGE_DIRS should be a (cmake) list of "cmake" dirs // CMAKE_PACKAGE_DIRS should be a (cmake) list of "cmake" dirs
// e.g. For each dir install/r2r_minimal_node_msgs/share/r2r_minimal_node_msgs/cmake // e.g. For each dir install/r2r_minimal_node_msgs/share/r2r_minimal_node_msgs/cmake
// we can traverse back and then look for .msg files in msg/ srv/ action/ // we can traverse back and then look for .msg files in msg/ srv/ action/
let dirs = cmake_package_dirs.split(':') let dirs = cmake_package_dirs
.split(':')
.flat_map(|i| Path::new(i).parent()) .flat_map(|i| Path::new(i).parent())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@ -132,18 +137,22 @@ pub fn get_wanted_messages() -> Vec<RosMsg> {
// //
// Suitable to customize with .cargo/config.toml [env] from consumers // Suitable to customize with .cargo/config.toml [env] from consumers
// of the r2r package. // of the r2r package.
let needed_msg_pkgs = &["rcl_interfaces", "builtin_interfaces", let needed_msg_pkgs = &[
"unique_identifier_msgs", "action_msgs"]; "rcl_interfaces",
"builtin_interfaces",
"unique_identifier_msgs",
"action_msgs",
];
if let Ok(idl_filter) = env::var("IDL_PACKAGE_FILTER") { if let Ok(idl_filter) = env::var("IDL_PACKAGE_FILTER") {
let mut idl_packages = idl_filter.split(';').collect::<Vec<&str>>(); let mut idl_packages = idl_filter.split(';').collect::<Vec<&str>>();
for needed in needed_msg_pkgs { for needed in needed_msg_pkgs {
if !idl_packages.contains(&needed) { if !idl_packages.contains(needed) {
idl_packages.push(needed); idl_packages.push(needed);
} }
} }
msgs.into_iter().filter(|msg| { msgs.into_iter()
idl_packages.contains(&msg.module.as_str()) .filter(|msg| idl_packages.contains(&msg.module.as_str()))
}).collect() .collect()
} else { } else {
msgs msgs
} }
@ -225,7 +234,6 @@ pub fn get_ros_msgs(paths: &[&Path]) -> Vec<String> {
msgs msgs
} }
fn get_msgs_in_dir(base: &Path, subdir: &str, package: &str) -> Vec<String> { fn get_msgs_in_dir(base: &Path, subdir: &str, package: &str) -> Vec<String> {
let path = base.to_owned(); let path = base.to_owned();
let path = path.join(subdir); let path = path.join(subdir);
@ -244,7 +252,7 @@ fn get_msgs_in_dir(base: &Path, subdir: &str, package: &str) -> Vec<String> {
let substr = &filename[0..filename.len() - 4]; let substr = &filename[0..filename.len() - 4];
msgs.push(format!("{}/{}/{}",package, subdir, substr)); msgs.push(format!("{}/{}/{}", package, subdir, substr));
} }
} }
msgs msgs

View File

@ -111,8 +111,10 @@ macro_rules! primitive_sequence {
pub fn to_vec(&self) -> Vec<$element_type> { pub fn to_vec(&self) -> Vec<$element_type> {
let mut target = Vec::with_capacity(self.size); let mut target = Vec::with_capacity(self.size);
unsafe { target.set_len(self.size); } unsafe {
unsafe { std::ptr::copy(self.data, target.as_mut_ptr(), self.size); } std::ptr::copy(self.data, target.as_mut_ptr(), self.size);
target.set_len(self.size);
}
target target
} }
} }