This is an automated email from the ASF dual-hosted git repository.

CurtHagenlocher pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-dotnet.git


The following commit(s) were added to refs/heads/main by this push:
     new ba04eca  perf: Write concatenated buffers directly into allocator 
memory (#463)
ba04eca is described below

commit ba04ecae0416d0aaaf79783caf106127409bfb99
Author: Curt Hagenlocher <[email protected]>
AuthorDate: Sun Oct 18 08:27:57 2026 -0700

    perf: Write concatenated buffers directly into allocator memory (#463)
    
    ## What's Changed
    
    `ArrayDataConcatenator` built each output buffer by appending elements
    one at a time to a growing managed `ArrowBuffer.Builder` and then
    copying the result into memory from the allocator. This change:
    
    - **Writes directly into allocator memory.** Each output buffer is sized
    up front, allocated from the caller's `MemoryAllocator` (or the
    default), and filled in place. Allocators aren't required to return
    zeroed memory, so padding and the unused trailing bits of bitmaps are
    cleared explicitly.
    - **Copies unaligned bitmaps in bulk.** Bitmaps that don't start on a
    byte boundary (e.g. from sliced inputs) used to be copied one bit at a
    time. The new internal `BitUtility.CopyBits` copies eight bytes at a
    time on little-endian platforms and falls back to byte-at-a-time
    otherwise.
    
    Run-end-encoded arrays still use builders, because the number of runs
    isn't known up front.
    
    ### Tests
    - `BitUtility.CopyBits`: every source/destination start position from 0
    to 15 with lengths from 0 to 150, including checks that bits outside the
    copied range are left unchanged.
    - A new `GarbageMemoryAllocator` test allocator fills new memory with a
    non-zero pattern and counts outstanding allocations. The existing
    concatenation test cases, sliced and unsliced, run through it to check
    the results, that the provided allocator is used, and that nothing
    leaks.
    - Checks that padding is zeroed, and a test that concatenates many
    randomly sliced boolean arrays with nulls.
    
    ### Benchmark
    Adds `ArrayConcatenatorBenchmark`: 10 inputs × 100,000 rows each.
    "Sliced" slices every input at an odd offset.
    
    | Benchmark | Before | After | Speedup | Managed memory before → after |
    |---|---|---|---|---|
    | Int32 | 2.19 ms | 1.05 ms | 2.1× | 4.0 MB → ~1 KB |
    | Int32, sliced | 5.03 ms | 1.09 ms | 4.6× | 4.0 MB → ~1 KB |
    | Boolean | 154 µs | 8.9 µs | 17× | 245 KB → ~0.8 KB |
    | Boolean, sliced | 5,682 µs | 19.7 µs | 289× | 245 KB → ~0.8 KB |
    | String | 16.2 ms | 6.06 ms | 2.7× | 49 MB → ~1.4 KB |
    | String, sliced | 18.7 ms | 6.06 ms | 3.1× | 49 MB → ~1.4 KB |
    | StringView | 8.99 ms | 5.18 ms | 1.7× | 15.7 MB → ~1.6 KB |
    | StringView, sliced | 11.9 ms | 5.23 ms | 2.3× | 15.7 MB → ~1.6 KB |
    | List | 6.70 ms | 3.39 ms | 2.0× | 10.7 MB → ~1.8 KB |
    | List, sliced | 9.94 ms | 3.46 ms | 2.9× | 10.7 MB → ~2.4 KB |
    | DenseUnion | 6.49 ms | 3.06 ms | 2.1× | 10.3 MB → ~2.9 KB |
    | DenseUnion, sliced | 6.50 ms | 3.11 ms | 2.1× | 10.3 MB → ~2.9 KB |
    
    BenchmarkDotNet 0.15.8, .NET 8, Windows 11.
    
    🤖 Generated with [Claude Code](https://claude.com/claude-code)
    
    ---------
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 src/Apache.Arrow/Arrays/ArrayDataConcatenator.cs   | 621 +++++++++++++--------
 src/Apache.Arrow/BitUtility.cs                     |  69 +++
 .../ArrayConcatenatorBenchmark.cs                  | 151 +++++
 .../ArrowArrayConcatenatorTests.cs                 | 104 ++++
 test/Apache.Arrow.Tests/BitUtilityTests.cs         |  65 +++
 test/Apache.Arrow.Tests/GarbageMemoryAllocator.cs  |  80 +++
 6 files changed, 858 insertions(+), 232 deletions(-)

diff --git a/src/Apache.Arrow/Arrays/ArrayDataConcatenator.cs 
b/src/Apache.Arrow/Arrays/ArrayDataConcatenator.cs
index e78edfe..fd8afed 100644
--- a/src/Apache.Arrow/Arrays/ArrayDataConcatenator.cs
+++ b/src/Apache.Arrow/Arrays/ArrayDataConcatenator.cs
@@ -14,7 +14,9 @@
 // limitations under the License.
 
 using System;
+using System.Buffers;
 using System.Collections.Generic;
+using System.Runtime.CompilerServices;
 using Apache.Arrow.Memory;
 using Apache.Arrow.Scalars;
 using Apache.Arrow.Types;
@@ -285,36 +287,43 @@ namespace Apache.Arrow
 
             private ArrowBuffer ConcatenateShiftedIndexBuffer(IntegerType 
indexType)
             {
-                int byteWidth = indexType.BitWidth / 8;
-                var builder = new ArrowBuffer.Builder<byte>(_totalLength * 
byteWidth);
-                builder.Resize(_totalLength * byteWidth);
-                Span<byte> destination = builder.Span;
-                int position = 0;
-                long shift = 0;
-
-                foreach (ArrayData arrayData in _arrayDataList)
+                int byteLength = checked(_totalLength * (indexType.BitWidth / 
8));
+                IMemoryOwner<byte> owner = AllocateBuffer(byteLength, out 
Span<byte> destination);
+                try
                 {
-                    if (arrayData.Length == 0)
+                    int byteWidth = indexType.BitWidth / 8;
+                    int position = 0;
+                    long shift = 0;
+
+                    foreach (ArrayData arrayData in _arrayDataList)
                     {
-                        continue;
-                    }
+                        if (arrayData.Length == 0)
+                        {
+                            continue;
+                        }
 
-                    ReadOnlySpan<byte> validity = arrayData.Buffers[0].Span;
-                    bool allNull = validity.Length == 0 && 
arrayData.GetNullCount() == arrayData.Length;
-                    ReadOnlySpan<byte> source = 
arrayData.Buffers[1].Span.Slice(arrayData.Offset * byteWidth, arrayData.Length 
* byteWidth);
+                        ReadOnlySpan<byte> validity = 
arrayData.Buffers[0].Span;
+                        bool allNull = validity.Length == 0 && 
arrayData.GetNullCount() == arrayData.Length;
+                        ReadOnlySpan<byte> source = 
arrayData.Buffers[1].Span.Slice(arrayData.Offset * byteWidth, arrayData.Length 
* byteWidth);
 
-                    for (int i = 0; i < arrayData.Length; i++)
-                    {
-                        bool isValid = validity.Length == 0 ? !allNull : 
BitUtility.GetBit(validity, arrayData.Offset + i);
-                        // A null slot's index is unspecified and may not be 
in range, so write 0 instead of shifting it.
-                        long index = isValid ? ReadIndex(source, 
indexType.TypeId, i) + shift : 0;
-                        WriteIndex(destination, indexType.TypeId, position++, 
index);
-                    }
+                        for (int i = 0; i < arrayData.Length; i++)
+                        {
+                            bool isValid = validity.Length == 0 ? !allNull : 
BitUtility.GetBit(validity, arrayData.Offset + i);
+                            // A null slot's index is unspecified and may not 
be in range, so write 0 instead of shifting it.
+                            long index = isValid ? ReadIndex(source, 
indexType.TypeId, i) + shift : 0;
+                            WriteIndex(destination, indexType.TypeId, 
position++, index);
+                        }
 
-                    shift += arrayData.Dictionary.Length;
+                        shift += arrayData.Dictionary.Length;
+                    }
+                }
+                catch
+                {
+                    owner.Dispose();
+                    throw;
                 }
 
-                return builder.Build(_allocator);
+                return BuildBuffer(owner, byteLength);
             }
 
             private static long ReadIndex(ReadOnlySpan<byte> source, 
ArrowTypeId typeId, int i) => typeId switch
@@ -365,60 +374,69 @@ namespace Apache.Arrow
                 ArrowBuffer sizesBuffer = 
ConcatenateFixedWidthTypeValueBuffer(2, Int64Type.Default);
 
                 var children = new List<ArrayData>(_arrayDataList.Count);
-                var offsetsBuilder = new 
ArrowBuffer.Builder<long>(_totalLength);
-                long baseOffset = 0;
-
-                foreach (ArrayData arrayData in _arrayDataList)
+                int offsetsByteLength = checked(_totalLength * sizeof(long));
+                IMemoryOwner<byte> offsetsOwner = 
AllocateBuffer(offsetsByteLength, out Span<byte> offsetsBytes);
+                try
                 {
-                    if (arrayData.Length == 0)
+                    Span<long> destination = offsetsBytes.CastTo<long>();
+                    int position = 0;
+                    long baseOffset = 0;
+
+                    foreach (ArrayData arrayData in _arrayDataList)
                     {
-                        continue;
-                    }
+                        if (arrayData.Length == 0)
+                        {
+                            continue;
+                        }
 
-                    var child = arrayData.Children[0];
-                    ReadOnlySpan<long> offsets = 
arrayData.Buffers[1].Span.CastTo<long>().Slice(arrayData.Offset, 
arrayData.Length);
-                    ReadOnlySpan<long> sizes = 
arrayData.Buffers[2].Span.CastTo<long>().Slice(arrayData.Offset, 
arrayData.Length);
-                    long minOffset = 0;
-                    long maxEnd = 0;
-                    bool hasNonEmptyValue = false;
+                        var child = arrayData.Children[0];
+                        ReadOnlySpan<long> offsets = 
arrayData.Buffers[1].Span.CastTo<long>().Slice(arrayData.Offset, 
arrayData.Length);
+                        ReadOnlySpan<long> sizes = 
arrayData.Buffers[2].Span.CastTo<long>().Slice(arrayData.Offset, 
arrayData.Length);
+                        long minOffset = 0;
+                        long maxEnd = 0;
+                        bool hasNonEmptyValue = false;
 
-                    for (int i = 0; i < arrayData.Length; ++i)
-                    {
-                        if (sizes[i] > 0)
+                        for (int i = 0; i < arrayData.Length; ++i)
                         {
-                            minOffset = hasNonEmptyValue ? Math.Min(minOffset, 
offsets[i]) : offsets[i];
-                            maxEnd = Math.Max(maxEnd, offsets[i] + sizes[i]);
-                            hasNonEmptyValue = true;
+                            if (sizes[i] > 0)
+                            {
+                                minOffset = hasNonEmptyValue ? 
Math.Min(minOffset, offsets[i]) : offsets[i];
+                                maxEnd = Math.Max(maxEnd, offsets[i] + 
sizes[i]);
+                                hasNonEmptyValue = true;
+                            }
                         }
-                    }
 
-                    if (!hasNonEmptyValue)
-                    {
-                        for (int i = 0; i < offsets.Length; ++i)
+                        if (!hasNonEmptyValue)
                         {
-                            offsetsBuilder.Append(baseOffset);
+                            destination.Slice(position, 
offsets.Length).Fill(baseOffset);
+                            position += offsets.Length;
+
+                            children.Add(child.Slice(0, 0));
+                            continue;
                         }
 
-                        children.Add(child.Slice(0, 0));
-                        continue;
-                    }
+                        for (int i = 0; i < offsets.Length; ++i)
+                        {
+                            destination[position++] = baseOffset + offsets[i] 
- minOffset;
+                        }
 
-                    foreach (long offset in offsets)
-                    {
-                        offsetsBuilder.Append(baseOffset + offset - minOffset);
-                    }
+                        var childLength = maxEnd - minOffset;
+                        if (minOffset != 0 || childLength != child.Length)
+                        {
+                            child = child.Slice(checked((int)minOffset), 
checked((int)childLength));
+                        }
 
-                    var childLength = maxEnd - minOffset;
-                    if (minOffset != 0 || childLength != child.Length)
-                    {
-                        child = child.Slice(checked((int)minOffset), 
checked((int)childLength));
+                        baseOffset += childLength;
+                        children.Add(child);
                     }
-
-                    baseOffset += childLength;
-                    children.Add(child);
+                }
+                catch
+                {
+                    offsetsOwner.Dispose();
+                    throw;
                 }
 
-                ArrowBuffer offsetBuffer = offsetsBuilder.Build(_allocator);
+                ArrowBuffer offsetBuffer = BuildBuffer(offsetsOwner, 
offsetsByteLength);
                 ArrayData combinedChild = ConcatenateChildrenOrEmpty(children);
 
                 Result = new ArrayData(type, _totalLength, _totalNullCount, 0, 
new ArrowBuffer[] { validityBuffer, offsetBuffer, sizesBuffer }, new[] { 
combinedChild });
@@ -433,60 +451,69 @@ namespace Apache.Arrow
                 ArrowBuffer sizesBuffer = 
ConcatenateFixedWidthTypeValueBuffer(2, Int32Type.Default);
 
                 var children = new List<ArrayData>(_arrayDataList.Count);
-                var offsetsBuilder = new 
ArrowBuffer.Builder<int>(_totalLength);
-                int baseOffset = 0;
-
-                foreach (ArrayData arrayData in _arrayDataList)
+                int offsetsByteLength = checked(_totalLength * sizeof(int));
+                IMemoryOwner<byte> offsetsOwner = 
AllocateBuffer(offsetsByteLength, out Span<byte> offsetsBytes);
+                try
                 {
-                    if (arrayData.Length == 0)
+                    Span<int> destination = offsetsBytes.CastTo<int>();
+                    int position = 0;
+                    int baseOffset = 0;
+
+                    foreach (ArrayData arrayData in _arrayDataList)
                     {
-                        continue;
-                    }
+                        if (arrayData.Length == 0)
+                        {
+                            continue;
+                        }
 
-                    var child = arrayData.Children[0];
-                    ReadOnlySpan<int> offsets = 
arrayData.Buffers[1].Span.CastTo<int>().Slice(arrayData.Offset, 
arrayData.Length);
-                    ReadOnlySpan<int> sizes = 
arrayData.Buffers[2].Span.CastTo<int>().Slice(arrayData.Offset, 
arrayData.Length);
-                    int minOffset = 0;
-                    int maxEnd = 0;
-                    bool hasNonEmptyValue = false;
+                        var child = arrayData.Children[0];
+                        ReadOnlySpan<int> offsets = 
arrayData.Buffers[1].Span.CastTo<int>().Slice(arrayData.Offset, 
arrayData.Length);
+                        ReadOnlySpan<int> sizes = 
arrayData.Buffers[2].Span.CastTo<int>().Slice(arrayData.Offset, 
arrayData.Length);
+                        int minOffset = 0;
+                        int maxEnd = 0;
+                        bool hasNonEmptyValue = false;
 
-                    for (int i = 0; i < arrayData.Length; ++i)
-                    {
-                        if (sizes[i] > 0)
+                        for (int i = 0; i < arrayData.Length; ++i)
                         {
-                            minOffset = hasNonEmptyValue ? Math.Min(minOffset, 
offsets[i]) : offsets[i];
-                            maxEnd = Math.Max(maxEnd, offsets[i] + sizes[i]);
-                            hasNonEmptyValue = true;
+                            if (sizes[i] > 0)
+                            {
+                                minOffset = hasNonEmptyValue ? 
Math.Min(minOffset, offsets[i]) : offsets[i];
+                                maxEnd = Math.Max(maxEnd, offsets[i] + 
sizes[i]);
+                                hasNonEmptyValue = true;
+                            }
                         }
-                    }
 
-                    if (!hasNonEmptyValue)
-                    {
-                        for (int i = 0; i < offsets.Length; ++i)
+                        if (!hasNonEmptyValue)
                         {
-                            offsetsBuilder.Append(baseOffset);
+                            destination.Slice(position, 
offsets.Length).Fill(baseOffset);
+                            position += offsets.Length;
+
+                            children.Add(child.Slice(0, 0));
+                            continue;
                         }
 
-                        children.Add(child.Slice(0, 0));
-                        continue;
-                    }
+                        for (int i = 0; i < offsets.Length; ++i)
+                        {
+                            destination[position++] = baseOffset + offsets[i] 
- minOffset;
+                        }
 
-                    foreach (int offset in offsets)
-                    {
-                        offsetsBuilder.Append(baseOffset + offset - minOffset);
-                    }
+                        var childLength = maxEnd - minOffset;
+                        if (minOffset != 0 || childLength != child.Length)
+                        {
+                            child = child.Slice(minOffset, childLength);
+                        }
 
-                    var childLength = maxEnd - minOffset;
-                    if (minOffset != 0 || childLength != child.Length)
-                    {
-                        child = child.Slice(minOffset, childLength);
+                        baseOffset += childLength;
+                        children.Add(child);
                     }
-
-                    baseOffset += childLength;
-                    children.Add(child);
+                }
+                catch
+                {
+                    offsetsOwner.Dispose();
+                    throw;
                 }
 
-                ArrowBuffer offsetBuffer = offsetsBuilder.Build(_allocator);
+                ArrowBuffer offsetBuffer = BuildBuffer(offsetsOwner, 
offsetsByteLength);
                 ArrayData combinedChild = ConcatenateChildrenOrEmpty(children);
 
                 Result = new ArrayData(type, _totalLength, _totalNullCount, 0, 
new ArrowBuffer[] { validityBuffer, offsetBuffer, sizesBuffer }, new[] { 
combinedChild });
@@ -1057,47 +1084,104 @@ namespace Apache.Arrow
                 throw new InvalidOperationException("Nested array data must 
contain child data.");
             }
 
-            private ArrowBuffer ConcatenateLargeOffsetBuffer()
+            private IMemoryOwner<byte> AllocateBuffer(int byteLength, out 
Span<byte> destination)
             {
-                var builder = new ArrowBuffer.Builder<long>(_totalLength + 1);
-                long baseOffset = 0;
+                // Buffers are padded to a multiple of 64 bytes, like those 
built by ArrowBuffer.Builder
+                int paddedLength = 
checked((int)BitUtility.RoundUpToMultipleOf64(byteLength));
+                IMemoryOwner<byte> owner = (_allocator ?? 
MemoryAllocator.Default.Value).Allocate(paddedLength);
+                destination = owner.Memory.Span.Slice(0, byteLength);
+                return owner;
+            }
 
-                foreach (ArrayData arrayData in _arrayDataList)
+            private IMemoryOwner<byte> AllocateBitmap(out Span<byte> 
destination)
+            {
+                IMemoryOwner<byte> owner = 
AllocateBuffer(BitUtility.ByteCount(_totalLength), out destination);
+                if (destination.Length > 0)
                 {
-                    if (arrayData.Length == 0)
-                    {
-                        continue;
-                    }
+                    // Bits are copied one range at a time, which leaves the 
bits past the end untouched
+                    destination[destination.Length - 1] = 0;
+                }
+
+                return owner;
+            }
 
-                    ReadOnlySpan<long> span = 
arrayData.Buffers[1].Span.CastTo<long>().Slice(arrayData.Offset, 
arrayData.Length + 1);
-                    var firstOffset = span[0];
+            private static ArrowBuffer BuildBuffer(IMemoryOwner<byte> owner, 
int byteLength)
+            {
+                // Allocators don't have to return zeroed memory, and may 
return more than was requested,
+                // so clear everything past the written bytes explicitly
+                owner.Memory.Span.Slice(byteLength).Clear();
+                return new ArrowBuffer(owner);
+            }
 
-                    foreach (long offset in span.Slice(0, arrayData.Length))
+            private ArrowBuffer ConcatenateLargeOffsetBuffer()
+            {
+                int byteLength = checked((_totalLength + 1) * sizeof(long));
+                IMemoryOwner<byte> owner = AllocateBuffer(byteLength, out 
Span<byte> bytes);
+                try
+                {
+                    Span<long> destination = bytes.CastTo<long>();
+                    int position = 0;
+                    long baseOffset = 0;
+
+                    foreach (ArrayData arrayData in _arrayDataList)
                     {
-                        builder.Append(baseOffset + offset - firstOffset);
+                        if (arrayData.Length == 0)
+                        {
+                            continue;
+                        }
+
+                        ReadOnlySpan<long> span = 
arrayData.Buffers[1].Span.CastTo<long>().Slice(arrayData.Offset, 
arrayData.Length + 1);
+                        var firstOffset = span[0];
+
+                        for (int i = 0; i < arrayData.Length; i++)
+                        {
+                            destination[position++] = baseOffset + span[i] - 
firstOffset;
+                        }
+
+                        baseOffset += span[arrayData.Length] - firstOffset;
                     }
 
-                    baseOffset += span[arrayData.Length] - firstOffset;
+                    destination[position] = baseOffset;
+                }
+                catch
+                {
+                    owner.Dispose();
+                    throw;
                 }
 
-                builder.Append(baseOffset);
-
-                return builder.Build(_allocator);
+                return BuildBuffer(owner, byteLength);
             }
 
             private ArrowBuffer ConcatenateLargeVariableBinaryValueBuffer()
             {
-                var builder = new ArrowBuffer.Builder<byte>();
-
+                int byteLength = 0;
                 foreach (ArrayData arrayData in _arrayDataList)
                 {
                     var offsets = 
arrayData.Buffers[1].Span.CastTo<long>().Slice(arrayData.Offset, 
arrayData.Length + 1);
-                    var firstOffset = checked((int)offsets[0]);
-                    var lastOffset = checked((int)offsets[arrayData.Length]);
-                    
builder.Append(arrayData.Buffers[2].Span.Slice(firstOffset, lastOffset - 
firstOffset));
+                    byteLength = checked(byteLength + 
(int)(offsets[arrayData.Length] - offsets[0]));
                 }
 
-                return builder.Build(_allocator);
+                IMemoryOwner<byte> owner = AllocateBuffer(byteLength, out 
Span<byte> destination);
+                try
+                {
+                    int position = 0;
+                    foreach (ArrayData arrayData in _arrayDataList)
+                    {
+                        var offsets = 
arrayData.Buffers[1].Span.CastTo<long>().Slice(arrayData.Offset, 
arrayData.Length + 1);
+                        var firstOffset = checked((int)offsets[0]);
+                        var lastOffset = 
checked((int)offsets[arrayData.Length]);
+                        int length = lastOffset - firstOffset;
+                        arrayData.Buffers[2].Span.Slice(firstOffset, 
length).CopyTo(destination.Slice(position, length));
+                        position += length;
+                    }
+                }
+                catch
+                {
+                    owner.Dispose();
+                    throw;
+                }
+
+                return BuildBuffer(owner, byteLength);
             }
 
             private ArrowBuffer ConcatenateValidityBuffer()
@@ -1107,199 +1191,272 @@ namespace Apache.Arrow
                     return ArrowBuffer.Empty;
                 }
 
-                var builder = new ArrowBuffer.BitmapBuilder(_totalLength);
-
-                foreach (ArrayData arrayData in _arrayDataList)
+                IMemoryOwner<byte> owner = AllocateBitmap(out Span<byte> 
destination);
+                try
                 {
-                    int length = arrayData.Length;
-                    int offset = arrayData.Offset;
-                    ReadOnlySpan<byte> span = arrayData.Buffers[0].Span;
-
-                    if (length > 0 && span.Length == 0)
+                    int position = 0;
+                    foreach (ArrayData arrayData in _arrayDataList)
                     {
-                        if (arrayData.NullCount == 0)
-                        {
-                            builder.AppendRange(true, length);
-                        }
-                        else if (arrayData.NullCount == length)
+                        int length = arrayData.Length;
+                        int offset = arrayData.Offset;
+                        ReadOnlySpan<byte> span = arrayData.Buffers[0].Span;
+
+                        if (length > 0 && span.Length == 0)
                         {
-                            builder.AppendRange(false, length);
+                            if (arrayData.NullCount == 0)
+                            {
+                                BitUtility.SetBits(destination, position, 
length, true);
+                            }
+                            else if (arrayData.NullCount == length)
+                            {
+                                BitUtility.SetBits(destination, position, 
length, false);
+                            }
+                            else
+                            {
+                                throw new Exception("Array has no validity 
buffer and null count != 0 or length");
+                            }
                         }
                         else
                         {
-                            throw new Exception("Array has no validity buffer 
and null count != 0 or length");
-                        }
-                    }
-                    else if (offset == 0)
-                    {
-                        builder.Append(span, length);
-                    }
-                    else
-                    {
-                        for (int i = 0; i < length; ++i)
-                        {
-                            builder.Append(BitUtility.GetBit(span, offset + 
i));
+                            BitUtility.CopyBits(span, offset, destination, 
position, length);
                         }
+
+                        position += length;
                     }
                 }
+                catch
+                {
+                    owner.Dispose();
+                    throw;
+                }
 
-                return builder.Build(_allocator);
+                return BuildBuffer(owner, destination.Length);
             }
 
             private ArrowBuffer ConcatenateBitmapBuffer(int bufferIndex)
             {
-                var builder = new ArrowBuffer.BitmapBuilder(_totalLength);
-
-                foreach (ArrayData arrayData in _arrayDataList)
+                IMemoryOwner<byte> owner = AllocateBitmap(out Span<byte> 
destination);
+                try
                 {
-                    int length = arrayData.Length;
-                    int offset = arrayData.Offset;
-                    ReadOnlySpan<byte> span = 
arrayData.Buffers[bufferIndex].Span;
-
-                    if (offset == 0)
-                    {
-                        builder.Append(span, length);
-                    }
-                    else
+                    int position = 0;
+                    foreach (ArrayData arrayData in _arrayDataList)
                     {
-                        for (int i = 0; i < length; ++i)
-                        {
-                            builder.Append(BitUtility.GetBit(span, offset + 
i));
-                        }
+                        
BitUtility.CopyBits(arrayData.Buffers[bufferIndex].Span, arrayData.Offset, 
destination, position, arrayData.Length);
+                        position += arrayData.Length;
                     }
                 }
+                catch
+                {
+                    owner.Dispose();
+                    throw;
+                }
 
-                return builder.Build(_allocator);
+                return BuildBuffer(owner, destination.Length);
             }
 
             private ArrowBuffer ConcatenateFixedWidthTypeValueBuffer(int 
bufferIndex, FixedWidthType type)
             {
                 int typeByteWidth = type.BitWidth / 8;
-                var builder = new ArrowBuffer.Builder<byte>(_totalLength * 
typeByteWidth);
-
-                foreach (ArrayData arrayData in _arrayDataList)
+                int byteLength = checked(_totalLength * typeByteWidth);
+                IMemoryOwner<byte> owner = AllocateBuffer(byteLength, out 
Span<byte> destination);
+                try
                 {
-                    int byteLength = arrayData.Length * typeByteWidth;
-                    int byteOffset = arrayData.Offset * typeByteWidth;
+                    int position = 0;
+                    foreach (ArrayData arrayData in _arrayDataList)
+                    {
+                        int length = arrayData.Length * typeByteWidth;
+                        int offset = arrayData.Offset * typeByteWidth;
 
-                    
builder.Append(arrayData.Buffers[bufferIndex].Span.Slice(byteOffset, 
byteLength));
+                        arrayData.Buffers[bufferIndex].Span.Slice(offset, 
length).CopyTo(destination.Slice(position, length));
+                        position += length;
+                    }
+                }
+                catch
+                {
+                    owner.Dispose();
+                    throw;
                 }
 
-                return builder.Build(_allocator);
+                return BuildBuffer(owner, byteLength);
             }
 
             private ArrowBuffer ConcatenateVariableBinaryValueBuffer()
             {
-                var builder = new ArrowBuffer.Builder<byte>();
-
+                int byteLength = 0;
                 foreach (ArrayData arrayData in _arrayDataList)
                 {
                     var offsets = 
arrayData.Buffers[1].Span.CastTo<int>().Slice(arrayData.Offset, 
arrayData.Length + 1);
-                    var firstOffset = offsets[0];
-                    var lastOffset = offsets[arrayData.Length];
-                    
builder.Append(arrayData.Buffers[2].Span.Slice(firstOffset, lastOffset - 
firstOffset));
+                    byteLength = checked(byteLength + 
(offsets[arrayData.Length] - offsets[0]));
                 }
 
-                return builder.Build(_allocator);
+                IMemoryOwner<byte> owner = AllocateBuffer(byteLength, out 
Span<byte> destination);
+                try
+                {
+                    int position = 0;
+                    foreach (ArrayData arrayData in _arrayDataList)
+                    {
+                        var offsets = 
arrayData.Buffers[1].Span.CastTo<int>().Slice(arrayData.Offset, 
arrayData.Length + 1);
+                        var firstOffset = offsets[0];
+                        var lastOffset = offsets[arrayData.Length];
+                        int length = lastOffset - firstOffset;
+                        arrayData.Buffers[2].Span.Slice(firstOffset, 
length).CopyTo(destination.Slice(position, length));
+                        position += length;
+                    }
+                }
+                catch
+                {
+                    owner.Dispose();
+                    throw;
+                }
+
+                return BuildBuffer(owner, byteLength);
             }
 
             private ArrowBuffer ConcatenateOffsetBuffer()
             {
-                var builder = new ArrowBuffer.Builder<int>(_totalLength + 1);
-                int baseOffset = 0;
-
-                foreach (ArrayData arrayData in _arrayDataList)
+                int byteLength = checked((_totalLength + 1) * sizeof(int));
+                IMemoryOwner<byte> owner = AllocateBuffer(byteLength, out 
Span<byte> bytes);
+                try
                 {
-                    if (arrayData.Length == 0)
+                    Span<int> destination = bytes.CastTo<int>();
+                    int position = 0;
+                    int baseOffset = 0;
+
+                    foreach (ArrayData arrayData in _arrayDataList)
                     {
-                        continue;
-                    }
+                        if (arrayData.Length == 0)
+                        {
+                            continue;
+                        }
 
-                    ReadOnlySpan<int> span = 
arrayData.Buffers[1].Span.CastTo<int>().Slice(arrayData.Offset, 
arrayData.Length + 1);
-                    // First offset may be non-zero for sliced arrays
-                    var firstOffset = span[0];
+                        ReadOnlySpan<int> span = 
arrayData.Buffers[1].Span.CastTo<int>().Slice(arrayData.Offset, 
arrayData.Length + 1);
+                        // First offset may be non-zero for sliced arrays
+                        var firstOffset = span[0];
 
-                    foreach (int offset in span.Slice(0, arrayData.Length))
-                    {
-                        builder.Append(baseOffset + offset - firstOffset);
+                        for (int i = 0; i < arrayData.Length; i++)
+                        {
+                            destination[position++] = baseOffset + span[i] - 
firstOffset;
+                        }
+
+                        baseOffset += span[arrayData.Length] - firstOffset;
                     }
 
-                    baseOffset += span[arrayData.Length] - firstOffset;
+                    destination[position] = baseOffset;
+                }
+                catch
+                {
+                    owner.Dispose();
+                    throw;
                 }
 
-                builder.Append(baseOffset);
-
-                return builder.Build(_allocator);
+                return BuildBuffer(owner, byteLength);
             }
 
             private ArrowBuffer ConcatenateViewBuffer(out int 
variadicBufferCount)
             {
-                var builder = new 
ArrowBuffer.Builder<BinaryView>(_totalLength);
+                int byteLength = checked(_totalLength * 
Unsafe.SizeOf<BinaryView>());
+                IMemoryOwner<byte> owner = AllocateBuffer(byteLength, out 
Span<byte> bytes);
                 variadicBufferCount = 0;
-                foreach (ArrayData arrayData in _arrayDataList)
+                try
                 {
-                    if (arrayData.Length == 0)
-                    {
-                        continue;
-                    }
+                    Span<BinaryView> destination = bytes.CastTo<BinaryView>();
+                    int position = 0;
 
-                    ReadOnlySpan<BinaryView> span = 
arrayData.Buffers[1].Span.CastTo<BinaryView>().Slice(arrayData.Offset, 
arrayData.Length);
-                    foreach (BinaryView view in span)
+                    foreach (ArrayData arrayData in _arrayDataList)
                     {
-                        if (view.Length > BinaryView.MaxInlineLength)
+                        if (arrayData.Length == 0)
                         {
-                            
builder.Append(view.AdjustBufferIndex(variadicBufferCount));
+                            continue;
+                        }
+
+                        ReadOnlySpan<BinaryView> span = 
arrayData.Buffers[1].Span.CastTo<BinaryView>().Slice(arrayData.Offset, 
arrayData.Length);
+                        if (variadicBufferCount == 0)
+                        {
+                            // Buffer indices only need adjusting after the 
first data buffers
+                            span.CopyTo(destination.Slice(position));
                         }
                         else
                         {
-                            builder.Append(view);
+                            for (int i = 0; i < span.Length; i++)
+                            {
+                                BinaryView view = span[i];
+                                destination[position + i] = view.Length > 
BinaryView.MaxInlineLength
+                                    ? 
view.AdjustBufferIndex(variadicBufferCount)
+                                    : view;
+                            }
                         }
-                    }
 
-                    variadicBufferCount += (arrayData.Buffers.Length - 2);
+                        position += span.Length;
+                        variadicBufferCount += (arrayData.Buffers.Length - 2);
+                    }
+                }
+                catch
+                {
+                    owner.Dispose();
+                    throw;
                 }
 
-                return builder.Build(_allocator);
+                return BuildBuffer(owner, byteLength);
             }
 
             private ArrowBuffer ConcatenateUnionTypeBuffer()
             {
-                var builder = new ArrowBuffer.Builder<byte>(_totalLength);
-
-                foreach (ArrayData arrayData in _arrayDataList)
+                IMemoryOwner<byte> owner = AllocateBuffer(_totalLength, out 
Span<byte> destination);
+                try
+                {
+                    int position = 0;
+                    foreach (ArrayData arrayData in _arrayDataList)
+                    {
+                        arrayData.Buffers[0].Span.Slice(arrayData.Offset, 
arrayData.Length).CopyTo(destination.Slice(position));
+                        position += arrayData.Length;
+                    }
+                }
+                catch
                 {
-                    
builder.Append(arrayData.Buffers[0].Span.Slice(arrayData.Offset, 
arrayData.Length));
+                    owner.Dispose();
+                    throw;
                 }
 
-                return builder.Build(_allocator);
+                return BuildBuffer(owner, _totalLength);
             }
 
             private ArrowBuffer ConcatenateUnionOffsetBuffer()
             {
-                var builder = new ArrowBuffer.Builder<int>(_totalLength);
-                var typeCount = _arrayDataList.Count > 0 ? 
_arrayDataList[0].Children.Length : 0;
-                var baseOffsets = new int[typeCount];
-
-                foreach (ArrayData arrayData in _arrayDataList)
+                int byteLength = checked(_totalLength * sizeof(int));
+                IMemoryOwner<byte> owner = AllocateBuffer(byteLength, out 
Span<byte> bytes);
+                try
                 {
-                    ReadOnlySpan<byte> typeSpan = 
arrayData.Buffers[0].Span.Slice(arrayData.Offset, arrayData.Length);
-                    ReadOnlySpan<int> offsetSpan = 
arrayData.Buffers[1].Span.CastTo<int>().Slice(arrayData.Offset, 
arrayData.Length);
-                    for (int i = 0; i < arrayData.Length; ++i)
-                    {
-                        var typeId = typeSpan[i];
-                        builder.Append(checked(baseOffsets[typeId] + 
offsetSpan[i]));
-                    }
+                    Span<int> destination = bytes.CastTo<int>();
+                    int position = 0;
+                    var typeCount = _arrayDataList.Count > 0 ? 
_arrayDataList[0].Children.Length : 0;
+                    var baseOffsets = new int[typeCount];
 
-                    for (int i = 0; i < typeCount; ++i)
+                    foreach (ArrayData arrayData in _arrayDataList)
                     {
-                        checked
+                        ReadOnlySpan<byte> typeSpan = 
arrayData.Buffers[0].Span.Slice(arrayData.Offset, arrayData.Length);
+                        ReadOnlySpan<int> offsetSpan = 
arrayData.Buffers[1].Span.CastTo<int>().Slice(arrayData.Offset, 
arrayData.Length);
+                        for (int i = 0; i < arrayData.Length; ++i)
                         {
-                            baseOffsets[i] += arrayData.Children[i].Length;
+                            var typeId = typeSpan[i];
+                            destination[position++] = 
checked(baseOffsets[typeId] + offsetSpan[i]);
+                        }
+
+                        for (int i = 0; i < typeCount; ++i)
+                        {
+                            checked
+                            {
+                                baseOffsets[i] += arrayData.Children[i].Length;
+                            }
                         }
                     }
                 }
+                catch
+                {
+                    owner.Dispose();
+                    throw;
+                }
 
-                return builder.Build(_allocator);
+                return BuildBuffer(owner, byteLength);
             }
 
             private List<ArrayData> SelectChildren(int index)
diff --git a/src/Apache.Arrow/BitUtility.cs b/src/Apache.Arrow/BitUtility.cs
index 3ed6f8c..5d92118 100644
--- a/src/Apache.Arrow/BitUtility.cs
+++ b/src/Apache.Arrow/BitUtility.cs
@@ -123,6 +123,75 @@ namespace Apache.Arrow
             }
         }
 
+        /// <summary>
+        /// Copy a range of bits from one bitmap to another. Bits of the 
destination
+        /// outside of the copied range are left unchanged.
+        /// </summary>
+        /// <param name="source">Bitmap to copy bits from.</param>
+        /// <param name="sourceIndex">Bit index in the source to start copying 
from.</param>
+        /// <param name="destination">Bitmap to copy bits to.</param>
+        /// <param name="destinationIndex">Bit index in the destination to 
start copying to.</param>
+        /// <param name="length">Number of bits to copy.</param>
+        internal static void CopyBits(ReadOnlySpan<byte> source, int 
sourceIndex, Span<byte> destination, int destinationIndex, int length)
+        {
+            // Copy single bits until the destination is byte-aligned
+            while (length > 0 && destinationIndex % 8 != 0)
+            {
+                SetBit(destination, destinationIndex++, GetBit(source, 
sourceIndex++));
+                length--;
+            }
+
+            int fullBytes = length / 8;
+            if (fullBytes > 0)
+            {
+                Span<byte> target = destination.Slice(destinationIndex / 8, 
fullBytes);
+                int shift = sourceIndex % 8;
+                if (shift == 0)
+                {
+                    source.Slice(sourceIndex / 8, fullBytes).CopyTo(target);
+                }
+                else
+                {
+                    // The bits of each destination byte straddle two source 
bytes
+                    CopyShiftedBytes(source.Slice(sourceIndex / 8, fullBytes + 
1), shift, target);
+                }
+
+                sourceIndex += fullBytes * 8;
+                destinationIndex += fullBytes * 8;
+                length -= fullBytes * 8;
+            }
+
+            for (int i = 0; i < length; i++)
+            {
+                SetBit(destination, destinationIndex + i, GetBit(source, 
sourceIndex + i));
+            }
+        }
+
+        private static void CopyShiftedBytes(ReadOnlySpan<byte> source, int 
shift, Span<byte> destination)
+        {
+            Debug.Assert(shift > 0 && shift < 8);
+            Debug.Assert(source.Length == destination.Length + 1);
+
+            int i = 0;
+            if (BitConverter.IsLittleEndian)
+            {
+                // Produce eight destination bytes at a time from nine source 
bytes
+                ref byte sourceRef = ref MemoryMarshal.GetReference(source);
+                ref byte destinationRef = ref 
MemoryMarshal.GetReference(destination);
+                for (; i + 8 <= destination.Length; i += 8)
+                {
+                    ulong low = Unsafe.ReadUnaligned<ulong>(ref Unsafe.Add(ref 
sourceRef, i));
+                    ulong high = Unsafe.Add(ref sourceRef, i + 8);
+                    Unsafe.WriteUnaligned(ref Unsafe.Add(ref destinationRef, 
i), (low >> shift) | (high << (64 - shift)));
+                }
+            }
+
+            for (; i < destination.Length; i++)
+            {
+                destination[i] = (byte)((source[i] >> shift) | (source[i + 1] 
<< (8 - shift)));
+            }
+        }
+
         public static void ToggleBit(Span<byte> data, int index)
         {
             data[index / 8] ^= BitMask[index % 8];
diff --git a/test/Apache.Arrow.Benchmarks/ArrayConcatenatorBenchmark.cs 
b/test/Apache.Arrow.Benchmarks/ArrayConcatenatorBenchmark.cs
new file mode 100644
index 0000000..fe86174
--- /dev/null
+++ b/test/Apache.Arrow.Benchmarks/ArrayConcatenatorBenchmark.cs
@@ -0,0 +1,151 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License. You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+using System.Collections.Generic;
+using Apache.Arrow.Types;
+using BenchmarkDotNet.Attributes;
+
+namespace Apache.Arrow.Benchmarks
+{
+    [MemoryDiagnoser]
+    public class ArrayConcatenatorBenchmark
+    {
+        private const int ChunkCount = 10;
+        private const int ChunkLength = 100_000;
+
+        private List<IArrowArray> _int32Arrays;
+        private List<IArrowArray> _booleanArrays;
+        private List<IArrowArray> _stringArrays;
+        private List<IArrowArray> _stringViewArrays;
+        private List<IArrowArray> _listArrays;
+        private List<IArrowArray> _denseUnionArrays;
+
+        /// <summary>
+        /// When true, every input is sliced at an odd offset so its bitmaps 
don't start on a byte boundary.
+        /// </summary>
+        [Params(false, true)]
+        public bool Sliced { get; set; }
+
+        [GlobalSetup]
+        public void GlobalSetup()
+        {
+            _int32Arrays = new List<IArrowArray>();
+            _booleanArrays = new List<IArrowArray>();
+            _stringArrays = new List<IArrowArray>();
+            _stringViewArrays = new List<IArrowArray>();
+            _listArrays = new List<IArrowArray>();
+            _denseUnionArrays = new List<IArrowArray>();
+
+            var unionType = new UnionType(
+                new[] { new Field("i", Int32Type.Default, true), new 
Field("s", StringType.Default, true) },
+                new[] { 0, 1 },
+                UnionMode.Dense);
+
+            for (int chunk = 0; chunk < ChunkCount; chunk++)
+            {
+                var int32Builder = new Int32Array.Builder();
+                var booleanBuilder = new BooleanArray.Builder();
+                var stringBuilder = new StringArray.Builder();
+                var stringViewBuilder = new StringViewArray.Builder();
+                var listBuilder = new ListArray.Builder(Int32Type.Default);
+                var listValueBuilder = 
(Int32Array.Builder)listBuilder.ValueBuilder;
+                var unionTypeIds = new ArrowBuffer.Builder<byte>();
+                var unionOffsets = new ArrowBuffer.Builder<int>();
+                var unionInts = new Int32Array.Builder();
+                var unionStrings = new StringArray.Builder();
+
+                for (int i = 0; i < ChunkLength; i++)
+                {
+                    bool isNull = i % 7 == 3;
+                    if (isNull)
+                    {
+                        int32Builder.AppendNull();
+                        booleanBuilder.AppendNull();
+                        stringBuilder.AppendNull();
+                        stringViewBuilder.AppendNull();
+                        listBuilder.AppendNull();
+                    }
+                    else
+                    {
+                        int32Builder.Append(i);
+                        booleanBuilder.Append(i % 3 == 0);
+                        string value = i % 2 == 0 ? "short" : "a somewhat 
longer string value";
+                        stringBuilder.Append(value);
+                        stringViewBuilder.Append(value);
+                        listBuilder.Append();
+                        listValueBuilder.Append(i);
+                        listValueBuilder.Append(i + 1);
+                    }
+
+                    if (i % 2 == 0)
+                    {
+                        unionTypeIds.Append(0);
+                        unionOffsets.Append(unionInts.Length);
+                        unionInts.Append(i);
+                    }
+                    else
+                    {
+                        unionTypeIds.Append(1);
+                        unionOffsets.Append(unionStrings.Length);
+                        unionStrings.Append("x");
+                    }
+                }
+
+                var union = new DenseUnionArray(
+                    unionType,
+                    ChunkLength,
+                    new IArrowArray[] { unionInts.Build(), 
unionStrings.Build() },
+                    unionTypeIds.Build(),
+                    unionOffsets.Build());
+
+                Add(_int32Arrays, int32Builder.Build());
+                Add(_booleanArrays, booleanBuilder.Build());
+                Add(_stringArrays, stringBuilder.Build());
+                Add(_stringViewArrays, stringViewBuilder.Build());
+                Add(_listArrays, listBuilder.Build());
+                Add(_denseUnionArrays, union);
+            }
+        }
+
+        private void Add(List<IArrowArray> arrays, IArrowArray array)
+        {
+            arrays.Add(Sliced ? ArrowArrayFactory.Slice(array, 3, array.Length 
- 5) : array);
+        }
+
+        [Benchmark]
+        public int Int32() => Concatenate(_int32Arrays);
+
+        [Benchmark]
+        public int Boolean() => Concatenate(_booleanArrays);
+
+        [Benchmark]
+        public int String() => Concatenate(_stringArrays);
+
+        [Benchmark]
+        public int StringView() => Concatenate(_stringViewArrays);
+
+        [Benchmark]
+        public int List() => Concatenate(_listArrays);
+
+        [Benchmark]
+        public int DenseUnion() => Concatenate(_denseUnionArrays);
+
+        private static int Concatenate(List<IArrowArray> arrays)
+        {
+            using IArrowArray result = 
ArrowArrayConcatenator.Concatenate(arrays);
+            return result.Length;
+        }
+    }
+}
diff --git a/test/Apache.Arrow.Tests/ArrowArrayConcatenatorTests.cs 
b/test/Apache.Arrow.Tests/ArrowArrayConcatenatorTests.cs
index f2b8094..e8f6fb3 100644
--- a/test/Apache.Arrow.Tests/ArrowArrayConcatenatorTests.cs
+++ b/test/Apache.Arrow.Tests/ArrowArrayConcatenatorTests.cs
@@ -45,6 +45,110 @@ namespace Apache.Arrow.Tests
             }
         }
 
+        [Theory]
+        [InlineData(false)]
+        [InlineData(true)]
+        public void TestUsesProvidedAllocator(bool slicedArrays)
+        {
+            // The allocator doesn't zero its memory, so this also checks that 
every byte of the result is written
+            var allocator = new GarbageMemoryAllocator();
+            foreach ((List<IArrowArray> testTargetArrayList, IArrowArray 
expectedArray) in GenerateTestData(slicedArrays))
+            {
+                long allocations = allocator.Statistics.Allocations;
+                using (IArrowArray actualArray = 
ArrowArrayConcatenator.Concatenate(testTargetArrayList, allocator))
+                {
+                    ArrowReaderVerifier.CompareArrays(expectedArray, 
actualArray, strictCompare: !slicedArrays);
+                    Assert.True(allocator.Statistics.Allocations > 
allocations, $"Concatenating {expectedArray.Data.DataType.Name} didn't use the 
allocator");
+                }
+            }
+
+            Assert.Equal(0, allocator.Outstanding);
+        }
+
+        [Fact]
+        public void TestPaddingIsZeroedWithAllocatorThatDoesNotZero()
+        {
+            var allocator = new GarbageMemoryAllocator(extraLength: 40);
+            var first = new 
StringArray.Builder().Append("a").AppendNull().Append("bc").Build();
+            var second = new 
StringArray.Builder().AppendNull().Append("def").Build();
+
+            using var result = 
(StringArray)ArrowArrayConcatenator.Concatenate(new IArrowArray[] { first, 
second }, allocator);
+
+            // The allocator returns more memory than requested, and all of it 
is visible through the buffer
+            Assert.True(result.ValueBuffer.Length >= 64 + 40);
+
+            // Five slots use the low five bits of the validity bitmap; 
everything after that is padding
+            ReadOnlySpan<byte> validity = result.NullBitmapBuffer.Span;
+            Assert.Equal(0b10101, validity[0]);
+            AssertAllZero(validity.Slice(1));
+            AssertAllZero(result.ValueOffsetsBuffer.Span.Slice(6 * 
sizeof(int)));
+            AssertAllZero(result.ValueBuffer.Span.Slice(6));
+        }
+
+        private static void AssertAllZero(ReadOnlySpan<byte> span)
+        {
+            for (int i = 0; i < span.Length; i++)
+            {
+                Assert.True(span[i] == 0, $"Expected padding byte {i} to be 
zero but it was {span[i]}");
+            }
+        }
+
+        [Theory]
+        [InlineData(false)]
+        [InlineData(true)]
+        public void TestConcatenateManyUnalignedBitmapSlices(bool useAllocator)
+        {
+            var random = new Random(1234);
+            var inputs = new List<IArrowArray>();
+            var expected = new List<bool?>();
+            for (int i = 0; i < 40; i++)
+            {
+                int length = random.Next(0, 300);
+                var builder = new BooleanArray.Builder();
+                var values = new List<bool?>();
+                for (int j = 0; j < length; j++)
+                {
+                    bool? value = random.Next(4) == 0 ? null : random.Next(2) 
== 0;
+                    builder.NullableAppend(value);
+                    values.Add(value);
+                }
+
+                BooleanArray array = builder.Build();
+                int offset = length == 0 ? 0 : random.Next(0, length);
+                int sliceLength = random.Next(0, length - offset + 1);
+                inputs.Add(array.Slice(offset, sliceLength));
+                expected.AddRange(values.GetRange(offset, sliceLength));
+            }
+
+            var allocator = useAllocator ? new 
GarbageMemoryAllocator(extraLength: 40) : null;
+            using var result = 
(BooleanArray)ArrowArrayConcatenator.Concatenate(inputs, allocator);
+
+            Assert.Equal(expected.Count, result.Length);
+            Assert.Equal(expected.Count(v => v == null), result.NullCount);
+            for (int i = 0; i < expected.Count; i++)
+            {
+                Assert.Equal(expected[i], result.GetValue(i));
+            }
+        }
+
+        [Theory]
+        [InlineData((long)int.MaxValue + 10, 1L)]
+        [InlineData(2_000_000_000L, 2_000_000_000L)]
+        public void TestLargeBinaryValuesTooLongThrowOverflow(long 
firstLength, long secondLength)
+        {
+            // The offsets claim more data than the value buffers hold, but 
the total length is computed
+            // before anything is copied, so this checks overflow without 
allocating gigabytes.
+            static ArrayData LargeBinaryData(long length)
+            {
+                var offsets = new 
ArrowBuffer.Builder<long>().Append(0).Append(length).Build();
+                return new ArrayData(LargeBinaryType.Default, 1, 0, 0, new[] { 
ArrowBuffer.Empty, offsets, ArrowBuffer.Empty });
+            }
+
+            var allocator = new GarbageMemoryAllocator();
+            Assert.Throws<OverflowException>(() =>
+                ArrayDataConcatenator.Concatenate(new[] { 
LargeBinaryData(firstLength), LargeBinaryData(secondLength) }, allocator));
+        }
+
         [Fact]
         public void TestNullOrEmpty()
         {
diff --git a/test/Apache.Arrow.Tests/BitUtilityTests.cs 
b/test/Apache.Arrow.Tests/BitUtilityTests.cs
index 242f180..b728b7f 100644
--- a/test/Apache.Arrow.Tests/BitUtilityTests.cs
+++ b/test/Apache.Arrow.Tests/BitUtilityTests.cs
@@ -239,6 +239,71 @@ namespace Apache.Arrow.Tests
             }
         }
 
+        public class CopyBits
+        {
+            [Theory]
+            [InlineData(0, 0, 0)]
+            [InlineData(0, 0, 64)]
+            [InlineData(0, 0, 200)]
+            [InlineData(3, 0, 200)]
+            [InlineData(0, 5, 200)]
+            [InlineData(3, 5, 200)]
+            [InlineData(5, 3, 200)]
+            [InlineData(7, 1, 200)]
+            [InlineData(1, 7, 7)]
+            [InlineData(6, 6, 3)]
+            [InlineData(11, 0, 1000)]
+            [InlineData(9, 17, 1000)]
+            public void CopiesBitRange(int sourceIndex, int destinationIndex, 
int length)
+            {
+                var random = new Random(sourceIndex * 1000 + destinationIndex 
* 10 + length);
+                // Make both buffers exactly as long as needed, so that reads 
past the end are caught
+                byte[] source = new byte[BitUtility.ByteCount(sourceIndex + 
length)];
+                byte[] destination = new 
byte[BitUtility.ByteCount(destinationIndex + length) + 2];
+                random.NextBytes(source);
+                random.NextBytes(destination);
+                byte[] expected = (byte[])destination.Clone();
+                for (int i = 0; i < length; i++)
+                {
+                    BitUtility.SetBit(expected, destinationIndex + i, 
BitUtility.GetBit(source, sourceIndex + i));
+                }
+
+                BitUtility.CopyBits(source, sourceIndex, destination, 
destinationIndex, length);
+
+                Assert.Equal(expected, destination);
+            }
+
+            [Fact]
+            public void CopiesEveryCombinationOfOffsetsAndLengths()
+            {
+                var random = new Random(42);
+                byte[] source = new byte[40];
+                random.NextBytes(source);
+                byte[] destination = new byte[40];
+                byte[] expected = new byte[40];
+
+                for (int sourceIndex = 0; sourceIndex < 16; sourceIndex++)
+                {
+                    for (int destinationIndex = 0; destinationIndex < 16; 
destinationIndex++)
+                    {
+                        for (int length = 0; length <= 150; length++)
+                        {
+                            random.NextBytes(destination);
+                            destination.CopyTo(expected, 0);
+                            for (int i = 0; i < length; i++)
+                            {
+                                BitUtility.SetBit(expected, destinationIndex + 
i, BitUtility.GetBit(source, sourceIndex + i));
+                            }
+
+                            BitUtility.CopyBits(source, sourceIndex, 
destination, destinationIndex, length);
+
+                            Assert.Equal(expected, destination);
+                        }
+                    }
+                }
+            }
+        }
+
         public class RoundUpToMultipleOf64
         {
             [Theory]
diff --git a/test/Apache.Arrow.Tests/GarbageMemoryAllocator.cs 
b/test/Apache.Arrow.Tests/GarbageMemoryAllocator.cs
new file mode 100644
index 0000000..f836c0a
--- /dev/null
+++ b/test/Apache.Arrow.Tests/GarbageMemoryAllocator.cs
@@ -0,0 +1,80 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+using System;
+using System.Buffers;
+using System.Threading;
+using Apache.Arrow.Memory;
+
+namespace Apache.Arrow.Tests
+{
+    /// <summary>
+    /// An allocator that fills new memory with a nonzero pattern, to catch 
code that
+    /// assumes allocated memory is zeroed. It can also return more memory 
than was requested,
+    /// as allocators are allowed to, and it counts outstanding allocations.
+    /// </summary>
+    public class GarbageMemoryAllocator : MemoryAllocator
+    {
+        public const byte Garbage = 0xA5;
+
+        private readonly int _extraLength;
+        private int _outstanding;
+        public int Outstanding => _outstanding;
+
+        /// <param name="extraLength">How many bytes more than requested each 
allocation has.</param>
+        public GarbageMemoryAllocator(int extraLength = 0)
+        {
+            _extraLength = extraLength;
+        }
+
+        protected override IMemoryOwner<byte> AllocateInternal(int length, out 
int bytesAllocated)
+        {
+            int extendedLength = length + _extraLength;
+            byte[] array = ArrayPool<byte>.Shared.Rent(extendedLength);
+            array.AsSpan().Fill(Garbage);
+            bytesAllocated = array.Length;
+            Interlocked.Increment(ref _outstanding);
+            return new GarbageMemoryOwner(this, array, extendedLength);
+        }
+
+        private sealed class GarbageMemoryOwner : IMemoryOwner<byte>
+        {
+            private readonly GarbageMemoryAllocator _allocator;
+            private byte[] _array;
+            private readonly int _length;
+
+            public GarbageMemoryOwner(GarbageMemoryAllocator allocator, byte[] 
array, int length)
+            {
+                _allocator = allocator;
+                _array = array;
+                _length = length;
+            }
+
+            public Memory<byte> Memory => _array == null
+                ? throw new ObjectDisposedException(nameof(GarbageMemoryOwner))
+                : _array.AsMemory(0, _length);
+
+            public void Dispose()
+            {
+                byte[] array = Interlocked.Exchange(ref _array, null);
+                if (array != null)
+                {
+                    ArrayPool<byte>.Shared.Return(array);
+                    Interlocked.Decrement(ref _allocator._outstanding);
+                }
+            }
+        }
+    }
+}

Reply via email to