Skip to content

Commit 2c4a16a

Browse files
committed
Fix BinaryVectorSerializerTests to generate little-endian test data for float32 on all platforms
Signed-off-by: Medha Tiwari <[email protected]>
1 parent 2c2cae1 commit 2c4a16a

File tree

1 file changed

+29
-4
lines changed

1 file changed

+29
-4
lines changed

tests/MongoDB.Bson.Tests/Serialization/Serializers/BinaryVectorSerializerTests.cs

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -365,10 +365,35 @@ private BsonBinaryData SerializeToBinaryData<TCollection>(TCollection collection
365365
private static (T[], byte[] VectorBson) GetTestData<T>(BinaryVectorDataType dataType, int elementsCount, byte bitsPadding)
366366
where T : struct
367367
{
368-
var elementsSpan = new ReadOnlySpan<T>(Enumerable.Range(0, elementsCount).Select(i => Convert.ChangeType(i, typeof(T)).As<T>()).ToArray());
369-
byte[] vectorBsonData = [(byte)dataType, bitsPadding, .. MemoryMarshal.Cast<T, byte>(elementsSpan)];
370-
371-
return (elementsSpan.ToArray(), vectorBsonData);
368+
var elementsSpan = new ReadOnlySpan<T>(
369+
Enumerable.Range(0, elementsCount)
370+
.Select(i => Convert.ChangeType(i, typeof(T)).As<T>())
371+
.ToArray());
372+
if (typeof(T) == typeof(float) && dataType == BinaryVectorDataType.Float32)
373+
{
374+
var buffer = new byte[2 + elementsCount * 4]; // 4 bytes per float
375+
buffer[0] = (byte)dataType;
376+
buffer[1] = bitsPadding;
377+
for (int i = 0; i < elementsCount; i++)
378+
{
379+
var floatBytes = BitConverter.GetBytes((float)(object)elementsSpan[i]);
380+
if (!BitConverter.IsLittleEndian)
381+
{
382+
Array.Reverse(floatBytes);
383+
}
384+
Buffer.BlockCopy(floatBytes, 0, buffer, 2 + i * 4, 4);
385+
}
386+
return (elementsSpan.ToArray(), buffer);
387+
}
388+
else if ((typeof(T) == typeof(byte) || typeof(T) == typeof(sbyte)) && (dataType == BinaryVectorDataType.Int8 || dataType == BinaryVectorDataType.PackedBit))
389+
{
390+
byte[] vectorBsonData = [(byte)dataType, bitsPadding, .. MemoryMarshal.Cast<T, byte>(elementsSpan)];
391+
return (elementsSpan.ToArray(), vectorBsonData);
392+
}
393+
else
394+
{
395+
throw new NotSupportedException($"Type {typeof(T)} is not supported for data type {dataType}.");
396+
}
372397
}
373398

374399
private static (BinaryVector<T>, byte[] VectorBson) GetTestDataBinaryVector<T>(BinaryVectorDataType dataType, int elementsCount, byte bitsPadding)

0 commit comments

Comments
 (0)