Optimize ImmutableArrayBuilder<T> type

このコミットが含まれているのは:
Sergio Pedri committed 2022-10-07 09:14:17 -07:00
1 親 f9e75e2526
コミット a751d128a3
1ファイル変更
+122 -74
+122 -74
ファイルの表示
@@ -5,35 +5,34 @@
using System;
using System.Collections.Immutable;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace ComputeSharp.SourceGeneration.Helpers;
/// <summary>
/// A helper type to build <see cref="ImmutableArray{T}"/> instances with pooled buffers.
/// A helper type to build sequences of values with pooled buffers.
/// </summary>
/// <typeparam name="T">The type of items to create arrays for.</typeparam>
/// <typeparam name="T">The type of items to create sequences for.</typeparam>
internal ref struct ImmutableArrayBuilder<T>
{
/// <summary>
/// The shared <see cref="ObjectPool{T}"/> instance to share <see cref="ImmutableArray{T}.Builder"/> objects.
/// The shared <see cref="ObjectPool{T}"/> instance to share <see cref="Writer"/> objects.
/// </summary>
private static readonly ObjectPool<ImmutableArray<T>.Builder> sharedObjectPool = new(ImmutableArray.CreateBuilder<T>);
private static readonly ObjectPool<Writer> sharedObjectPool = new(static () => new Writer());
/// <summary>
/// The owner <see cref="ObjectPool{T}"/> instance.
/// </summary>
private readonly ObjectPool<ImmutableArray<T>.Builder> objectPool;
private readonly ObjectPool<Writer> objectPool;
/// <summary>
/// The rented <see cref="ImmutableArray{T}.Builder"/> instance to use.
/// The rented <see cref="Writer"/> instance to use.
/// </summary>
private ImmutableArray<T>.Builder? builder;
private Writer? writer;
/// <summary>
/// Rents a new pooled <see cref="ImmutableArray{T}.Builder"/> instance through a new <see cref="ImmutableArrayBuilder{T}"/> value.
/// Creates a <see cref="ImmutableArrayBuilder{T}"/> value with a pooled underlying data writer.
/// </summary>
/// <returns>A <see cref="ImmutableArrayBuilder{T}"/> to interact with the underlying <see cref="ImmutableArray{T}.Builder"/> instance.</returns>
/// <returns>A <see cref="ImmutableArrayBuilder{T}"/> instance to write data to.</returns>
public static ImmutableArrayBuilder<T> Rent()
{
return new(sharedObjectPool, sharedObjectPool.Allocate());
@@ -42,107 +41,156 @@ internal ref struct ImmutableArrayBuilder<T>
/// <summary>
/// Creates a new <see cref="ImmutableArrayBuilder{T}"/> object with the specified parameters.
/// </summary>
/// <param name="objectPool"></param>
/// <param name="builder"></param>
private ImmutableArrayBuilder(ObjectPool<ImmutableArray<T>.Builder> objectPool, ImmutableArray<T>.Builder builder)
/// <param name="objectPool">The target <see cref="ObjectPool{T}"/> to return <paramref name="writer"/> to.</param>
/// <param name="writer">The target data writer to use.</param>
private ImmutableArrayBuilder(ObjectPool<Writer> objectPool, Writer writer)
{
this.objectPool = objectPool;
this.builder = builder;
}
/// <inheritdoc cref="ImmutableArray{T}.Builder.Count"/>
public readonly int Count
{
get => this.builder!.Count;
this.writer = writer;
}
/// <inheritdoc cref="ImmutableArray{T}.Builder.Add(T)"/>
public readonly void Add(T item)
{
this.builder!.Add(item);
this.writer!.Add(item);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items to add at the end of the array.</param>
public readonly unsafe void AddRange(ReadOnlySpan<T> items)
public readonly void AddRange(ReadOnlySpan<T> items)
{
if (items.IsEmpty)
{
return;
}
int offset = this.builder!.Count;
this.builder!.Count += items.Length;
ref T firstItem = ref Unsafe.AsRef(in this.builder!.ItemRef(offset));
if (typeof(T) == typeof(char))
{
int sizeInBytes = checked(items.Length * Unsafe.SizeOf<T>());
fixed (void* source = &Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(items)))
fixed (void* destination = &Unsafe.As<T, byte>(ref firstItem))
{
new ReadOnlySpan<byte>(source, sizeInBytes).CopyTo(new Span<byte>(destination, sizeInBytes));
}
}
else
{
ref T lastItem = ref Unsafe.Add(ref firstItem, items.Length);
ref T sourceItem = ref MemoryMarshal.GetReference(items);
while (Unsafe.IsAddressLessThan(ref firstItem, ref lastItem))
{
firstItem = sourceItem;
firstItem = ref Unsafe.Add(ref firstItem, 1);
sourceItem = ref Unsafe.Add(ref sourceItem, 1);
}
}
this.writer!.AddRange(items);
}
/// <inheritdoc cref="ImmutableArray{T}.Builder.ToImmutable"/>
public readonly ImmutableArray<T> ToImmutable()
{
return this.builder!.ToImmutable();
T[] array = this.writer!.WrittenSpan.ToArray();
return Unsafe.As<T[], ImmutableArray<T>>(ref array);
}
/// <inheritdoc cref="ImmutableArray{T}.Builder.ToArray"/>
public readonly T[] ToArray()
{
return this.builder!.ToArray();
return this.writer!.WrittenSpan.ToArray();
}
/// <inheritdoc/>
public override readonly unsafe string ToString()
public override readonly string ToString()
{
if (typeof(T) == typeof(char) &&
this.builder!.Count > 0)
{
fixed (char* p = &Unsafe.As<T, char>(ref Unsafe.AsRef(in this.builder!.ItemRef(0))))
{
return new ReadOnlySpan<char>(p, this.builder!.Count).ToString();
}
}
return this.builder!.ToString();
return this.writer!.WrittenSpan.ToString();
}
/// <inheritdoc cref="IDisposable.Dispose"/>
public void Dispose()
{
ImmutableArray<T>.Builder? builder = this.builder;
Writer? writer = this.writer;
this.builder = null;
this.writer = null;
if (builder is not null)
if (writer is not null)
{
builder.Clear();
writer.Clear();
this.objectPool.Free(builder);
this.objectPool.Free(writer);
}
}
/// <summary>
/// A class handling the actual buffer writing.
/// </summary>
private sealed class Writer
{
/// <summary>
/// The underlying <typeparamref name="T"/> array.
/// </summary>
private T[] array;
/// <summary>
/// The starting offset within <see cref="array"/>.
/// </summary>
private int index;
/// <summary>
/// Creates a new <see cref="Writer"/> instance with the specified parameters.
/// </summary>
public Writer()
{
this.array = new T[8];
this.index = 0;
}
/// <summary>
/// Gets the data written to the underlying buffer so far, as a <see cref="ReadOnlySpan{T}"/>.
/// </summary>
public ReadOnlySpan<T> WrittenSpan
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new(this.array, 0, this.index);
}
/// <inheritdoc cref="ImmutableArrayBuilder{T}.Add"/>
public void Add(T value)
{
EnsureCapacity(1);
this.array[this.index++] = value;
}
/// <inheritdoc cref="ImmutableArrayBuilder{T}.AddRange"/>
public void AddRange(ReadOnlySpan<T> items)
{
EnsureCapacity(items.Length);
items.CopyTo(this.array.AsSpan(this.index));
this.index += items.Length;
}
/// <summary>
/// Clears the items in the current writer.
/// </summary>
public void Clear()
{
if (typeof(T) != typeof(char))
{
this.array.AsSpan(0, this.index).Clear();
}
this.index = 0;
}
/// <summary>
/// Ensures that <see cref="array"/> has enough free space to contain a given number of new items.
/// </summary>
/// <param name="requestedSize">The minimum number of items to ensure space for in <see cref="array"/>.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnsureCapacity(int requestedSize)
{
if (requestedSize > this.array.Length - this.index)
{
ResizeBuffer(requestedSize);
}
}
/// <summary>
/// Resizes <see cref="array"/> to ensure it can fit the specified number of new items.
/// </summary>
/// <param name="sizeHint">The minimum number of items to ensure space for in <see cref="array"/>.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private void ResizeBuffer(int sizeHint)
{
int minimumSize = this.index + sizeHint;
int requestedSize = Math.Max(this.array.Length * 2, minimumSize);
T[] newArray = new T[requestedSize];
Array.Copy(this.array, newArray, this.index);
this.array = newArray;
}
}
}