microsoft/teams.net

Public

mirrored from https://github.com/microsoft/teams.netAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v2.0.0-preview.6

Branches

Tags

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

Clone

HTTPS

Download ZIP

Libraries/Microsoft.Teams.AI.Models.OpenAI/Builders/SequenceBuilder.cs

67lines · modecode

1using System.Buffers;
2using System.Diagnostics;
3
4namespace Microsoft.Teams.AI.Models.OpenAI.Builders;
5
6/// <summary>
7/// https://github.com/openai/openai-dotnet/blob/main/examples/Chat/Example04_FunctionCallingStreaming.cs#L74
8/// </summary>
9public class SequenceBuilder<T>
10{
11 Segment? _first;
12 Segment? _last;
13
14 public void Append(ReadOnlyMemory<T> data)
15 {
16 if (_first is null)
17 {
18 Debug.Assert(_last is null);
19 _first = new Segment(data);
20 _last = _first;
21 }
22 else
23 {
24 _last = _last!.Append(data);
25 }
26 }
27
28 public ReadOnlySequence<T> Build()
29 {
30 if (_first is null)
31 {
32 Debug.Assert(_last is null);
33 return ReadOnlySequence<T>.Empty;
34 }
35
36 if (_first == _last)
37 {
38 Debug.Assert(_first.Next is null);
39 return new ReadOnlySequence<T>(_first.Memory);
40 }
41
42 return new ReadOnlySequence<T>(_first, 0, _last!, _last!.Memory.Length);
43 }
44
45 private sealed class Segment : ReadOnlySequenceSegment<T>
46 {
47 public Segment(ReadOnlyMemory<T> items) : this(items, 0)
48 {
49 }
50
51 private Segment(ReadOnlyMemory<T> items, long runningIndex)
52 {
53 Debug.Assert(runningIndex >= 0);
54 Memory = items;
55 RunningIndex = runningIndex;
56 }
57
58 public Segment Append(ReadOnlyMemory<T> items)
59 {
60 long runningIndex;
61 checked { runningIndex = RunningIndex + Memory.Length; }
62 Segment segment = new(items, runningIndex);
63 Next = segment;
64 return segment;
65 }
66 }
67}