openai/openai-dotnet

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
OpenAI_2.0.0-beta.1

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/Utility/ServerSentEventField.cs

55lines · modecode

1using System;
2
3#nullable enable
4
5namespace OpenAI;
6
7/// <summary>
8/// Represents a field that can be composed into an SSE event.
9/// See SSE specification: https://html.spec.whatwg.org/multipage/server-sent-events.html
10/// </summary>
11internal readonly struct ServerSentEventField
12{
13 private static readonly ReadOnlyMemory<char> s_eventFieldName = "event".AsMemory();
14 private static readonly ReadOnlyMemory<char> s_dataFieldName = "data".AsMemory();
15 private static readonly ReadOnlyMemory<char> s_lastEventIdFieldName = "id".AsMemory();
16 private static readonly ReadOnlyMemory<char> s_retryFieldName = "retry".AsMemory();
17
18 public ServerSentEventFieldKind FieldType { get; }
19
20 // Note: we don't plan to expose UTF16 publicly
21 public ReadOnlyMemory<char> Value { get; }
22
23 internal ServerSentEventField(string line)
24 {
25 int colonIndex = line.AsSpan().IndexOf(':');
26
27 ReadOnlyMemory<char> fieldName = colonIndex < 0 ?
28 line.AsMemory() :
29 line.AsMemory(0, colonIndex);
30
31 FieldType = fieldName.Span switch
32 {
33 var x when x.SequenceEqual(s_eventFieldName.Span) => ServerSentEventFieldKind.Event,
34 var x when x.SequenceEqual(s_dataFieldName.Span) => ServerSentEventFieldKind.Data,
35 var x when x.SequenceEqual(s_lastEventIdFieldName.Span) => ServerSentEventFieldKind.Id,
36 var x when x.SequenceEqual(s_retryFieldName.Span) => ServerSentEventFieldKind.Retry,
37 _ => ServerSentEventFieldKind.Ignore,
38 };
39
40 if (colonIndex < 0)
41 {
42 Value = ReadOnlyMemory<char>.Empty;
43 }
44 else
45 {
46 Value = line.AsMemory(colonIndex + 1);
47
48 // Per spec, remove a leading space if present.
49 if (Value.Length > 0 && Value.Span[0] == ' ')
50 {
51 Value = Value.Slice(1);
52 }
53 }
54 }
55}
56