Skip to content

Commit a4384e3

Browse files
committed
-s
Added comments for clarity
1 parent ff89368 commit a4384e3

File tree

2 files changed

+13
-9
lines changed

2 files changed

+13
-9
lines changed

src/MongoDB.Bson/Serialization/BinaryVectorReader.cs

+5-3
Original file line numberDiff line numberDiff line change
@@ -51,14 +51,15 @@ public static (TItem[] Items, byte Padding, BinaryVectorDataType VectorDataType)
5151
throw new NotSupportedException($"Expected float for Float32 vector type, but found {typeof(TItem)}.");
5252
}
5353

54-
int count = vectorDataBytes.Length / 4;
54+
int count = vectorDataBytes.Length / 4; // 4 bytes per float
5555
float[] floatArray = new float[count];
5656

5757
for (int i = 0; i < count; i++)
5858
{
59+
// Each float32 is 4 bytes. So to extract the i-th float, we slice 4 bytes from offset i * 4. Use little-endian or big-endian decoding based on platform.
5960
floatArray[i] = BitConverter.IsLittleEndian
60-
? MemoryMarshal.Read<float>(vectorDataBytes.Span.Slice(i * 4, 4))
61-
: BinaryPrimitives.ReadSingleBigEndian(vectorDataBytes.Span.Slice(i * 4, 4));
61+
? MemoryMarshal.Read<float>(vectorDataBytes.Span.Slice(i * 4, 4)) // fast, unaligned read on little endian
62+
: BinaryPrimitives.ReadSingleBigEndian(vectorDataBytes.Span.Slice(i * 4, 4)); // correctly reassemble 4 bytes as big-endian float
6263
}
6364

6465
items = (TItem[])(object)floatArray;
@@ -158,3 +159,4 @@ private static void ValidateItemTypeForBinaryVector<TItem, TItemExpectedType, TB
158159
}
159160
}
160161
}
162+

src/MongoDB.Bson/Serialization/BinaryVectorWriter.cs

+8-6
Original file line numberDiff line numberDiff line change
@@ -48,15 +48,16 @@ public static byte[] WriteToBytes<TItem>(ReadOnlySpan<TItem> vectorData, BinaryV
4848
{
4949
case BinaryVectorDataType.Float32:
5050
int length = vectorData.Length * sizeof(float);
51-
resultBytes = new byte[2 + length];
52-
resultBytes[0] = (byte)binaryVectorDataType;
53-
resultBytes[1] = padding;
54-
var floatSpan = MemoryMarshal.Cast<TItem, float>(vectorData);
55-
Span<byte> floatOutput = resultBytes.AsSpan(2);
51+
resultBytes = new byte[2 + length]; // Allocate output buffer:
52+
resultBytes[0] = (byte)binaryVectorDataType; // - [0]: vector type
53+
resultBytes[1] = padding; // - [1]: padding
54+
var floatSpan = MemoryMarshal.Cast<TItem, float>(vectorData);
55+
Span<byte> floatOutput = resultBytes.AsSpan(2); // - [2...]: actual float data , skipping header
5656
foreach (var value in floatSpan)
5757
{
58+
// Each float is 4 bytes - write in Big Endian format
5859
BinaryPrimitives.WriteSingleBigEndian(floatOutput, value);
59-
floatOutput = floatOutput.Slice(4);
60+
floatOutput = floatOutput.Slice(4); // advance to next 4-byte block
6061
}
6162
return resultBytes;
6263

@@ -75,3 +76,4 @@ public static byte[] WriteToBytes<TItem>(ReadOnlySpan<TItem> vectorData, BinaryV
7576
}
7677
}
7778
}
79+

0 commit comments

Comments
 (0)