Skip to content

Commit

Permalink
Add Advance APIs to builder and writer types
Browse files Browse the repository at this point in the history
  • Loading branch information
Sergio0694 committed Sep 26, 2023
1 parent 9c37a2a commit d874907
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,20 @@ public readonly int Count
get => this.writer!.WrittenSpan.Length;
}

/// <summary>
/// Advances the current writer and gets a <see cref="Span{T}"/> to the requested memory area.
/// </summary>
/// <param name="requestedSize">The requested size to advance by.</param>
/// <returns>A <see cref="Span{T}"/> to the requested memory area.</returns>
/// <remarks>
/// No other data should be written to the builder while the returned <see cref="Span{T}"/>
/// is in use, as it could invalidate the memory area wrapped by it, if resizing occurs.
/// </remarks>
public readonly Span<T> Advance(int requestedSize)
{
return this.writer!.Advance(requestedSize);
}

/// <inheritdoc cref="ImmutableArray{T}.Builder.Add(T)"/>
public readonly void Add(T item)
{
Expand Down Expand Up @@ -159,6 +173,18 @@ public ReadOnlySpan<T> WrittenSpan
get => new(this.array, 0, this.index);
}

/// <inheritdoc cref="ImmutableArrayBuilder{T}.Advance"/>
public Span<T> Advance(int requestedSize)
{
EnsureCapacity(requestedSize);

Span<T> span = this.array.AsSpan(this.index, requestedSize);

this.index += requestedSize;

return span;
}

/// <inheritdoc cref="ImmutableArrayBuilder{T}.Add"/>
public void Add(T value)
{
Expand Down
20 changes: 20 additions & 0 deletions src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,26 @@ private IndentedTextWriter(ImmutableArrayBuilder<char> builder)
}
}

/// <summary>
/// Advances the current writer and gets a <see cref="Span{T}"/> to the requested memory area.
/// </summary>
/// <param name="requestedSize">The requested size to advance by.</param>
/// <returns>A <see cref="Span{T}"/> to the requested memory area.</returns>
/// <remarks>
/// No other data should be written to the writer while the returned <see cref="Span{T}"/>
/// is in use, as it could invalidate the memory area wrapped by it, if resizing occurs.
/// </remarks>
public Span<char> 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);
}

/// <summary>
/// Increases the current indentation level.
/// </summary>
Expand Down

0 comments on commit d874907

Please sign in to comment.