Commit 43f89c23 authored by James Lemieux's avatar James Lemieux Committed by android-build-merger
Browse files

Do not assume current stopwatch lap has positive duration

am: f8e562f6

* commit 'f8e562f6':
  Do not assume current stopwatch lap has positive duration
parents 079dc3af f8e562f6
......@@ -61,7 +61,11 @@ public final class Stopwatch {
return mAccumulatedTime;
}
return mAccumulatedTime + (now() - mLastStartTime);
// In practice, "now" can be any value due to device reboots. When the real-time clock
// is reset, there is no more guarantee that "now" falls after the last start time. To
// ensure the stopwatch is monotonically increasing, normalize negative time segments to 0,
final long timeSinceStart = now() - mLastStartTime;
return mAccumulatedTime + Math.max(0, timeSinceStart);
}
/**
......@@ -79,7 +83,7 @@ public final class Stopwatch {
return this;
}
return new Stopwatch(RUNNING, now(), mAccumulatedTime);
return new Stopwatch(RUNNING, now(), getTotalTime());
}
/**
......@@ -90,8 +94,7 @@ public final class Stopwatch {
return this;
}
final long accumulatedTime = mAccumulatedTime + (now() - mLastStartTime);
return new Stopwatch(PAUSED, Long.MIN_VALUE, accumulatedTime);
return new Stopwatch(PAUSED, Long.MIN_VALUE, getTotalTime());
}
/**
......
......@@ -175,21 +175,17 @@ final class StopwatchModel {
}
/**
* @param time a point in time after the end of the last lap
* @return the elapsed time between the given {@code time} and the end of the previous lap
* In practice, {@code time} can be any value due to device reboots. When the real-time clock is
* reset, there is no more guarantee that this time falls after the last recorded lap.
*
* @param time a point in time expected, but not required, to be after the end of the prior lap
* @return the elapsed time between the given {@code time} and the end of the prior lap;
* negative elapsed times are normalized to {@code 0}
*/
long getCurrentLapTime(long time) {
final Lap previousLap = getLaps().get(0);
final long last = previousLap.getAccumulatedTime();
final long lapTime = time - last;
if (lapTime < 0) {
final String message = String.format("time (%d) must exceed last lap (%d)", time, last);
throw new IllegalArgumentException(message);
}
return lapTime;
final long currentLapTime = time - previousLap.getAccumulatedTime();
return Math.max(0, currentLapTime);
}
/**
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment