Skip to content

Commit 7c223db

Browse files
committed
cras_py_common: string_utils: Fixed bug stringifying negative durations.
1 parent beb1059 commit 7c223db

File tree

2 files changed

+7
-3
lines changed

2 files changed

+7
-3
lines changed

cras_py_common/src/cras/string_utils.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,9 @@ def __time_val_to_str(time):
4141
:return: The string representation.
4242
:rtype: str
4343
"""
44-
return "%i.%09i" % (time.secs, time.nsecs)
44+
# We can't directly print .secs, .nsecs, as that would fail for negative durations
45+
nsecs = time.to_nsec()
46+
return "%i.%09i" % (nsecs // 1000000000, nsecs % 1000000000)
4547

4648

4749
__to_str_functions = {

cras_py_common/test/test_string_utils.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,10 @@ def test_to_str(self):
5151
self.assertEqual("1.000000001", to_str(Duration(1, 1)))
5252
self.assertEqual("1.100000000", to_str(Duration(1, 100000000)))
5353
self.assertEqual("-1.000000000", to_str(-Duration(1)))
54-
self.assertEqual("-1.000000001", to_str(Duration(-1, 1)))
55-
self.assertEqual("-1.100000000", to_str(Duration(-1, 100000000)))
54+
# negative durations mean "10e9 * secs + nsecs", so (-1, 1) is actually
55+
# (-1 * 10e9 + 1) = -999999999
56+
self.assertEqual("-0.999999999", to_str(Duration(-1, 1)))
57+
self.assertEqual("-0.9", to_str(Duration(-1, 100000000)))
5658
self.assertEqual("1.000000000", to_str(Time(1)))
5759
self.assertEqual("1.000000001", to_str(Time(1, 1)))
5860
self.assertEqual("1.100000000", to_str(Time(1, 100000000)))

0 commit comments

Comments
 (0)