Skip to content

Commit

Permalink
Make PrimitiveArray<T> support IReadOnlyList<T?>
Browse files Browse the repository at this point in the history
  • Loading branch information
voidstar69 committed Nov 11, 2023
1 parent 3c99fbb commit 99715f2
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
22 changes: 21 additions & 1 deletion csharp/src/Apache.Arrow/Arrays/PrimitiveArray.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,13 @@
// limitations under the License.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;

namespace Apache.Arrow
{
public abstract class PrimitiveArray<T> : Array
public abstract class PrimitiveArray<T> : Array, IReadOnlyList<T?>
where T : struct
{
protected PrimitiveArray(ArrayData data)
Expand Down Expand Up @@ -66,5 +67,24 @@ protected PrimitiveArray(ArrayData data)

return list;
}

T? IReadOnlyList<T?>.this[int index] => GetValue(index);
int IReadOnlyCollection<T?>.Count => Length;

IEnumerator<T?> IEnumerable<T?>.GetEnumerator()
{
for (int index = 0; index < Length; index++)
{
yield return IsValid(index) ? Values[index] : null;
}
}

IEnumerator IEnumerable.GetEnumerator()
{
for (int index = 0; index < Length; index++)
{
yield return IsValid(index) ? Values[index] : null;
}
}
}
}
29 changes: 29 additions & 0 deletions csharp/test/Apache.Arrow.Tests/ArrowArrayTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
// limitations under the License.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Numerics;
using Xunit;

Expand Down Expand Up @@ -93,6 +95,33 @@ void TestIsValid(ArrowBuffer valueBuf, ArrowBuffer nullBitmapBuf, int length, in
}
}

[Fact]
public void EnumerateArray()
{
var array = new Int64Array.Builder().Append(1).Append(2).Build();

foreach(long? foo in (IEnumerable<long?>)array)
{
Assert.InRange(foo.Value, 1, 2);
}

foreach (object foo in (IEnumerable)array)
{
Assert.InRange((long)foo, 1, 2);
}
}

[Fact]
public void ArrayAsReadOnlyList()
{
Int64Array array = new Int64Array.Builder().Append(1).Append(2).Build();
var readOnlyList = (IReadOnlyList<long?>)array;

Assert.Equal(array.Length, readOnlyList.Count);
Assert.Equal(readOnlyList[0], 1);
Assert.Equal(readOnlyList[1], 2);
}

#if NET5_0_OR_GREATER
[Fact]
public void SliceArray()
Expand Down

0 comments on commit 99715f2

Please sign in to comment.