From 117bdc2ab3363c25716898a7b7f6da7312ea3939 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 26 Sep 2023 18:34:49 +0200 Subject: [PATCH] Add Advance APIs to builder and writer types --- .../Helpers/ImmutableArrayBuilder{T}.cs | 26 +++++++++++++++++++ .../Helpers/IndentedTextWriter.cs | 20 ++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs index 3aa5b62b..aa1d495a 100644 --- a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs +++ b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs @@ -60,6 +60,20 @@ internal struct ImmutableArrayBuilder : IDisposable get => this.writer!.WrittenSpan.Length; } + /// + /// Advances the current writer and gets a to the requested memory area. + /// + /// The requested size to advance by. + /// A to the requested memory area. + /// + /// No other data should be written to the builder while the returned + /// is in use, as it could invalidate the memory area wrapped by it, if resizing occurs. + /// + public readonly Span Advance(int requestedSize) + { + return this.writer!.Advance(requestedSize); + } + /// public readonly void Add(T item) { @@ -159,6 +173,18 @@ internal struct ImmutableArrayBuilder : IDisposable get => new(this.array, 0, this.index); } + /// + public Span Advance(int requestedSize) + { + EnsureCapacity(requestedSize); + + Span span = this.array.AsSpan(this.index, requestedSize); + + this.index += requestedSize; + + return span; + } + /// public void Add(T value) { diff --git a/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs index 6fadbdae..470f6696 100644 --- a/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs +++ b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs @@ -72,6 +72,26 @@ internal sealed class IndentedTextWriter : IDisposable } } + /// + /// Advances the current writer and gets a to the requested memory area. + /// + /// The requested size to advance by. + /// A to the requested memory area. + /// + /// No other data should be written to the writer while the returned + /// is in use, as it could invalidate the memory area wrapped by it, if resizing occurs. + /// + public Span Advance(int requestedSize) + { + // Add the leading whitespace if needed (same as WriteRawText below) + if (this.builder.Count == 0 || this.builder.WrittenSpan[^1] == DefaultNewLine) + { + this.builder.AddRange(this.currentIndentation.AsSpan()); + } + + return this.builder.Advance(requestedSize); + } + /// /// Increases the current indentation level. ///