Skip to content

Commit 16281ae

Browse files
committed
Move to finally
1 parent 22c0999 commit 16281ae

File tree

1 file changed

+23
-20
lines changed

1 file changed

+23
-20
lines changed

src/Custom/Embeddings/OpenAIEmbedding.cs

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -118,33 +118,36 @@ private static ReadOnlyMemory<float> ConvertToVectorOfFloats(BinaryData binaryDa
118118

119119
// Decode base64 string to bytes.
120120
byte[] bytes = ArrayPool<byte>.Shared.Rent(Base64.GetMaxDecodedFromUtf8Length(base64.Length));
121-
OperationStatus status = Base64.DecodeFromUtf8(base64, bytes.AsSpan(), out int bytesConsumed, out int bytesWritten);
122-
if (status != OperationStatus.Done || bytesWritten % sizeof(float) != 0)
123-
{
124-
ArrayPool<byte>.Shared.Return(bytes);
125-
ThrowInvalidData();
126-
}
127-
128-
// Interpret bytes as floats
129-
float[] vector = new float[bytesWritten / sizeof(float)];
130-
bytes.AsSpan(0, bytesWritten).CopyTo(MemoryMarshal.AsBytes(vector.AsSpan()));
131-
if (!BitConverter.IsLittleEndian)
132-
{
133-
Span<int> ints = MemoryMarshal.Cast<float, int>(vector.AsSpan());
121+
try
122+
{
123+
OperationStatus status = Base64.DecodeFromUtf8(base64, bytes.AsSpan(), out int bytesConsumed, out int bytesWritten);
124+
if (status != OperationStatus.Done || bytesWritten % sizeof(float) != 0)
125+
{
126+
ThrowInvalidData();
127+
}
128+
129+
// Interpret bytes as floats
130+
float[] vector = new float[bytesWritten / sizeof(float)];
131+
bytes.AsSpan(0, bytesWritten).CopyTo(MemoryMarshal.AsBytes(vector.AsSpan()));
132+
if (!BitConverter.IsLittleEndian)
133+
{
134+
Span<int> ints = MemoryMarshal.Cast<float, int>(vector.AsSpan());
134135
#if NET8_0_OR_GREATER
135-
BinaryPrimitives.ReverseEndianness(ints, ints);
136+
BinaryPrimitives.ReverseEndianness(ints, ints);
136137
#else
137138
for (int i = 0; i < ints.Length; i++)
138139
{
139140
ints[i] = BinaryPrimitives.ReverseEndianness(ints[i]);
140141
}
141142
#endif
143+
}
144+
return new ReadOnlyMemory<float>(vector);
145+
}
146+
finally
147+
{
148+
ArrayPool<byte>.Shared.Return(bytes);
142149
}
143-
144-
ArrayPool<byte>.Shared.Return(bytes);
145-
return new ReadOnlyMemory<float>(vector);
146-
147-
static void ThrowInvalidData() =>
150+
}
151+
static void ThrowInvalidData() =>
148152
throw new FormatException("The input is not a valid Base64 string of encoded floats.");
149-
}
150153
}

0 commit comments

Comments
 (0)