Skip to content

Commit

Permalink
Handle overflow in Deadline calculation to ensure correct behavior fo…
Browse files Browse the repository at this point in the history
…r large time values. (#512)
  • Loading branch information
arturobernalg authored Jan 10, 2025
1 parent 68865fd commit fd5c617
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,8 @@ public class Deadline {
*/
public static Deadline calculate(final long timeMillis, final TimeValue timeValue) {
if (TimeValue.isPositive(timeValue)) {
// TODO handle unlikely overflow
final long deadline = timeMillis + timeValue.toMilliseconds();
return deadline < 0 ? Deadline.MAX_VALUE : Deadline.fromUnixMilliseconds(deadline);
return Deadline.fromUnixMilliseconds(timeMillis +
Math.min(timeValue.toMilliseconds(), Long.MAX_VALUE - timeMillis));
}
return Deadline.MAX_VALUE;
}
Expand Down
10 changes: 10 additions & 0 deletions httpcore5/src/test/java/org/apache/hc/core5/util/TestDeadline.java
Original file line number Diff line number Diff line change
Expand Up @@ -130,4 +130,14 @@ void testValue() {
final Deadline deadline = Deadline.fromUnixMilliseconds(nowPlusOneMin);
Assertions.assertEquals(nowPlusOneMin, deadline.getValue());
}

@Test
void testOverflowHandling() {
final long currentTime = Long.MAX_VALUE - 5000; // Simulate close to overflow
final TimeValue tenSeconds = TimeValue.ofMilliseconds(10000); // 10 seconds
final Deadline deadline = Deadline.calculate(currentTime, tenSeconds);

Assertions.assertEquals(Deadline.MAX_VALUE, deadline,
"Overflow should result in the maximum deadline value.");
}
}

0 comments on commit fd5c617

Please sign in to comment.