Skip to content

Commit 3e43ef7

Browse files
🎨 Improve context API
1 parent 754c321 commit 3e43ef7

File tree

5 files changed

+40
-67
lines changed

5 files changed

+40
-67
lines changed

Lite3DotNet.Generators/Lite3ApiGenerator.cs

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -193,12 +193,10 @@ private static bool TryWriteMethod(StringBuilder source,
193193
var isChainableMethod = isInitMethod || isSetMethod || isAppendMethod;
194194

195195
var originalReturnTypeName = method.ReturnsVoid ? "void" : GetTypeName(method.ReturnType);
196-
197-
const string refContext = $"ref {ContextTypeName}";
198196

199-
var returnTypeMoniker =
197+
var returnTypeName =
200198
useTryPattern ? "bool" :
201-
isContextApi && isChainableMethod ? refContext :
199+
isContextApi && isChainableMethod ? ContextTypeName :
202200
returnArgParam != null ? GetTypeName(returnArgParam.Type) :
203201
tryPattern ? "void" :
204202
originalReturnTypeName;
@@ -256,7 +254,7 @@ private static bool TryWriteMethod(StringBuilder source,
256254

257255
if (text.StartsWith("<returns>"))
258256
{
259-
if (returnTypeMoniker == "void")
257+
if (returnTypeName == "void")
260258
continue;
261259

262260
if (useTryPattern)
@@ -314,7 +312,7 @@ private static bool TryWriteMethod(StringBuilder source,
314312
.Append(indent).AppendLine(InlineAttribute)
315313
.Append(indent)
316314
.Append("public static ")
317-
.Append(returnTypeMoniker)
315+
.Append(returnTypeName)
318316
.Append(" ")
319317
.Append(useTryPattern ? "Try" : null)
320318
.Append(method.Name)
@@ -325,7 +323,7 @@ private static bool TryWriteMethod(StringBuilder source,
325323
{
326324
if (isContextApi && index == 0)
327325
{
328-
source.Append("this ").Append(refContext).Append(" context");
326+
source.Append("this ").Append(ContextTypeName).Append(" context");
329327
indexOffset++;
330328
}
331329

@@ -421,10 +419,10 @@ private static bool TryWriteMethod(StringBuilder source,
421419
if (!useTryPattern)
422420
{
423421
if (isContextApi && isChainableMethod)
424-
source.Append(indent).AppendLine("return ref context;");
422+
source.Append(indent).AppendLine("return context;");
425423
else if (returnArgParam != null)
426424
source.Append(indent).Append("return ").Append(returnArgParam.Name).AppendLine(";");
427-
else if (returnTypeMoniker != "void")
425+
else if (returnTypeName != "void")
428426
source.Append(indent).AppendLine("return result;");
429427
}
430428

Lite3DotNet.Tests/ContextApiExamples.cs

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,7 @@ public class ContextApiExamples(ITestOutputHelper output)
1919
[Fact]
2020
public void Can_build_messages()
2121
{
22-
var context = Lite3Context.Create();
23-
using var scope = context.BeginScope();
22+
using var context = Lite3Context.Create();
2423

2524
// Build message
2625
context
@@ -40,8 +39,7 @@ public void Can_build_messages()
4039
output.WriteLine(Lite3JsonEncoder.EncodeString(context.WrittenBuffer, 0));
4140

4241
// Transmit data / copy to new context
43-
var receiveContext = Lite3Context.CreateFrom(context.Buffer, context.Position);
44-
using var transmitScope = receiveContext.BeginScope();
42+
using var receiveContext = Lite3Context.CreateFrom(context.Buffer, context.Position);
4543

4644
// Mutate (zero-copy, no parsing)
4745
output.WriteLine("Verifying fastest lap");
@@ -62,8 +60,7 @@ public void Can_build_messages()
6260
[Fact]
6361
public void Can_read_messages()
6462
{
65-
var context = Lite3Context.Create();
66-
using var scope = context.BeginScope();
63+
using var context = Lite3Context.Create();
6764

6865
// Build Message
6966
context
@@ -123,8 +120,7 @@ public void Can_read_messages()
123120
[Fact]
124121
public void Can_work_with_strings()
125122
{
126-
var context = Lite3Context.Create();
127-
using var scope = context.BeginScope();
123+
using var context = Lite3Context.Create();
128124

129125
// Build message
130126
context
@@ -158,8 +154,7 @@ public void Can_work_with_strings()
158154
[Fact]
159155
public void Can_work_with_nesting()
160156
{
161-
var context = Lite3Context.Create();
162-
using var scope = context.BeginScope();
157+
using var context = Lite3Context.Create();
163158

164159
// Build message
165160
context
@@ -190,8 +185,7 @@ public void Can_work_with_nesting()
190185
[Fact]
191186
public void Can_work_with_arrays()
192187
{
193-
var context = Lite3Context.Create();
194-
using var scope = context.BeginScope();
188+
using var context = Lite3Context.Create();
195189

196190
context
197191
.InitializeArray()
@@ -241,8 +235,7 @@ public void Can_use_iterators()
241235
"Sarah"u8.ToArray(),
242236
};
243237

244-
var context = Lite3Context.Create();
245-
using var scope = context.BeginScope();
238+
using var context = Lite3Context.Create();
246239

247240
// Build array
248241
context.InitializeArray();
@@ -308,9 +301,8 @@ public async Task Can_convert_to_and_from_JSON()
308301
await using var fileStream = File.OpenRead("periodic_table.json");
309302

310303
var decodeResult = await Lite3JsonDecoder.DecodeAsync(PipeReader.Create(fileStream));
311-
var context = Lite3Context.CreateFromOwned(decodeResult.Buffer, decodeResult.Position, decodeResult.ArrayPool);
312304

313-
using var scope = context.BeginScope();
305+
using var context = Lite3Context.CreateFromOwned(decodeResult.Buffer, decodeResult.Position, decodeResult.ArrayPool);
314306

315307
// Iterator to find densest element
316308
var dataOffset = context.GetArray(0, "data"u8);

Lite3DotNet.Tests/TypeQueryTests.cs

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,7 @@ public void Can_get_array_type_with_buffer_API()
4141
[Fact]
4242
public void Can_get_array_type_with_context_API()
4343
{
44-
var context = Lite3Context.Create();
45-
46-
using var scope = context.BeginScope();
44+
using var context = Lite3Context.Create();
4745

4846
// Initialize as array
4947
context.InitializeArray();
@@ -74,9 +72,7 @@ public void Can_get_array_type_with_context_API()
7472
[Fact]
7573
public void Can_get_array_types_when_nested()
7674
{
77-
var context = Lite3Context.Create();
78-
79-
using var scope = context.BeginScope();
75+
using var context = Lite3Context.Create();
8076

8177
// Initialize as object
8278
context.InitializeObject();
@@ -105,7 +101,7 @@ public void Can_get_root_type_with_context_API()
105101
// Test object root
106102
var context = Lite3Context.Create();
107103

108-
using (context.BeginScope())
104+
using (context)
109105
{
110106
context.InitializeObject();
111107

@@ -115,7 +111,7 @@ public void Can_get_root_type_with_context_API()
115111
// Test array root
116112
context = Lite3Context.Create();
117113

118-
using (context.BeginScope())
114+
using (context)
119115
{
120116
context.InitializeArray();
121117

@@ -146,9 +142,7 @@ public void Can_get_root_type_with_buffer_API()
146142
[Fact]
147143
public void Can_get_root_type_with_empty_buffer()
148144
{
149-
var context = Lite3Context.Create();
150-
151-
using var scope = context.BeginScope();
145+
using var context = Lite3Context.Create();
152146

153147
context.GetRootType().ShouldBe(Lite3Core.ValueKind.Invalid);
154148
}

Lite3DotNet/Lite3Context.cs

Lines changed: 19 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
namespace Lite3DotNet;
55

6-
public ref struct Lite3Context
6+
public sealed class Lite3Context : IDisposable
77
{
88
/// <summary>
99
/// <para>Create a context, optionally with a custom size.</para>
@@ -28,7 +28,7 @@ public static Lite3Context Create(int initialCapacity = Lite3Buffer.MinBufferSiz
2828
// Ensure that at least the root type tag is invalid
2929
buffer[0] = (byte)Lite3Core.ValueKind.Invalid;
3030

31-
return new Lite3Context(buffer, position: 0, isRentedBuffer: true, arrayPool);
31+
return new Lite3Context(arrayPool, buffer, position: 0, isRentedBuffer: true);
3232
}
3333

3434
/// <summary>
@@ -61,7 +61,7 @@ public static Lite3Context CreateFrom(ReadOnlySpan<byte> buffer, int position, A
6161

6262
buffer.CopyTo(newBuffer);
6363

64-
return new Lite3Context(newBuffer, position, isRentedBuffer: true, arrayPool: arrayPool);
64+
return new Lite3Context(arrayPool: arrayPool, buffer: newBuffer, position: position, isRentedBuffer: true);
6565
}
6666

6767
/// <summary>
@@ -86,46 +86,37 @@ public static Lite3Context CreateFrom(ReadOnlySpan<byte> buffer, int position, A
8686
public static Lite3Context CreateFromOwned(byte[] buffer, int position, ArrayPool<byte>? arrayPool = null)
8787
{
8888
arrayPool ??= ArrayPool<byte>.Shared;
89-
return new Lite3Context(buffer, position, isRentedBuffer: true, arrayPool);
89+
return new Lite3Context(arrayPool, buffer, position, isRentedBuffer: true);
9090
}
91-
92-
private readonly Scope _scope;
9391

94-
public Span<byte> Buffer;
92+
public byte[] Buffer;
9593
public int Position;
94+
private readonly ArrayPool<byte> _arrayPool;
95+
private bool _isRentedBuffer;
9696

97-
private Lite3Context(byte[] buffer, int position, bool isRentedBuffer, ArrayPool<byte> arrayPool)
97+
private Lite3Context(ArrayPool<byte> arrayPool, byte[] buffer, int position, bool isRentedBuffer)
9898
{
99-
_scope = new Scope(buffer, isRentedBuffer, arrayPool);
99+
_arrayPool = arrayPool;
100+
_isRentedBuffer = isRentedBuffer;
100101

101102
Buffer = buffer;
102103
Position = position;
103104
}
104-
105-
public Scope BeginScope() => _scope;
106105

107106
public Span<byte> WrittenBuffer => Buffer[..Position];
108-
109-
internal Lite3Core.Status Grow()
107+
108+
public void Dispose()
110109
{
111-
var status = Lite3Buffer.Grow(_scope.ArrayPool, _scope.IsRentedBuffer, _scope.Buffer, out _scope.Buffer);
112-
113-
_scope.IsRentedBuffer = true;
114-
115-
return status;
110+
if (_isRentedBuffer)
111+
ArrayPool<byte>.Shared.Return(Buffer);
116112
}
117113

118-
public sealed class Scope(byte[] buffer, bool isRentedBuffer, ArrayPool<byte> arrayPool)
119-
: IDisposable
114+
internal Lite3Core.Status Grow()
120115
{
121-
internal readonly ArrayPool<byte> ArrayPool = arrayPool;
122-
internal byte[] Buffer = buffer;
123-
internal bool IsRentedBuffer = isRentedBuffer;
116+
var status = Lite3Buffer.Grow(_arrayPool, _isRentedBuffer, Buffer, out Buffer);
117+
118+
_isRentedBuffer = true;
124119

125-
public void Dispose()
126-
{
127-
if (IsRentedBuffer)
128-
ArrayPool<byte>.Shared.Return(Buffer);
129-
}
120+
return status;
130121
}
131122
}

README.md

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,7 @@ Console.WriteLine($"Max Retries: {maxRetries}");
4848
The equivalent Context API code is below.
4949

5050
```csharp
51-
var context = Lite3Context.Create();
52-
53-
using var scope = context.BeginScope();
51+
using var context = Lite3Context.Create();
5452

5553
context
5654
.InitializeObject()

0 commit comments

Comments
 (0)