14
14
*/
15
15
16
16
using System ;
17
+ using System . Buffers . Binary ;
17
18
using System . Collections . Generic ;
18
19
using System . Linq ;
19
20
using System . Runtime . InteropServices ;
@@ -26,7 +27,6 @@ public static BinaryVector<TItem> ReadBinaryVector<TItem>(ReadOnlyMemory<byte> v
26
27
where TItem : struct
27
28
{
28
29
var ( items , padding , vectorDataType ) = ReadBinaryVectorAsArray < TItem > ( vectorData ) ;
29
-
30
30
return CreateBinaryVector ( items , padding , vectorDataType ) ;
31
31
}
32
32
@@ -41,29 +41,38 @@ public static (TItem[] Items, byte Padding, BinaryVectorDataType VectorDataType)
41
41
switch ( vectorDataType )
42
42
{
43
43
case BinaryVectorDataType . Float32 :
44
-
45
44
if ( ( vectorDataBytes . Span . Length & 3 ) != 0 )
46
45
{
47
46
throw new FormatException ( "Data length of binary vector of type Float32 must be a multiple of 4 bytes." ) ;
48
47
}
49
48
50
- if ( BitConverter . IsLittleEndian )
49
+ if ( typeof ( TItem ) != typeof ( float ) )
51
50
{
52
- var singles = MemoryMarshal . Cast < byte , float > ( vectorDataBytes . Span ) ;
53
- items = ( TItem [ ] ) ( object ) singles . ToArray ( ) ;
51
+ throw new NotSupportedException ( $ "Expected float for Float32 vector type, but found { typeof ( TItem ) } .") ;
54
52
}
55
- else
53
+
54
+ int count = vectorDataBytes . Length / 4 ;
55
+ float [ ] floatArray = new float [ count ] ;
56
+
57
+ for ( int i = 0 ; i < count ; i ++ )
56
58
{
57
- throw new NotSupportedException ( "Binary vector data is not supported on Big Endian architecture yet." ) ;
59
+ floatArray [ i ] = BitConverter . IsLittleEndian
60
+ ? MemoryMarshal . Read < float > ( vectorDataBytes . Span . Slice ( i * 4 , 4 ) )
61
+ : BinaryPrimitives . ReadSingleBigEndian ( vectorDataBytes . Span . Slice ( i * 4 , 4 ) ) ;
58
62
}
63
+
64
+ items = ( TItem [ ] ) ( object ) floatArray ;
59
65
break ;
66
+
60
67
case BinaryVectorDataType . Int8 :
61
68
var itemsSpan = MemoryMarshal . Cast < byte , TItem > ( vectorDataBytes . Span ) ;
62
- items = ( TItem [ ] ) ( object ) itemsSpan . ToArray ( ) ;
69
+ items = itemsSpan . ToArray ( ) ;
63
70
break ;
71
+
64
72
case BinaryVectorDataType . PackedBit :
65
73
items = ( TItem [ ] ) ( object ) vectorDataBytes . ToArray ( ) ;
66
74
break ;
75
+
67
76
default :
68
77
throw new NotSupportedException ( $ "Binary vector data type { vectorDataType } is not supported.") ;
69
78
}
0 commit comments