Skip to content

Commit

Permalink
Modifies the add() function to support signed additions (eg. subtract…
Browse files Browse the repository at this point in the history
…ions) and fixes the chrono_t long _offset problem (closes #20).
  • Loading branch information
sofian committed Jan 4, 2025
1 parent cd79fab commit 6438bfc
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 7 deletions.
30 changes: 27 additions & 3 deletions Chrono.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,29 @@
#endif
#include "Chrono.h"

#if defined(ARDUINO_ARC32_TOOLS)
#define CHRONO_T_MAX UINT64_MAX
#else
#define CHRONO_T_MAX UINT32_MAX
#endif

// Safe addition (prevents overflows and underflows).
Chrono::chrono_t safeAdd(Chrono::chrono_t a, Chrono::signed_chrono_t b) {
if (b > 0) {
// Overflow.
if ((Chrono::chrono_t)b > CHRONO_T_MAX - a)
return CHRONO_T_MAX;
}

else {
// Underflow.
if ((Chrono::chrono_t)(-b) > a)
return 0;
}
// Default.
return a + b;
}

Chrono::Chrono(Resolution resolution, bool startNow) {
// Assign appropriate time function.
switch(resolution) {
Expand Down Expand Up @@ -82,8 +105,8 @@ void Chrono::resume() {
}
}

void Chrono::add(Chrono::chrono_t t) {
_offset += t;
void Chrono::add(Chrono::signed_chrono_t t) {
_offset = safeAdd(_offset, t);
}

bool Chrono::isRunning() const {
Expand Down Expand Up @@ -125,7 +148,8 @@ void Chrono::_init(chrono_t (*getTime_)(void), bool startNow) {
if (startNow)
restart();
else {
_startTime = _offset = 0;
_startTime = 0;
_offset = 0;
_isRunning = false;
}
}
Expand Down
10 changes: 6 additions & 4 deletions Chrono.h
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,10 @@ class Chrono

#if defined(ARDUINO_ARC32_TOOLS)
typedef uint64_t chrono_t;
typedef int64_t signed_chrono_t;
#else
typedef unsigned long chrono_t;
typedef uint32_t chrono_t;
typedef int32_t signed_chrono_t;
#endif

// Different sorts of ways to get time.
Expand All @@ -61,7 +63,7 @@ class Chrono
chrono_t _startTime;

// Time offset.
chrono_t long _offset;
chrono_t _offset;

// Time function.
chrono_t (*_getTime)(void);
Expand Down Expand Up @@ -96,8 +98,8 @@ class Chrono
// Resumes the chronometer.
void resume();

/// Adds some time to the chronometer.
void add(chrono_t t);
/// Adds/subtracts some time to the chronometer.
void add(signed_chrono_t t);

/// Returns the elapsed time since start (in milliseconds).
chrono_t elapsed() const;
Expand Down

0 comments on commit 6438bfc

Please sign in to comment.