@@ -84,7 +84,7 @@ class Time
8484 Time (int32_t seconds, uint32_t nanoseconds)
8585 : rcl_time_(get_empty_time_point())
8686 {
87- uint64_t ns = RCL_S_TO_NS (seconds);
87+ uint64_t ns = RCL_S_TO_NS (static_cast < uint64_t >( seconds) );
8888 ns += nanoseconds;
8989 rcl_time_.nanoseconds = ns;
9090 }
@@ -99,7 +99,11 @@ class Time
9999 Time (const builtin_interfaces::msg::Time & time_msg) // NOLINT
100100 : rcl_time_(get_empty_time_point())
101101 {
102- rcl_time_.nanoseconds = RCL_S_TO_NS (time_msg.sec );
102+ if (time_msg.sec < 0 ) {
103+ throw std::runtime_error (" can't convert a negative time msg to rclcpp::Time" );
104+ }
105+
106+ rcl_time_.nanoseconds = RCL_S_TO_NS (static_cast <uint64_t >(time_msg.sec ));
103107 rcl_time_.nanoseconds += time_msg.nanosec ;
104108 }
105109
@@ -114,8 +118,12 @@ class Time
114118 void
115119 operator =(const builtin_interfaces::msg::Time & time_msg)
116120 {
121+ if (time_msg.sec < 0 ) {
122+ throw std::runtime_error (" can't convert a negative time msg to rclcpp::Time" );
123+ }
124+
117125 auto time_point = get_empty_time_point ();
118- time_point.nanoseconds = RCL_S_TO_NS (time_msg.sec );
126+ time_point.nanoseconds = RCL_S_TO_NS (static_cast < uint64_t >( time_msg.sec ) );
119127 time_point.nanoseconds += time_msg.nanosec ;
120128
121129 this ->rcl_time_ = time_point;
@@ -164,6 +172,11 @@ class Time
164172 throw std::runtime_error (" can't add times with different time sources" );
165173 }
166174
175+ auto ns = rcl_time_.nanoseconds + rhs.rcl_time_ .nanoseconds ;
176+ if (ns < rcl_time_.nanoseconds ) {
177+ throw std::runtime_error (" addition leads to uint64_t overflow" );
178+ }
179+
167180 return Time (rcl_time_.nanoseconds + rhs.rcl_time_ .nanoseconds );
168181 }
169182
@@ -174,6 +187,11 @@ class Time
174187 throw std::runtime_error (" can't add times with different time sources" );
175188 }
176189
190+ auto ns = rcl_time_.nanoseconds - rhs.rcl_time_ .nanoseconds ;
191+ if (ns > rcl_time_.nanoseconds ) {
192+ throw std::runtime_error (" subtraction leads to uint64_t underflow" );
193+ }
194+
177195 return Time (rcl_time_.nanoseconds - rhs.rcl_time_ .nanoseconds );
178196 }
179197
0 commit comments