openai/openai-dotnet

Public

mirrored from https://github.com/openai/openai-dotnetAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
fe4d6cf1ccfea48fa5c2baf67103495ac9b459dd

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

OpenAI/src/Utility/DataEncodingHelpers.cs

42lines · modecode

1using System;
2using System.Text.RegularExpressions;
3
4#nullable enable
5
6namespace OpenAI;
7
8internal static partial class DataEncodingHelpers
9{
10#if NET8_0_OR_GREATER
11 [GeneratedRegex(@"^data:(?<type>.+?);base64,(?<data>.+)$")]
12 private static partial Regex ParseDataUriRegex();
13#else
14 private static Regex ParseDataUriRegex() => s_parseDataUriRegex;
15 private static readonly Regex s_parseDataUriRegex = new(@"^data:(?<type>.+?);base64,(?<data>.+)$", RegexOptions.Compiled);
16#endif
17
18 public static bool TryParseDataUri(string dataUri, out BinaryData? bytes, out string? bytesMediaType)
19 {
20 Match parsedDataUri = ParseDataUriRegex().Match(dataUri);
21
22 if (!parsedDataUri.Success)
23 {
24 bytes = null;
25 bytesMediaType = null;
26 return false;
27 }
28
29 string matchedBase64Data = parsedDataUri.Groups["data"].Value;
30 byte[] matchedBase64RawBytes = Convert.FromBase64String(matchedBase64Data);
31
32 bytes = BinaryData.FromBytes(matchedBase64RawBytes);
33 bytesMediaType = parsedDataUri.Groups["type"].Value;
34 return true;
35 }
36
37 public static string CreateDataUri(BinaryData bytes, string bytesMediaType)
38 {
39 string base64Bytes = Convert.ToBase64String(bytes.ToArray());
40 return $"data:{bytesMediaType};base64,{base64Bytes}";
41 }
42}