diff base/RealTimeSV.cpp @ 1427:622d193a00dc

Rework canonicalisation so as to avoid theoretical possibility of integer overflow
author Chris Cannam
date Mon, 11 Dec 2017 09:28:40 +0000
parents a1af054d8f75
children 48e9f538e6e9
line wrap: on
line diff
--- a/base/RealTimeSV.cpp	Thu Dec 07 13:33:30 2017 +0000
+++ b/base/RealTimeSV.cpp	Mon Dec 11 09:28:40 2017 +0000
@@ -19,6 +19,7 @@
 */
 
 #include <iostream>
+#include <limits.h>
 
 #include <cstdlib>
 #include <sstream>
@@ -43,16 +44,10 @@
 RealTime::RealTime(int s, int n) :
     sec(s), nsec(n)
 {
-    if (sec == 0) {
-	while (nsec <= -ONE_BILLION) { nsec += ONE_BILLION; --sec; }
-	while (nsec >=  ONE_BILLION) { nsec -= ONE_BILLION; ++sec; }
-    } else if (sec < 0) {
-	while (nsec <= -ONE_BILLION) { nsec += ONE_BILLION; --sec; }
-	while (nsec > 0 && sec < 0)  { nsec -= ONE_BILLION; ++sec; }
-    } else { 
-	while (nsec >=  ONE_BILLION) { nsec -= ONE_BILLION; ++sec; }
-	while (nsec < 0 && sec > 0)  { nsec += ONE_BILLION; --sec; }
-    }
+    while (nsec <= -ONE_BILLION && sec > INT_MIN) { nsec += ONE_BILLION; --sec; }
+    while (nsec >=  ONE_BILLION && sec < INT_MAX) { nsec -= ONE_BILLION; ++sec; }
+    while (nsec > 0 && sec < 0) { nsec -= ONE_BILLION; ++sec; }
+    while (nsec < 0 && sec > 0) { nsec += ONE_BILLION; --sec; }
 }
 
 RealTime