Skip to content

Commit 88504ef

Browse files
committed
fourth bug fix: don't cast bytes to DateTimes
1 parent fcb3c8a commit 88504ef

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/libraries/System.Formats.Nrbf/src/System/Formats/Nrbf/ArraySinglePrimitiveRecord.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,17 @@ internal static IReadOnlyList<T> DecodePrimitiveTypes(BinaryReader reader, int c
175175
}
176176
}
177177
}
178+
else if (typeof(T) == typeof(DateTime))
179+
{
180+
DateTime[] dateTimes = (DateTime[])(object)result;
181+
Span<ulong> span = MemoryMarshal.Cast<T, ulong>(result);
182+
for (int i = 0; i < dateTimes.Length; i++)
183+
{
184+
// The value needs to get validated.
185+
dateTimes[i] = BinaryReaderExtensions.CreateDateTimeFromData(span[i]);
186+
}
187+
}
188+
178189
return result;
179190
}
180191

src/libraries/System.Formats.Nrbf/tests/ArraySinglePrimitiveRecordTests.cs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
using System.Collections.Generic;
55
using System.IO;
6+
using System.Runtime.Serialization;
67
using System.Text;
78
using Xunit;
89

@@ -52,6 +53,24 @@ public void DontCastBytesToBooleans()
5253
Assert.True(c);
5354
}
5455

56+
[Fact]
57+
public void DontCastBytesToDateTimes()
58+
{
59+
using MemoryStream stream = new();
60+
BinaryWriter writer = new(stream, Encoding.UTF8);
61+
62+
WriteSerializedStreamHeader(writer);
63+
writer.Write((byte)SerializationRecordType.ArraySinglePrimitive);
64+
writer.Write(1); // object ID
65+
writer.Write(1); // length
66+
writer.Write((byte)PrimitiveType.DateTime); // element type
67+
writer.Write(ulong.MaxValue); // un-representable DateTime
68+
writer.Write((byte)SerializationRecordType.MessageEnd);
69+
stream.Position = 0;
70+
71+
Assert.Throws<SerializationException>(() => NrbfDecoder.Decode(stream));
72+
}
73+
5574
[Theory]
5675
[MemberData(nameof(GetCanReadArrayOfAnySizeArgs))]
5776
public void CanReadArrayOfAnySize_Bool(int size, bool canSeek) => Test<bool>(size, canSeek);

0 commit comments

Comments
 (0)