Skip to content

Commit b4ac89b

Browse files
author
rstam
committed
CSHARP-945: Throw ArgumentOutOfRangeException when ObjectId constructor is passed a DateTime that is out of range.
1 parent 61f0fbf commit b4ac89b

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/MongoDB.Bson.Tests/ObjectModel/ObjectIdTests.cs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,23 @@ public void TestDateTimeConstructor()
107107
Assert.IsTrue(bytes.SequenceEqual(objectId.ToByteArray()));
108108
}
109109

110+
[TestCase(int.MinValue)]
111+
[TestCase(int.MaxValue)]
112+
public void TestDateTimeConstructorAtEdgeOfRange(int secondsSinceEpoch)
113+
{
114+
var timestamp = BsonConstants.UnixEpoch.AddSeconds(secondsSinceEpoch);
115+
var objectId = new ObjectId(timestamp, 0, 0, 0);
116+
Assert.AreEqual(timestamp, objectId.CreationTime);
117+
}
118+
119+
[TestCase((long)int.MinValue - 1)]
120+
[TestCase((long)int.MaxValue + 1)]
121+
public void TestDateTimeConstructorArgumentOutOfRangeException(long secondsSinceEpoch)
122+
{
123+
var timestamp = BsonConstants.UnixEpoch.AddSeconds(secondsSinceEpoch);
124+
Assert.Throws<ArgumentOutOfRangeException>(() => new ObjectId(timestamp, 0, 0, 0));
125+
}
126+
110127
[Test]
111128
public void TestStringConstructor()
112129
{

src/MongoDB.Bson/ObjectModel/ObjectId.cs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -409,7 +409,12 @@ private static int GetMachineHash()
409409

410410
private static int GetTimestampFromDateTime(DateTime timestamp)
411411
{
412-
return (int)Math.Floor((BsonUtils.ToUniversalTime(timestamp) - BsonConstants.UnixEpoch).TotalSeconds);
412+
var secondsSinceEpoch = (long)Math.Floor((BsonUtils.ToUniversalTime(timestamp) - BsonConstants.UnixEpoch).TotalSeconds);
413+
if (secondsSinceEpoch < int.MinValue || secondsSinceEpoch > int.MaxValue)
414+
{
415+
throw new ArgumentOutOfRangeException("timestamp");
416+
}
417+
return (int)secondsSinceEpoch;
413418
}
414419

415420
// public methods

0 commit comments

Comments
 (0)