Adding a factory method to create a Duration from seconds (#567)

* Adding a factory method to create a Duration from seconds

There are many places in the ROS codebase where a time duration is
specified as a floating point number of seconds. A factory function
to create a Duration object from these values makes the code a
bit simpler in many cases.

Signed-off-by: Carl Delsey <carl.r.delsey@intel.com>

* Adding some comments to clarify which constructors get matched.

Signed-off-by: Carl Delsey <carl.r.delsey@intel.com>
This commit is contained in:
Carl Delsey 2019-06-28 09:43:09 -07:00 committed by Chris Lalancette
parent 5a5a1fe530
commit 0ccac1e3bd
3 changed files with 29 additions and 0 deletions

View file

@ -28,10 +28,12 @@ class RCLCPP_PUBLIC Duration
public:
Duration(int32_t seconds, uint32_t nanoseconds);
// This constructor matches any numeric value - ints or floats
explicit Duration(rcl_duration_value_t nanoseconds);
explicit Duration(std::chrono::nanoseconds nanoseconds);
// This constructor matches any std::chrono value other than nanoseconds
// intentionally not using explicit to create a conversion constructor
template<class Rep, class Period>
// cppcheck-suppress noExplicitConstructor
@ -94,6 +96,10 @@ public:
double
seconds() const;
// Create a duration object from a floating point number representing seconds
static Duration
from_seconds(double seconds);
template<class DurationT>
DurationT
to_chrono() const

View file

@ -233,4 +233,10 @@ Duration::to_rmw_time() const
return result;
}
Duration
Duration::from_seconds(double seconds)
{
return Duration(static_cast<int64_t>(RCL_S_TO_NS(seconds)));
}
} // namespace rclcpp

View file

@ -136,3 +136,20 @@ TEST(TestDuration, maximum_duration) {
EXPECT_EQ(max_duration, max);
}
static const int64_t HALF_SEC_IN_NS = 500 * 1000 * 1000;
static const int64_t ONE_AND_HALF_SEC_IN_NS = 3 * HALF_SEC_IN_NS;
TEST(TestDuration, from_seconds) {
EXPECT_EQ(rclcpp::Duration(0), rclcpp::Duration::from_seconds(0.0));
EXPECT_EQ(rclcpp::Duration(0), rclcpp::Duration::from_seconds(0));
EXPECT_EQ(rclcpp::Duration(1, HALF_SEC_IN_NS), rclcpp::Duration::from_seconds(1.5));
EXPECT_EQ(rclcpp::Duration(-ONE_AND_HALF_SEC_IN_NS), rclcpp::Duration::from_seconds(-1.5));
}
TEST(TestDuration, std_chrono_constructors) {
EXPECT_EQ(rclcpp::Duration(0), rclcpp::Duration(0.0s));
EXPECT_EQ(rclcpp::Duration(0), rclcpp::Duration(0s));
EXPECT_EQ(rclcpp::Duration(1, HALF_SEC_IN_NS), rclcpp::Duration(1.5s));
EXPECT_EQ(rclcpp::Duration(-1, 0), rclcpp::Duration(-1s));
}