diff --git a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs index bfd2ce02..d682f0cf 100644 --- a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs +++ b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs @@ -4,6 +4,8 @@ using System; using System.Collections.Immutable; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; namespace ComputeSharp.SourceGeneration.Helpers; @@ -60,6 +62,48 @@ internal ref struct ImmutableArrayBuilder this.builder!.Add(item); } + /// + /// Adds the specified items to the end of the array. + /// + /// The items to add at the end of the array. + public readonly unsafe void AddRange(ReadOnlySpan 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()); + + fixed (void* source = &Unsafe.As(ref MemoryMarshal.GetReference(items))) + fixed (void* destination = &Unsafe.As(ref firstItem)) + { + new ReadOnlySpan(source, sizeInBytes).CopyTo(new Span(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); + } + } + } + /// public readonly ImmutableArray ToImmutable() { @@ -72,6 +116,21 @@ internal ref struct ImmutableArrayBuilder return this.builder!.ToArray(); } + /// + public override readonly unsafe string ToString() + { + if (typeof(T) == typeof(char) && + this.builder!.Count > 0) + { + fixed (char* p = &Unsafe.As(ref Unsafe.AsRef(in this.builder!.ItemRef(0)))) + { + return new ReadOnlySpan(p, this.builder!.Count).ToString(); + } + } + + return this.builder!.ToString(); + } + /// public void Dispose() {