1414*/
1515
1616using System ;
17+ using System . Buffers . Binary ;
1718using System . Collections . Generic ;
1819using System . Linq ;
1920using System . Runtime . InteropServices ;
@@ -26,7 +27,6 @@ public static BinaryVector<TItem> ReadBinaryVector<TItem>(ReadOnlyMemory<byte> v
2627 where TItem : struct
2728 {
2829 var ( items , padding , vectorDataType ) = ReadBinaryVectorAsArray < TItem > ( vectorData ) ;
29-
3030 return CreateBinaryVector ( items , padding , vectorDataType ) ;
3131 }
3232
@@ -41,29 +41,38 @@ public static (TItem[] Items, byte Padding, BinaryVectorDataType VectorDataType)
4141 switch ( vectorDataType )
4242 {
4343 case BinaryVectorDataType . Float32 :
44-
4544 if ( ( vectorDataBytes . Span . Length & 3 ) != 0 )
4645 {
4746 throw new FormatException ( "Data length of binary vector of type Float32 must be a multiple of 4 bytes." ) ;
4847 }
4948
50- if ( BitConverter . IsLittleEndian )
49+ if ( typeof ( TItem ) != typeof ( float ) )
5150 {
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 ) } .") ;
5452 }
55- else
53+
54+ int count = vectorDataBytes . Length / 4 ;
55+ float [ ] floatArray = new float [ count ] ;
56+
57+ for ( int i = 0 ; i < count ; i ++ )
5658 {
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 ) ) ;
5862 }
63+
64+ items = ( TItem [ ] ) ( object ) floatArray ;
5965 break ;
66+
6067 case BinaryVectorDataType . Int8 :
6168 var itemsSpan = MemoryMarshal . Cast < byte , TItem > ( vectorDataBytes . Span ) ;
62- items = ( TItem [ ] ) ( object ) itemsSpan . ToArray ( ) ;
69+ items = itemsSpan . ToArray ( ) ;
6370 break ;
71+
6472 case BinaryVectorDataType . PackedBit :
6573 items = ( TItem [ ] ) ( object ) vectorDataBytes . ToArray ( ) ;
6674 break ;
75+
6776 default :
6877 throw new NotSupportedException ( $ "Binary vector data type { vectorDataType } is not supported.") ;
6978 }
0 commit comments