diff --git a/csharp/src/Apache.Arrow/Arrays/Array.cs b/csharp/src/Apache.Arrow/Arrays/Array.cs index a453b0807267..1baa54a33823 100644 --- a/csharp/src/Apache.Arrow/Arrays/Array.cs +++ b/csharp/src/Apache.Arrow/Arrays/Array.cs @@ -15,6 +15,8 @@ using System; using System.Runtime.CompilerServices; +using Apache.Arrow.Arrays; +using Apache.Arrow.Builder; namespace Apache.Arrow { @@ -40,6 +42,16 @@ public virtual void Accept(IArrowArrayVisitor visitor) Accept(this, visitor); } + TArray IArrowArray.As() => As(); + TArray As() where TArray : IArrowArray + { + if (this is not TArray casted) + { + throw new InvalidOperationException($"Cannot cast {this} as {typeof(TArray)}"); + } + return casted; + } + public bool IsValid(int index) => NullCount == 0 || NullBitmapBuffer.IsEmpty || BitUtility.GetBit(NullBitmapBuffer.Span, index + Offset); @@ -60,7 +72,7 @@ internal static void Accept(T array, IArrowArrayVisitor visitor) } } - public Array Slice(int offset, int length) + public IArrowArray Slice(int offset, int length) { if (offset > Length) { @@ -68,12 +80,46 @@ public Array Slice(int offset, int length) } length = Math.Min(Data.Length - offset, length); - offset += Data.Offset; + offset += Offset; ArrayData newData = Data.Slice(offset, length); - return ArrowArrayFactory.BuildArray(newData) as Array; + return ArrayBuilderFactory.MakeArray(newData); + } + + /// + /// Get non nullable arrow scalar from array at index + /// + /// value index + /// + public virtual IScalar GetScalar(int index) + { + switch (Data.DataType.TypeId) + { + case Types.ArrowTypeId.Binary: + return As().GetScalar(index); + case Types.ArrowTypeId.FixedSizedBinary: + return As().GetScalar(index); + case Types.ArrowTypeId.String: + return As().GetScalar(index); + case Types.ArrowTypeId.List: + return As().GetScalar(index); + case Types.ArrowTypeId.Struct: + return As().GetScalar(index); + default: + throw new NotSupportedException($"Cannot get scalar from array of type {Data.DataType}"); + } } + /// + /// Get nullable arrow scalar from array at index + /// + /// value index + /// + public INullableScalar GetNullableScalar(int index) + => IsValid(index) ? + new NullableScalar(Data.DataType, true, GetScalar(index)) : + new NullableScalar(Data.DataType, false, null); + public void Dispose() { Dispose(true); @@ -88,4 +134,4 @@ protected virtual void Dispose(bool disposing) } } } -} \ No newline at end of file +} diff --git a/csharp/src/Apache.Arrow/Arrays/ArrayData.cs b/csharp/src/Apache.Arrow/Arrays/ArrayData.cs index fb5aa1b5f23f..b20025b7a43d 100644 --- a/csharp/src/Apache.Arrow/Arrays/ArrayData.cs +++ b/csharp/src/Apache.Arrow/Arrays/ArrayData.cs @@ -26,7 +26,7 @@ public sealed class ArrayData : IDisposable public readonly IArrowType DataType; public readonly int Length; - public readonly int NullCount; + public int NullCount { get; internal set; } public readonly int Offset; public readonly ArrowBuffer[] Buffers; public readonly ArrayData[] Children; @@ -77,7 +77,6 @@ public ArrayData( Children = children; Dictionary = dictionary; } - public void Dispose() { if (Buffers != null) diff --git a/csharp/src/Apache.Arrow/Arrays/BinaryArray.cs b/csharp/src/Apache.Arrow/Arrays/BinaryArray.cs index 4fd8059f6fe7..2cb7302792a6 100644 --- a/csharp/src/Apache.Arrow/Arrays/BinaryArray.cs +++ b/csharp/src/Apache.Arrow/Arrays/BinaryArray.cs @@ -351,8 +351,25 @@ public ReadOnlySpan GetBytes(int index) return ReadOnlySpan.Empty; } - return ValueBuffer.Span.Slice(ValueOffsets[index], GetValueLength(index)); + return GetScalar(index).AsBytes(); } + // Arrow Scalar + public override IScalar GetScalar(int index) => GetScalar(index); + + /// + /// Get non nullable arrow scalar from array at index + /// + /// value index + /// + public BinaryScalar GetScalar(int index, bool valid = true) + { + bool isValid = IsValid(index); + ReadOnlySpan offsets = ValueOffsets; + int start = offsets[index]; + int length = isValid ? offsets[index + 1] - start : 0; + + return new(ValueBuffer.Slice(start, length)); + } } } diff --git a/csharp/src/Apache.Arrow/Arrays/FixedSizeBinaryArray.cs b/csharp/src/Apache.Arrow/Arrays/FixedSizeBinaryArray.cs index 7d3d8754747e..42795b0baa5f 100644 --- a/csharp/src/Apache.Arrow/Arrays/FixedSizeBinaryArray.cs +++ b/csharp/src/Apache.Arrow/Arrays/FixedSizeBinaryArray.cs @@ -22,6 +22,8 @@ namespace Apache.Arrow.Arrays { public class FixedSizeBinaryArray : Array { + public FixedSizeBinaryType DataType => Data.DataType as FixedSizeBinaryType; + public FixedSizeBinaryArray(ArrayData data) : base(data) { @@ -70,6 +72,21 @@ public ReadOnlySpan GetBytes(int index) return ValueBuffer.Span.Slice(index * size, size); } + // Arrow Scalar + public override IScalar GetScalar(int index) => GetScalar(index); + + /// + /// Get non nullable arrow scalar from array at index + /// + /// value index + /// + public FixedSizeBinaryScalar GetScalar(int index, bool valid = true) + { + FixedSizeBinaryType type = DataType; + int size = type.BitWidth * 8; + return new(type, ValueBuffer.Slice(index * size, size)); + } + public abstract class BuilderBase : IArrowArrayBuilder where TArray : IArrowArray where TBuilder : class, IArrowArrayBuilder diff --git a/csharp/src/Apache.Arrow/Arrays/ListArray.cs b/csharp/src/Apache.Arrow/Arrays/ListArray.cs index 97673cb48e6a..78de7220e7b2 100644 --- a/csharp/src/Apache.Arrow/Arrays/ListArray.cs +++ b/csharp/src/Apache.Arrow/Arrays/ListArray.cs @@ -14,6 +14,7 @@ // limitations under the License. using System; +using Apache.Arrow.Builder; using Apache.Arrow.Memory; using Apache.Arrow.Types; @@ -196,5 +197,23 @@ protected override void Dispose(bool disposing) } base.Dispose(disposing); } + + // Arrow Scalar + public override IScalar GetScalar(int index) => GetScalar(index); + + /// + /// Get non nullable arrow scalar from array at index + /// + /// value index + /// + public ListScalar GetScalar(int index, bool valid = true) + { + bool isValid = IsValid(index); + ReadOnlySpan offsets = ValueOffsets; + int start = offsets[index]; + int length = isValid ? offsets[index + 1] - start : 0; + + return new(Data.DataType as ListType, Values.Slice(start, length), isValid); + } } } diff --git a/csharp/src/Apache.Arrow/Arrays/StringArray.cs b/csharp/src/Apache.Arrow/Arrays/StringArray.cs index f008f56fa847..36f1e8e9690e 100644 --- a/csharp/src/Apache.Arrow/Arrays/StringArray.cs +++ b/csharp/src/Apache.Arrow/Arrays/StringArray.cs @@ -13,17 +13,16 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Apache.Arrow.Types; using System; using System.Collections.Generic; -using System.Runtime.InteropServices; using System.Text; +using Apache.Arrow.Types; namespace Apache.Arrow { public class StringArray: BinaryArray { - public static readonly Encoding DefaultEncoding = Encoding.UTF8; + public static readonly Encoding DefaultEncoding = StringType.DefaultEncoding; public new class Builder : BuilderBase { @@ -70,26 +69,30 @@ public StringArray(int length, public override void Accept(IArrowArrayVisitor visitor) => Accept(this, visitor); + /// + /// Converts the underlying byte data to a string using the specified encoding. + /// + /// The encoding used to decode the byte data. + /// String representation of the decoded byte data. public string GetString(int index, Encoding encoding = default) - { - encoding = encoding ?? DefaultEncoding; + => IsValid(index) ? encoding is null ? GetScalar(index).DotNet : GetScalar(index).GetString(encoding) : null; - ReadOnlySpan bytes = GetBytes(index); + // Arrow Scalar + public override IScalar GetScalar(int index) => GetScalar(index); - if (bytes == default) - { - return null; - } - if (bytes.Length == 0) - { - return string.Empty; - } + /// + /// Get non nullable arrow scalar from array at index + /// + /// value index + /// + public new StringScalar GetScalar(int index, bool valid = true) + { + bool isValid = IsValid(index); + ReadOnlySpan offsets = ValueOffsets; + int start = offsets[index]; + int length = isValid ? offsets[index + 1] - start : 0; - unsafe - { - fixed (byte* data = &MemoryMarshal.GetReference(bytes)) - return encoding.GetString(data, bytes.Length); - } + return new(ValueBuffer.Slice(start, length)); } } } diff --git a/csharp/src/Apache.Arrow/Arrays/StructArray.cs b/csharp/src/Apache.Arrow/Arrays/StructArray.cs index 31aea9b41139..a43a8853ac34 100644 --- a/csharp/src/Apache.Arrow/Arrays/StructArray.cs +++ b/csharp/src/Apache.Arrow/Arrays/StructArray.cs @@ -14,6 +14,7 @@ // limitations under the License. using Apache.Arrow.Types; +using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -55,5 +56,23 @@ private IReadOnlyList InitializeFields() } return result; } + + // Arrow Scalar + public override IScalar GetScalar(int index) => GetScalar(index); + + /// + /// Get non nullable arrow scalar from array at index + /// + /// value index + /// + public StructScalar GetScalar(int index, bool valid = true) + { + var values = new IScalar[Fields.Count]; + + for (int i = 0; i < values.Length; i++) + values[i] = Fields[i].GetScalar(index); + + return new(Data.DataType as StructType, values, IsValid(index)); + } } } diff --git a/csharp/src/Apache.Arrow/ArrowBuffer.cs b/csharp/src/Apache.Arrow/ArrowBuffer.cs index f8e675921684..c41f6f560006 100644 --- a/csharp/src/Apache.Arrow/ArrowBuffer.cs +++ b/csharp/src/Apache.Arrow/ArrowBuffer.cs @@ -20,6 +20,8 @@ namespace Apache.Arrow { + // See https://arrow.apache.org/docs/cpp/api/memory.html#_CPPv4N5arrow6BufferE + public readonly partial struct ArrowBuffer : IEquatable, IDisposable { private readonly IMemoryOwner _memoryOwner; @@ -53,13 +55,13 @@ internal ArrowBuffer(IMemoryOwner memoryOwner) public ReadOnlySpan Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => Memory.Span; + get => AsBytes(); } public ArrowBuffer Clone(MemoryAllocator allocator = default) { - return new Builder(Span.Length) - .Append(Span) + return new Builder.BufferBuilder(Span.Length) + .AppendBytes(Span) .Build(allocator); } @@ -72,5 +74,22 @@ public void Dispose() { _memoryOwner?.Dispose(); } + + /// + /// Forms a slice out of the given memory, beginning at 'start', of given length + /// + /// The index at which to begin this slice. + /// The desired length for the slice (exclusive). + /// + /// Thrown when the specified or end index is not in range (<0 or >Length). + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ArrowBuffer Slice(int start, int length) => new(Memory.Slice(start, length)); + + /// + /// Returns a byte span from the memory. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal unsafe ReadOnlySpan AsBytes() => new((byte*)Memory.Pin().Pointer, Length); } } diff --git a/csharp/src/Apache.Arrow/BitUtility.cs b/csharp/src/Apache.Arrow/BitUtility.cs index 19417bbbe45d..09048ba758b2 100644 --- a/csharp/src/Apache.Arrow/BitUtility.cs +++ b/csharp/src/Apache.Arrow/BitUtility.cs @@ -53,6 +53,14 @@ public static void SetBit(Span data, int index) data[index / 8] |= BitMask[index % 8]; } + public static void SetBit(ref byte data, int index, bool value) + { + int mod = index % 8; + data = value + ? (byte)(data | BitMask[mod]) + : (byte)(data & ~BitMask[mod]); + } + public static void SetBit(Span data, int index, bool value) { int idx = index / 8; @@ -62,6 +70,22 @@ public static void SetBit(Span data, int index, bool value) : (byte)(data[idx] & ~BitMask[mod]); } + public static void SetBits(ref byte value, ReadOnlySpan bits) + { + for (int i = 0; i < Math.Min(8, bits.Length); i++) + { + SetBit(ref value, i, bits[i]); + } + } + + public static void SetBits(Span bytes, ReadOnlySpan bits) + { + for (int i = 0; i < bytes.Length; i++) + { + SetBits(ref bytes[i], bits.Slice(i * 8)); + } + } + public static void ToggleBit(Span data, int index) { data[index / 8] ^= BitMask[index % 8]; @@ -200,5 +224,57 @@ internal static int ReadInt32(ReadOnlyMemory value) return Unsafe.ReadUnaligned(ref MemoryMarshal.GetReference(value.Span)); } + + /// + /// Convert byte value into a Span bits + /// + /// byte value to convert to bits + /// Span of bits to recieve the byte value, length must be 8 + public static void ByteToBits(byte value, Span bits) + { + for (int i = 0; i < 8; i++) + { + bits[i] = GetBit(value, i); + } + } + + /// + /// Convert byte values into a Span bits + /// + /// byte values to convert to bits + /// Span of bits to recieve the byte values + public static void BytesToBits(ReadOnlySpan bytes, Span bits) + { + for (int i = 0; i < bytes.Length; i++) + { + ByteToBits(bytes[i], bits.Slice(i * 8, 8)); + } + } + + public static Span BytesToBits(ReadOnlySpan bytes) + { + Span bits = new bool[bytes.Length * 8]; + + BytesToBits(bytes, bits); + + return bits; + } + + /// + /// Get the next multiple of 2 of an integer + /// + /// value to get the next power of 2 + internal static int NextPowerOfTwo(int n) + { + n--; + n |= n >> 1; + n |= n >> 2; + n |= n >> 4; + n |= n >> 8; + n |= n >> 16; + n++; + + return n; + } } } diff --git a/csharp/src/Apache.Arrow/Builder/ArrayBuilder.cs b/csharp/src/Apache.Arrow/Builder/ArrayBuilder.cs new file mode 100644 index 000000000000..854a662d4617 --- /dev/null +++ b/csharp/src/Apache.Arrow/Builder/ArrayBuilder.cs @@ -0,0 +1,503 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using Apache.Arrow.Arrays; +using Apache.Arrow.Memory; +using Apache.Arrow.Types; + +namespace Apache.Arrow.Builder +{ + public abstract class ArrayBuilder : IArrayBuilder + { + // Global Settings + public const int MaxByteStackAllocSize = 257; + public const int MaxIntStackAllocSize = MaxByteStackAllocSize / 4; + public const int MaxBitStackAllocSize = MaxByteStackAllocSize * 8; + public const int DefaultCapacity = 32; + + public IArrowType DataType { get; } + + public int Length { get; protected set; } + + public int NullCount { get; protected set; } + + public int Offset { get; } + + public ITypedBufferBuilder[] Buffers { get; } + public ITypedBufferBuilder ValidityBuffer => Buffers[ValidityBufferIndex]; + private int ValidityBufferIndex => 0; + + public IArrayBuilder[] Children { get; } + + public IArrayBuilder Dictionary { get; } + + protected ArrayBuilder( + IArrowType dataType, + ITypedBufferBuilder[] buffers, + IArrayBuilder[] children = null, + IArrayBuilder dictionary = null + ) + { + DataType = dataType; + + Buffers = buffers; + Children = children; + Dictionary = dictionary; + + Length = 0; + NullCount = 0; + Offset = 0; + } + + TBuilder IArrayBuilder.As() => As(); + TBuilder As() where TBuilder : IArrayBuilder + { + if (this is not TBuilder casted) + { + throw new InvalidOperationException($"Cannot cast {this} as {typeof(TBuilder)}"); + } + return casted; + } + + public virtual Status AppendNull() + { + ValidityBuffer.AppendBit(false); + NullCount++; + Length++; + return Status.OK; + } + + public virtual Status AppendNulls(int count) + { + Reserve(count); + ValidityBuffer.AppendBits(false, count); + NullCount += count; + Length += count; + return Status.OK; + } + + internal virtual Status AppendValid() + { + ValidityBuffer.AppendBit(true); + Length++; + return Status.OK; + } + + internal virtual Status AppendValidity(bool isValid, int count) + { + ValidityBuffer.AppendBits(isValid, count); + Length += count; + if (!isValid) + NullCount += count; + return Status.OK; + } + + internal virtual Status AppendValidity(ReadOnlySpan mask, int nullCount) + { + if (nullCount == 0) + ValidityBuffer.AppendBits(true, mask.Length); + else if (nullCount == mask.Length) + ValidityBuffer.AppendBits(false, nullCount); + else + ValidityBuffer.AppendBits(mask); + + Length += mask.Length; + + NullCount += nullCount; + + return Status.OK; + } + + // Append values from arrow objects + internal bool Validate(IArrowType type0, IArrowType type1) + => type0.TypeId == type1.TypeId; + + internal bool Validate(IArrowType dtype) + { + if (!Validate(DataType, dtype)) + return false; + + switch (dtype.TypeId) + { + // Nested types + case ArrowTypeId.List: + case ArrowTypeId.Struct: + case ArrowTypeId.Map: + var currentFields = (DataType as NestedType).Fields; + var nestedFields = (dtype as NestedType).Fields; + + for (int i = 0; i < currentFields.Count; i++) + if (!Validate(currentFields.ElementAt(i).DataType, nestedFields.ElementAt(i).DataType)) + return false; + return true; + default: + return true; + } + } + + public virtual Status AppendScalar(IScalar value) + { + switch (DataType.TypeId) + { + case ArrowTypeId.String: + case ArrowTypeId.Binary: + return As().AppendScalar(value); + case ArrowTypeId.Boolean: + return As().AppendScalar(value); + case ArrowTypeId.UInt8: + case ArrowTypeId.Int8: + case ArrowTypeId.UInt16: + case ArrowTypeId.Int16: + case ArrowTypeId.UInt32: + case ArrowTypeId.Int32: + case ArrowTypeId.UInt64: + case ArrowTypeId.Int64: +#if NET5_0_OR_GREATER + case ArrowTypeId.HalfFloat: +#endif + case ArrowTypeId.Float: + case ArrowTypeId.Double: + case ArrowTypeId.Decimal128: + case ArrowTypeId.Decimal256: + return As().AppendScalar(value); + case ArrowTypeId.Struct: + return As().AppendScalar(value); + case ArrowTypeId.List: + return As().AppendScalar(value); + case ArrowTypeId.Null: + return AppendNull(); + default: + throw new ArgumentException($"Cannot append {value} in builder with data type {DataType}"); + } + } + + public virtual Status AppendArray(IArrowArray array) => AppendArray(array.Data); + + public async Task AppendArrayAsync(IArrowArray data) => await AppendArrayAsync(data); + + private Status AppendValidity(ArrayData data) + { + // Handle validity + var dataValidity = data.Buffers[ValidityBufferIndex]; + int length = data.Length; + + // Check if need to recalculate null count + if (data.NullCount < 0) + { + Span bits = length < MaxBitStackAllocSize ? stackalloc bool[length] : new bool[length]; + int nullCount = 0; + + // Need recalculate nulls + for (int i = 0; i < data.Length; i++) + { + bool isValid = BitUtility.GetBit(dataValidity.Span, data.Offset + i); + + if (isValid) + bits[i] = isValid; + else + nullCount++; + } + + AppendValidity(bits, nullCount); + // Update it since we calculated it + data.NullCount = nullCount; + } + else + { + int nullCount = data.NullCount; + + if (nullCount == 0) + AppendValidity(true, data.Length); + else if (nullCount == data.Length) + AppendValidity(false, data.Length); + else if (data.Offset == 0) + { + // Should use AppendValidity, but optimized for bulk byte copy + // Bulk copy full bytes + int end = (data.Length * ValidityBuffer.ValueBitSize) / 8; + ValidityBuffer.AppendBytes(dataValidity.Span.Slice(0, end)); + + // Copy remaining bits + Span bits = BitUtility.BytesToBits(dataValidity.Span.Slice(end)).Slice(0, data.Length - end * 8); + ValidityBuffer.AppendBits(bits); + + NullCount += nullCount; + Length += data.Length; + } + else + { + Span bits = length < MaxBitStackAllocSize ? stackalloc bool[length] : new bool[length]; + + for (int i = 0; i < data.Length; i++) + bits[i] = BitUtility.GetBit(dataValidity.Span, data.Offset + i); + + AppendValidity(bits, nullCount); + } + } + return Status.OK; + } + + internal abstract Status AppendPrimitiveValueOffset(ArrayData data); + + public Status AppendArray(ArrayData data) + { + // TODO: Make better / recursive fields data type check + if (!Validate(data.DataType)) + throw new ArgumentException($"Cannot append Arrow.Array<{data.DataType}> in {this}<{DataType}>"); + + // Add Length and reserve + Reserve(data.Length); + + AppendValidity(data); + AppendPrimitiveValueOffset(data); + + // Append children data + if (Children != null && data.Children != null) + { + for (int i = 0; i < Children.Length; i++) + { + Children[i].AppendArray(data.Children[i]); + } + } + + if (Dictionary != null && data.Dictionary != null) + { + Dictionary.AppendArray(data.Dictionary); + } + + return Status.OK; + } + + public async Task AppendArrayAsync(ArrayData data) + { + // TODO: Make better / recursive fields data type check + if (!Validate(data.DataType)) + throw new ArgumentException($"Cannot append Arrow.Array<{data.DataType}> in {this}<{DataType}>"); + + // Add Length and reserve + Reserve(data.Length); + + AppendValidity(data); + AppendPrimitiveValueOffset(data); + + // Append children data + if (Children != null && data.Children != null) + { + Task[] childTasks = new Task[Children.Length]; + for (int i = 0; i < Children.Length; i++) + { + int index = i; // Create a local copy of the loop variable + childTasks[index] = Children[index].AppendArrayAsync(data.Children[index]); + } + await Task.WhenAll(childTasks); + } + + if (Dictionary != null && data.Dictionary != null) + { + await Dictionary.AppendArrayAsync(data.Dictionary); + } + + return Status.OK; + } + + public ArrayData FinishInternal(MemoryAllocator allocator = null) + => new ArrayData( + DataType, Length, NullCount, Offset, + Buffers.Select(b => b.Build(allocator)).ToArray(), + Children?.Select(c => c.FinishInternal(allocator)).ToArray(), + Dictionary?.FinishInternal() + ); + + public async Task FinishInternalAsync(MemoryAllocator allocator = null) + => new ArrayData( + DataType, Length, NullCount, Offset, + await Task.WhenAll(Buffers.Select(b => b.BuildAsync(allocator))), + Children != null ? await Task.WhenAll(Children.Select(c => c.FinishInternalAsync(allocator))) : null, + Dictionary != null ? await Dictionary.FinishInternalAsync() : null + ); + + public virtual IArrowArray Build(MemoryAllocator allocator = null) + => ArrayBuilderFactory.MakeArray(FinishInternal(allocator)); + + public virtual async Task BuildAsync(MemoryAllocator allocator = null) + => ArrayBuilderFactory.MakeArray(await FinishInternalAsync(allocator)); + + // Memory management + public Status Reserve(int additionnalCapacity) + { + foreach (ITypedBufferBuilder buffer in Buffers) + buffer.Reserve(additionnalCapacity); + + if (Children != null) + foreach (IArrayBuilder builder in Children) + builder.Reserve(additionnalCapacity); + + if (Dictionary != null) + Dictionary.Reserve(additionnalCapacity); + + return Status.OK; + } + + public Status Resize(int capacity) + { + foreach (ITypedBufferBuilder buffer in Buffers) + buffer.Resize(capacity); + + if (Children != null) + foreach (IArrayBuilder builder in Children) + builder.Resize(capacity); + + if (Dictionary != null) + Dictionary.Resize(capacity); + + return Status.OK; + } + + public void Clear() + { + foreach (ITypedBufferBuilder buffer in Buffers) + buffer.Clear(); + + if (Children != null) + foreach (IArrayBuilder builder in Children) + builder.Clear(); + + if (Dictionary != null) + Dictionary.Clear(); + } + } + + public static class ArrayBuilderFactory + { + public static IArrayBuilder MakeBuilder(IArrowType dtype, int capacity = ArrayBuilder.DefaultCapacity) + { + switch (dtype.TypeId) + { + case ArrowTypeId.Boolean: + return new BooleanArrayBuilder(dtype as BooleanType, capacity); + case ArrowTypeId.UInt8: + return new FixedBinaryArrayBuilder(dtype as FixedWidthType, capacity); + case ArrowTypeId.Int8: + return new FixedBinaryArrayBuilder(dtype as FixedWidthType, capacity); + case ArrowTypeId.UInt16: + return new FixedBinaryArrayBuilder(dtype as FixedWidthType, capacity); + case ArrowTypeId.Int16: + return new FixedBinaryArrayBuilder(dtype as FixedWidthType, capacity); + case ArrowTypeId.UInt32: + return new FixedBinaryArrayBuilder(dtype as FixedWidthType, capacity); + case ArrowTypeId.Int32: + return new FixedBinaryArrayBuilder(dtype as FixedWidthType, capacity); + case ArrowTypeId.UInt64: + return new FixedBinaryArrayBuilder(dtype as FixedWidthType, capacity); + case ArrowTypeId.Int64: + return new FixedBinaryArrayBuilder(dtype as FixedWidthType, capacity); +#if NET5_0_OR_GREATER + case ArrowTypeId.HalfFloat: + return new FixedBinaryArrayBuilder(dtype as FixedWidthType, capacity); +#endif + case ArrowTypeId.Float: + return new FixedBinaryArrayBuilder(dtype as FixedWidthType, capacity); + case ArrowTypeId.Double: + return new FixedBinaryArrayBuilder(dtype as FixedWidthType, capacity); + case ArrowTypeId.FixedSizedBinary: + return new FixedBinaryArrayBuilder(dtype as FixedWidthType, capacity); + case ArrowTypeId.String: + return new StringArrayBuilder(dtype, capacity); + case ArrowTypeId.Binary: + return new BinaryArrayBuilder(dtype, capacity); + case ArrowTypeId.Struct: + return new StructArrayBuilder(dtype as StructType, capacity); + case ArrowTypeId.List: + return new ListArrayBuilder(dtype as ListType, capacity); + case ArrowTypeId.Timestamp: + return new TimestampArrayBuilder(dtype as TimestampType, capacity); + case ArrowTypeId.Time32: + return new Time32ArrayBuilder(dtype as TimeType, capacity); + case ArrowTypeId.Time64: + return new Time64ArrayBuilder(dtype as TimeType, capacity); + case ArrowTypeId.Decimal128: + case ArrowTypeId.Decimal256: + return new FixedBinaryArrayBuilder(dtype as FixedWidthType, capacity); + case ArrowTypeId.Date32: + return new Date32ArrayBuilder(dtype as DateType, capacity); + case ArrowTypeId.Date64: + return new Date64ArrayBuilder(dtype as DateType, capacity); + case ArrowTypeId.Interval: + case ArrowTypeId.Union: + case ArrowTypeId.Dictionary: + case ArrowTypeId.Map: + case ArrowTypeId.Null: + default: + throw new ArgumentException($"Cannot create arrow array builder from {dtype.TypeId}"); + } + } + + public static IArrowArray MakeArray(ArrayData data) + { + switch (data.DataType.TypeId) + { + case ArrowTypeId.Boolean: + return new BooleanArray(data); + case ArrowTypeId.UInt8: + return new UInt8Array(data); + case ArrowTypeId.Int8: + return new Int8Array(data); + case ArrowTypeId.UInt16: + return new UInt16Array(data); + case ArrowTypeId.Int16: + return new Int16Array(data); + case ArrowTypeId.UInt32: + return new UInt32Array(data); + case ArrowTypeId.Int32: + return new Int32Array(data); + case ArrowTypeId.UInt64: + return new UInt64Array(data); + case ArrowTypeId.Int64: + return new Int64Array(data); + case ArrowTypeId.Float: + return new FloatArray(data); + case ArrowTypeId.Double: + return new DoubleArray(data); + case ArrowTypeId.String: + return new StringArray(data); + case ArrowTypeId.FixedSizedBinary: + return new FixedSizeBinaryArray(data); + case ArrowTypeId.Binary: + return new BinaryArray(data); + case ArrowTypeId.Timestamp: + return new TimestampArray(data); + case ArrowTypeId.List: + return new ListArray(data); + case ArrowTypeId.Struct: + return new StructArray(data); + case ArrowTypeId.Union: + return new UnionArray(data); + case ArrowTypeId.Date64: + return new Date64Array(data); + case ArrowTypeId.Date32: + return new Date32Array(data); + case ArrowTypeId.Time32: + return new Time32Array(data); + case ArrowTypeId.Time64: + return new Time64Array(data); + case ArrowTypeId.Decimal128: + return new Decimal128Array(data); + case ArrowTypeId.Decimal256: + return new Decimal256Array(data); + case ArrowTypeId.Dictionary: + return new DictionaryArray(data); + case ArrowTypeId.HalfFloat: +#if NET5_0_OR_GREATER + return new HalfFloatArray(data); +#else + throw new NotSupportedException("Half-float arrays are not supported by this target framework."); +#endif + case ArrowTypeId.Interval: + case ArrowTypeId.Map: + case ArrowTypeId.Null: + default: + throw new NotSupportedException($"An ArrowArray cannot be built for type {data.DataType.TypeId}."); + } + } + } +} diff --git a/csharp/src/Apache.Arrow/Builder/BinaryArrayBuilder.cs b/csharp/src/Apache.Arrow/Builder/BinaryArrayBuilder.cs new file mode 100644 index 000000000000..fc08a82c5e8c --- /dev/null +++ b/csharp/src/Apache.Arrow/Builder/BinaryArrayBuilder.cs @@ -0,0 +1,137 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Apache.Arrow.Memory; +using Apache.Arrow.Types; + +namespace Apache.Arrow.Builder +{ + public class BinaryArrayBuilder : VariableBinaryArrayBuilder + { + public BinaryArrayBuilder(int capacity = ArrayBuilder.DefaultCapacity) + : base(BinaryType.Default, capacity) + { + } + + internal BinaryArrayBuilder(IArrowType dtype, int capacity = ArrayBuilder.DefaultCapacity) + : base(dtype, capacity) + { + } + public override IArrowArray Build(MemoryAllocator allocator = default) => Build(allocator); + + public BinaryArray Build(MemoryAllocator allocator = default, bool bin = true) + => new BinaryArray(FinishInternal(allocator)); + } + + public class StringArrayBuilder : BinaryArrayBuilder + { + public StringArrayBuilder(int capacity = ArrayBuilder.DefaultCapacity) + : this(StringType.Default, capacity) + { + } + + internal StringArrayBuilder(IArrowType dtype, int capacity = ArrayBuilder.DefaultCapacity) + : base(dtype, capacity) + { + } + + /// + /// Append string value to builder encoded in UTF8 + /// + /// string value + public virtual Status AppendValue(string value) => AppendValue(value, StringType.DefaultEncoding); + + /// + /// Append string value to builder encoded + /// + /// string value + /// to convert string to bytes + public virtual Status AppendValue(string value, Encoding encoding) + { + if (value is null) + return AppendNull(); + else if (value.Length == 0) + return AppendValue(ReadOnlySpan.Empty); + + int byteLength = encoding.GetByteCount(value); + + ReadOnlySpan chars = value.AsSpan(); + Span encoded = byteLength < MaxByteStackAllocSize ? + stackalloc byte[byteLength] : new byte[byteLength]; + + unsafe + { + fixed (byte* pBytes = encoded) + fixed (char* pChars = chars) + { + encoding.GetBytes(pChars, chars.Length, pBytes, encoded.Length); + return AppendValue(encoded); + } + } + } + + /// + /// Append string value to builder repeated x times. + /// + /// string value + /// repeat x times + public virtual Status AppendValues(string value, int count) + => AppendValues(value, count, StringType.DefaultEncoding); + + /// + /// Append string value to builder repeated x times encoded + /// + /// string value + /// repeat x times + /// to convert string to bytes + public virtual Status AppendValues(string value, int count, Encoding encoding) + { + if (value is null) + return AppendNulls(count); + else if (value.Length == 0) + return AppendValues(ReadOnlySpan.Empty, count); + + int byteLength = encoding.GetByteCount(value); + + ReadOnlySpan chars = value.AsSpan(); + Span encoded = byteLength < MaxByteStackAllocSize ? + stackalloc byte[byteLength] : new byte[byteLength]; + + unsafe + { + fixed (byte* pBytes = encoded) + fixed (char* pChars = chars) + { + encoding.GetBytes(pChars, chars.Length, pBytes, encoded.Length); + return AppendValues(encoded, count); + } + } + } + + public virtual Status AppendValues(ICollection values) + => AppendValues(values, StringType.DefaultEncoding); + + public virtual Status AppendValues(ICollection values, Encoding encoding) + { + int length = values.Count; + int currentOffset = CurrentOffset; + + Span validity = length < MaxBitStackAllocSize ? stackalloc bool[length] : new bool[length]; + Span offsets = length < MaxIntStackAllocSize ? stackalloc int[length] : new int[length]; + + // Append values + ValuesBuffer.AppendBytes(values, validity, offsets, currentOffset, encoding, out int nullCount); + + // Append offsets + CurrentOffset = currentOffset; + OffsetsBuffer.AppendValues(offsets); + + return AppendValidity(validity, nullCount); + } + + public override IArrowArray Build(MemoryAllocator allocator = default) => Build(allocator); + + public StringArray Build(MemoryAllocator allocator = default, bool bin = false, bool str = true) + => new StringArray(FinishInternal(allocator)); + } +} diff --git a/csharp/src/Apache.Arrow/Builder/BufferBuilder.cs b/csharp/src/Apache.Arrow/Builder/BufferBuilder.cs new file mode 100644 index 000000000000..189075b4fb86 --- /dev/null +++ b/csharp/src/Apache.Arrow/Builder/BufferBuilder.cs @@ -0,0 +1,652 @@ +using System; +using System.Buffers; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using Apache.Arrow.Memory; +using Apache.Arrow.Reflection; +using Apache.Arrow.Types; + +namespace Apache.Arrow.Builder +{ + public class BufferBuilder : IBufferBuilder + { + private const int DefaultCapacity = 64; + public int ByteLength { get; internal set; } + public int BitOffset { get; private set; } + + public Memory Memory { get; private set; } + + /// + /// Creates an instance of the class. + /// + /// Number of bytes of initial capacity to reserve. + public BufferBuilder(int capacity = DefaultCapacity) + { + Memory = new byte[capacity]; + + ByteLength = 0; + BitOffset = 0; + } + + public IBufferBuilder AppendBit(bool bit) + { + UncheckedAppendBit(bit); + + if (BitOffset == 8) + { + BitOffset = 0; + ByteLength++; + // Ensure current and another byte for next append + EnsureBytes(ByteLength + 1); + } + return this; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void UncheckedAppendBit(bool bit) + { + BitUtility.SetBit(ref Memory.Span[ByteLength], BitOffset, bit); + BitOffset++; + } + + public IBufferBuilder AppendBits(ReadOnlySpan bits) + { + if (BitOffset > 0) + { + int available = 8 - BitOffset; + + if (bits.Length < available) + { + foreach (bool bit in bits) + UncheckedAppendBit(bit); + + bits = ReadOnlySpan.Empty; + } + else + { + foreach (bool bit in bits.Slice(0, available)) + UncheckedAppendBit(bit); + + BitOffset = 0; + ByteLength++; + + bits = bits.Slice(available); + } + } + + if (bits.Length > 0) + { + int byteEnd = bits.Length / 8; + int bitEnd = byteEnd * 8; + + if (byteEnd > 0) + { + var span = Memory.Span; + + // Ensure byte length + EnsureAdditionalBytes(byteEnd); + + // Raw Span copy to memory + BitUtility.SetBits(span.Slice(ByteLength, byteEnd), bits.Slice(0, bitEnd)); + + ByteLength += byteEnd; + + bits = bits.Slice(bitEnd); + } + + if (bits.Length > 0) + { + // Fill byte buffer with last unfilled + foreach (bool bit in bits) + UncheckedAppendBit(bit); + } + } + + return this; + } + + public IBufferBuilder AppendBits(bool value, int count) + { + // by default bit values are false + if (!value) + return AppendEmptyBits(count); + + var span = Memory.Span; + + if (BitOffset == 0) + { + int wholeBytes = count / 8; + + if (wholeBytes > 0) + { + EnsureAdditionalBytes(wholeBytes + 1); + + var fill = (byte)0xFF; + span.Slice(ByteLength, wholeBytes).Fill(fill); + ByteLength += wholeBytes; + } + + // Write remaining bits + int trailing = count - (wholeBytes * 8); + for (int i = 0; i < trailing; i++) + UncheckedAppendBit(value); + } + else + { + int available = 8 - BitOffset; + + if (count < available) + { + for (int i = 0; i < count; i++) + UncheckedAppendBit(value); + return this; + } + + // Write all remaining bits + for (int i = 0; i < available; i++) + UncheckedAppendBit(value); + + // Commit to memory + BitOffset = 0; + ByteLength++; + // Ensure current and another byte for next append + EnsureBytes(ByteLength + 1); + + int trailing = count - available; + AppendBits(value, trailing); + } + + return this; + } + + // Write false bool values = AppendBits(false, count) + public IBufferBuilder AppendEmptyBits(int count) + { + if (BitOffset == 0) + { + int wholeBytes = count / 8; + + if (wholeBytes > 0) + { + EnsureAdditionalBytes(wholeBytes + 1); + ByteLength += wholeBytes; + } + + // Write remaining bits + BitOffset = count - (wholeBytes * 8); + } + else + { + int available = 8 - BitOffset; + + if (count < available) + { + BitOffset += count; + return this; + } + + // Commit to memory + BitOffset = 0; + ByteLength++; + // Ensure current and another byte for next append + EnsureBytes(ByteLength + 1); + + int trailing = count - available; + AppendEmptyBits(trailing); + } + + return this; + } + + public IBufferBuilder AppendByte(byte value) + { + if (BitOffset > 0) + { + // Convert byte to bits + Span bits = stackalloc bool[8]; + BitUtility.ByteToBits(value, bits); + + AppendBits(bits); + } + else + { + EnsureAdditionalBytes(1); + // Raw add to memory + Memory.Span[ByteLength] = value; + ByteLength++; + } + + return this; + } + + public IBufferBuilder AppendFixedSizeBytes( + ICollection bytes, int fixedSize, Span validity, out int nullCount + ) + { + int i = 0; + int offset = ByteLength; + int _nullCount = 0; + EnsureAdditionalBytes(bytes.Count * fixedSize); + + var span = Memory.Span; + + foreach (byte[] value in bytes) + { + if (value is null) + _nullCount++; + else + { + // Copy to memory + if (value.Length > fixedSize) + value.AsSpan().Slice(0, fixedSize).CopyTo(span.Slice(offset, fixedSize)); + else + value.CopyTo(span.Slice(offset, fixedSize)); + validity[i] = true; + } + offset += fixedSize; + i++; + } + + ByteLength = offset; + nullCount = _nullCount; + return this; + } + + public IBufferBuilder AppendBytes(ReadOnlySpan bytes) + { + if (bytes.Length == 0) + return this; + + if (BitOffset == 0) + { + EnsureAdditionalBytes(bytes.Length); + // Raw Span copy to memory + bytes.CopyTo(Memory.Span.Slice(ByteLength, bytes.Length)); + ByteLength += bytes.Length; + } + else + { + // Convert Bytes to Bits streamed in batchsize = 128 bytes + int offset = 0; + while (offset < bytes.Length) + { + int remainingBytes = bytes.Length - offset; + int bufferLength = Math.Min(128, remainingBytes); + + // Append batch bits + var bits = BitUtility.BytesToBits(bytes.Slice(offset, bufferLength)); + AppendBits(bits); + offset += bufferLength; + } + } + + return this; + } + + public IBufferBuilder AppendBytes( + ICollection values, + Span validity, Span offsets, + int baseOffset, + out int nullCount + ) + { + if (BitOffset != 0) + throw new NotSupportedException("Cannot append collection of byte[] while current buffer BitOffset != 0"); + + int newBytes = 0; + + foreach (var bytes in values) + if (bytes is not null) + newBytes += bytes.Length; + + EnsureAdditionalBytes(newBytes); + int _nullCount = 0; + int offset = ByteLength; + int i = 0; + var span = Memory.Span; + + foreach (var bytes in values) + { + if (bytes is null) + { + _nullCount++; + } + else + { + int byteLength = bytes.Length; + + if (bytes.Length > 0) + { + // Span copy to memory + bytes.CopyTo(span.Slice(offset, byteLength)); + offset += byteLength; + baseOffset += byteLength; + } + validity[i] = true; + } + offsets[i] = baseOffset; + i++; + } + + ByteLength += offset; + nullCount = _nullCount; + return this; + } + + public IBufferBuilder AppendBytes( + ICollection values, + Span validity, Span offsets, + int baseOffset, + Encoding encoding, + out int nullCount + ) + { + if (BitOffset != 0) + throw new NotSupportedException("Cannot append collection of byte[] while current buffer BitOffset != 0"); + + int newBytes = 0; + + foreach (var str in values) + if (str is not null) + newBytes += encoding.GetByteCount(str); + + EnsureAdditionalBytes(newBytes); + int _nullCount = 0; + int offset = ByteLength; + int i = 0; + var span = Memory.Span; + + foreach (var str in values) + { + if (str is null) + { + _nullCount++; + } + else + { + if (str.Length > 0) + { + int byteLength = encoding.GetByteCount(str); + + ReadOnlySpan chars = str.AsSpan(); + Span encoded = byteLength < ArrayBuilder.MaxByteStackAllocSize ? + stackalloc byte[byteLength] : new byte[byteLength]; + + // Append encoded + unsafe + { + fixed (byte* pBytes = encoded) + fixed (char* pChars = chars) + { + encoding.GetBytes(pChars, chars.Length, pBytes, byteLength); + encoded.CopyTo(span.Slice(offset, byteLength)); + } + } + offset += byteLength; + baseOffset += byteLength; + } + validity[i] = true; + } + offsets[i] = baseOffset; + i++; + } + + ByteLength += offset; + nullCount = _nullCount; + return this; + } + + public IBufferBuilder AppendEmptyBytes(int count) + { + if (BitOffset == 0) + { + ByteLength += count; + return this; + } + return AppendEmptyBits(count * 8); + } + + public IBufferBuilder AppendBytes(ReadOnlySpan value, int count) + { + if (value.Length == 0) + return this; + + if (BitOffset != 0) + throw new NotSupportedException("Cannot append repeated bytes while current buffer BitOffset != 0"); + + int total = count * value.Length; + EnsureAdditionalBytes(total); + int offset = ByteLength; + var span = Memory.Span; + + for (int i = 0; i < count; i++) + { + value.CopyTo(span.Slice(offset, value.Length)); + offset += value.Length; + } + + ByteLength += total; + return this; + } + + internal IBufferBuilder ReserveAdditionalBytes(int numBytes) + { + EnsureAdditionalBytes(numBytes); + return this; + } + + internal IBufferBuilder ResizeBytes(int numBytes) + { + EnsureBytes(numBytes); + ByteLength = numBytes; + BitOffset = 0; + return this; + } + + public IBufferBuilder Clear() + { + Memory.Span.Fill(default); + ByteLength = 0; + BitOffset = 0; + return this; + } + + public ArrowBuffer Build(MemoryAllocator allocator = default) => Build(64, allocator); + + public async Task BuildAsync(MemoryAllocator allocator = default) + => await Task.FromResult(Build(allocator)); + + public ArrowBuffer Build(int byteSize, MemoryAllocator allocator = default) + { + var byteLength = BitOffset > 0 ? ByteLength + 1 : ByteLength; + + int bufferLength = checked((int)BitUtility.RoundUpToMultiplePowerOfTwo(byteLength, byteSize)); + + MemoryAllocator memoryAllocator = allocator ?? MemoryAllocator.Default.Value; + IMemoryOwner memoryOwner = memoryAllocator.Allocate(bufferLength); + Memory.Slice(0, byteLength).CopyTo(memoryOwner.Memory); + + return new ArrowBuffer(memoryOwner); + } + + internal void EnsureAdditionalBytes(int numBytes) => EnsureBytes(checked(ByteLength + numBytes)); + + internal void EnsureBytes(int numBytes) + { + if (numBytes > Memory.Length) + { + int twice = checked(Memory.Length * 2); + + Reallocate(twice < numBytes ? BitUtility.NextPowerOfTwo(numBytes) : twice); + } + } + + private void Reallocate(int numBytes) + { + var memory = new Memory(new byte[numBytes]); + Memory.CopyTo(memory); + + Memory = memory; + } + } + + public class TypedBufferBuilder : BufferBuilder, ITypedBufferBuilder + { + public bool IsVariableLength { get; } + public int ValueBitSize { get; } + public int ValueByteSize { get; } + public int ValueLength => (ByteLength * 8 + BitOffset) / ValueBitSize; + private int MinimumBitSize => IsVariableLength ? 8 : ValueBitSize; + + public TypedBufferBuilder(int valueBitSize, int capacity = ArrayBuilder.DefaultCapacity) : base(capacity * (valueBitSize + 7) / 8) + { + IsVariableLength = valueBitSize < 0; + ValueBitSize = valueBitSize; + ValueByteSize = valueBitSize / 8; + } + + public ITypedBufferBuilder Ensure(int capacity) + { + EnsureBytes((capacity * MinimumBitSize + 7) / 8); + return this; + } + + public ITypedBufferBuilder Reserve(int additionnalCapacity) + { + ReserveAdditionalBytes((additionnalCapacity * MinimumBitSize + 7) / 8); + return this; + } + + public ITypedBufferBuilder Resize(int capacity) + { + ResizeBytes((capacity * MinimumBitSize + 7) / 8); + return this; + } + } + + public class TypedBufferBuilder : TypedBufferBuilder, ITypedBufferBuilder where T : struct + { + public TypedBufferBuilder(int capacity = ArrayBuilder.DefaultCapacity) : this((TypeReflection.ArrowType as FixedWidthType).BitWidth, capacity) + { + } + + public TypedBufferBuilder(int bitWidth, int capacity = ArrayBuilder.DefaultCapacity) : base(bitWidth, capacity) + { + } + + public ITypedBufferBuilder AppendValue(T value) + => AppendValues(TypeReflection.CreateReadOnlySpan(ref value)); + + public ITypedBufferBuilder AppendValue(bool value) + { + AppendBit(value); + return this; + } + + public ITypedBufferBuilder AppendValues(ReadOnlySpan values) + { + ReadOnlySpan bytes = MemoryMarshal.AsBytes(values); + AppendBytes(bytes); + return this; + } + + public ITypedBufferBuilder AppendValues(ReadOnlySpan values) + { + AppendBits(values); + return this; + } + + public ITypedBufferBuilder AppendValues(T value, int count) + { + AppendBytes(TypeReflection.AsBytes(ref value), count); + return this; + } + + public ITypedBufferBuilder AppendValues(bool value, int count) + { + AppendBits(value, count); + return this; + } + + public ITypedBufferBuilder AppendValues( + ICollection values, Span validity, out int nullCount + ) + { + int i = 0; + int offset = 0; + int fixedSize = ValueByteSize; + int _nullCount = 0; + EnsureAdditionalBytes(values.Count * fixedSize); + + var span = Memory.Span; + + foreach (T? value in values) + { + if (value.HasValue) + { + T real = value.Value; + TypeReflection.AsBytes(ref real).CopyTo(span.Slice(offset, fixedSize)); + validity[i] = true; + } + else + _nullCount++; + offset += fixedSize; + i++; + } + + ByteLength += offset; + + nullCount = _nullCount; + return this; + } + + public ITypedBufferBuilder AppendValues( + ICollection values, Span validity, out int nullCount + ) + { + int i = 0; + int _nullCount = 0; + int length = values.Count; + bool allTrue = true; + bool allFalse = true; + Span bits = length < ArrayBuilder.MaxBitStackAllocSize ? stackalloc bool[length] : new bool[length]; + EnsureAdditionalBytes((length + 7) / 8); + + foreach (bool? value in values) + { + if (value.HasValue) + { + bool _value = value.Value; + + if (_value) + { + allFalse = false; + bits[i] = _value; + } + else + allTrue = false; + + validity[i] = true; + } + else + _nullCount++; + i++; + } + + nullCount = _nullCount; + + if (allTrue) + AppendBits(true, length); + if (allFalse) + AppendBits(false, length); + else + AppendBits(bits); + return this; + } + } +} + diff --git a/csharp/src/Apache.Arrow/Builder/IArrayBuilder.cs b/csharp/src/Apache.Arrow/Builder/IArrayBuilder.cs new file mode 100644 index 000000000000..fd74749020ed --- /dev/null +++ b/csharp/src/Apache.Arrow/Builder/IArrayBuilder.cs @@ -0,0 +1,110 @@ +using System.Threading.Tasks; +using Apache.Arrow.Memory; +using Apache.Arrow.Types; + +namespace Apache.Arrow.Builder +{ + public interface IArrayBuilder + { + IArrowType DataType { get; } + int Length { get; } + int NullCount { get; } + int Offset { get; } + + ITypedBufferBuilder[] Buffers { get; } + IArrayBuilder[] Children { get; } + IArrayBuilder Dictionary { get; } // Only used for dictionary type + + /// + /// Cast current builder to another one. + /// + /// Current casted + TBuilder As() where TBuilder : IArrayBuilder; + + /// + /// Append a null value to builder. + /// + /// Current + Status AppendNull(); + + /// + /// Append a number of null values to builder. + /// + /// Current + Status AppendNulls(int count); + + /// + /// Append value. + /// + /// Current + Status AppendScalar(IScalar value); + + /// + /// Append values. + /// + /// Current + Status AppendArray(ArrayData data); + Task AppendArrayAsync(ArrayData data); + + /// + /// Append values. + /// + /// Current + Status AppendArray(IArrowArray data); + Task AppendArrayAsync(IArrowArray data); + + /// + /// Clear all contents appended so far. + /// + void Clear(); + + /// + /// Ensure that there is enough space allocated to append the indicated number of elements without + /// any further reallocation. + /// + /// + /// Overallocation is used in order to minimize the impact of incremental Reserve() calls. + /// + /// Note that additionnalCapacity is relative to the current number of elements rather than + /// to the current capacity, so calls to Reserve() which are not interspersed with addition of new elements + /// may not increase the capacity. + /// + /// number of additional array values + /// Current + Status Reserve(int additionnalCapacity); + + /// + /// Ensure that enough memory has been allocated to fit the indicated number of total elements in the builder, + /// including any that have already been appended. + /// + /// + /// Does not account for reallocations that may be due to variable size data, like binary values. + /// To make space for incremental appends, use Reserve instead. + /// + /// minimum number of total array values to accommodate. Must be greater than the current capacity. + /// Current + Status Resize(int capacity); + + /// + /// Return result of builder as an internal generic ArrayData object. + /// + /// + /// Resets builder except for dictionary builder + /// + /// + /// + ArrayData FinishInternal(MemoryAllocator allocator = default); + Task FinishInternalAsync(MemoryAllocator allocator = null); + + /// + /// Return result of builder as an Array object. + /// + /// + /// Resets builder except for dictionary builder + /// + /// + /// + IArrowArray Build(MemoryAllocator allocator = default); + Task BuildAsync(MemoryAllocator allocator = null); + } +} diff --git a/csharp/src/Apache.Arrow/Builder/IBufferBuilder.cs b/csharp/src/Apache.Arrow/Builder/IBufferBuilder.cs new file mode 100644 index 000000000000..7d7ab44498a7 --- /dev/null +++ b/csharp/src/Apache.Arrow/Builder/IBufferBuilder.cs @@ -0,0 +1,205 @@ +// 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.Collections; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using Apache.Arrow.Memory; + +namespace Apache.Arrow.Builder +{ + public interface IBufferBuilder + { + /// + /// Raw byte Memory buffer. + /// + Memory Memory { get; } + + /// + /// Append bool value too buffer. + /// + /// bool to append + /// Current + IBufferBuilder AppendBit(bool bit); + + /// + /// Append boolean value too buffer. + /// + /// booleans to append + /// Current + IBufferBuilder AppendBits(ReadOnlySpan bits); + + /// + /// Append booleans value too buffer + /// + /// boolean to append + /// number of time to append + /// Current + IBufferBuilder AppendBits(bool value, int count); + + /// + /// Append empty boolean values too buffer + /// + /// number of time to append + /// Current + IBufferBuilder AppendEmptyBits(int count); + + /// + /// Append byte value too buffer. + /// + /// byte to append + /// Current + IBufferBuilder AppendByte(byte value); + + /// + /// Append byte values too buffer. + /// + /// bytes to append + /// fixed length + /// Current + IBufferBuilder AppendFixedSizeBytes(ICollection bytes, int fixedSize, Span validity, out int nullCount); + + /// + /// Append byte values too buffer. + /// + /// bytes to append + /// Current + IBufferBuilder AppendBytes(ReadOnlySpan bytes); + + /// + /// Append byte values too buffer repeated x times. + /// + /// bytes value + /// bytes value + /// Current + IBufferBuilder AppendBytes(ReadOnlySpan bytes, int count); + + /// + /// Append collection of nullable byte array. + /// + /// Current + IBufferBuilder AppendBytes( + ICollection values, + Span validity, Span offsets, + int baseOffset, + out int nullCount + ); + + /// + /// Append collection of nullable string values encoded with . + /// + /// Current + IBufferBuilder AppendBytes( + ICollection values, + Span validity, Span offsets, + int baseOffset, + Encoding encoding, + out int nullCount + ); + + /// + /// Append empty bytes values too buffer + /// + /// number of time to append + /// Current + IBufferBuilder AppendEmptyBytes(int count); + + /// + /// Clear all contents appended so far. + /// + IBufferBuilder Clear(); + + /// + /// Build an Arrow buffer from the appended contents so far. + /// + /// Optional memory allocator. + /// Returns an object. + ArrowBuffer Build(MemoryAllocator allocator = default); + Task BuildAsync(MemoryAllocator allocator = default); + + /// + /// Build an Arrow buffer from the appended contents so far of the specified byte size. + /// + /// Optional memory allocator. + /// Returns an object. + ArrowBuffer Build(int byteSize, MemoryAllocator allocator = default); + } + + public interface ITypedBufferBuilder : IBufferBuilder + { + int ValueBitSize { get; } + int ValueByteSize { get; } + int ValueLength { get; } + + /// + /// Reserve a given number of items' additional capacity. + /// + /// Number of new values. + ITypedBufferBuilder Reserve(int capacity); + + /// + /// Resize the buffer to a given size. + /// + /// + /// Note that if the required capacity is larger than the current length of the populated buffer so far, + /// the buffer's contents in the new, expanded region are undefined. + /// + /// + /// Note that if the required capacity is smaller than the current length of the populated buffer so far, + /// the buffer will be truncated and items at the end of the buffer will be lost. + /// + /// Number of values. + ITypedBufferBuilder Resize(int capacity); + } + + public interface ITypedBufferBuilder : ITypedBufferBuilder where T : struct + { + /// + /// Append struct values too buffer. + /// + /// structs to append + /// Current + ITypedBufferBuilder AppendValues(ReadOnlySpan values); + ITypedBufferBuilder AppendValues(ReadOnlySpan values); + + /// + /// Append struct value too buffer. + /// + /// struct to append + /// Current + ITypedBufferBuilder AppendValue(T value); + ITypedBufferBuilder AppendValue(bool value); + + /// + /// Append struct values too buffer + /// + /// struct to append + /// number of time to append + /// Current + ITypedBufferBuilder AppendValues(T value, int count); + ITypedBufferBuilder AppendValues(bool value, int count); + + /// + /// Append nullable struct values too buffer. + /// + /// structs to append + /// Current + ITypedBufferBuilder AppendValues(ICollection values, Span validity, out int nullCount); + ITypedBufferBuilder AppendValues(ICollection values, Span validity, out int nullCount); + } +} + diff --git a/csharp/src/Apache.Arrow/Builder/LogicalArrayBuilder.cs b/csharp/src/Apache.Arrow/Builder/LogicalArrayBuilder.cs new file mode 100644 index 000000000000..57170cd2aabe --- /dev/null +++ b/csharp/src/Apache.Arrow/Builder/LogicalArrayBuilder.cs @@ -0,0 +1,153 @@ +using System; +using System.Collections.Generic; +using Apache.Arrow.Reflection; +using Apache.Arrow.Types; + +namespace Apache.Arrow.Builder +{ + public class LogicalArrayBuilder : FixedBinaryArrayBuilder + where TPrimitive : struct + where TLogical : struct + { + private readonly Func ToPrimitive; + + public LogicalArrayBuilder(Func convert, int capacity = ArrayBuilder.DefaultCapacity) + : this(TypeReflection.ArrowType as FixedWidthType, convert, capacity) + { + } + + public LogicalArrayBuilder(FixedWidthType dataType, Func convert, int capacity = ArrayBuilder.DefaultCapacity) + : base(dataType, capacity) + { + ToPrimitive = convert; + } + + public Status AppendValue(TLogical value) => AppendValue(ToPrimitive(value)); + + public Status AppendValue(TLogical? value) + => value.HasValue ? AppendValue(ToPrimitive(value.Value)) : AppendNull(); + + public Status AppendValues(ReadOnlySpan values) + { + int length = values.Length; + Span buffer = new TPrimitive[length]; + + for (int i = 0; i < length; i++) + buffer[i] = ToPrimitive(values[i]); + + return AppendValues(buffer); + } + + public Status AppendValues(ICollection values) + { + int length = values.Count; + Span validity = length < MaxBitStackAllocSize ? stackalloc bool[length] : new bool[length]; + Span destination = new TPrimitive[length]; + int i = 0; + int nullCount = 0; + + // Transform the source ReadOnlySpan into the destination ReadOnlySpan, filling any null values with default(T) + foreach (TLogical? value in values) + { + if (value.HasValue) + { + destination[i] = ToPrimitive(value.Value); + validity[i] = true; + } + else + { + nullCount++; + destination[i] = default; + // default is already false + // validity[i] = false; + } + i++; + } + + return AppendValues(destination, validity, nullCount); + } + } + + // Timestamp / DateTime + public class TimestampArrayBuilder : LogicalArrayBuilder + { + private static Func ToPrimitive(TimeUnit unit) + { + return unit switch + { + TimeUnit.Second => DateTimeOffsetExtensions.ToUnixTimeSeconds, + TimeUnit.Millisecond => DateTimeOffsetExtensions.ToUnixTimeMilliseconds, + TimeUnit.Microsecond => DateTimeOffsetExtensions.ToUnixTimeMicroseconds, + TimeUnit.Nanosecond => DateTimeOffsetExtensions.ToUnixTimeNanoseconds, + _ => throw new ArgumentException($"Unknwown arrow TimeUnit {unit}"), + }; + } + + public TimestampArrayBuilder(int capacity = ArrayBuilder.DefaultCapacity) : this(TimestampType.SystemDefault, capacity) + { + } + + public TimestampArrayBuilder(TimestampType dtype, int capacity = ArrayBuilder.DefaultCapacity) : base(dtype, ToPrimitive(dtype.Unit), capacity) + { + } + } + + // Time + public class Time32ArrayBuilder : LogicalArrayBuilder + { + private static Func ToPrimitive(TimeUnit unit) + { + return unit switch + { + TimeUnit.Second => TimeSpanExtensions.TotalSeconds, + TimeUnit.Millisecond => TimeSpanExtensions.TotalMilliseconds, + _ => throw new ArgumentException($"Unknwown arrow TimeUnit {unit}"), + }; + } + + public Time32ArrayBuilder(int capacity = ArrayBuilder.DefaultCapacity) : this(Time32Type.Default, capacity) + { + } + + public Time32ArrayBuilder(TimeType dtype, int capacity = ArrayBuilder.DefaultCapacity) : base(dtype, ToPrimitive(dtype.Unit), capacity) + { + } + } + + public class Time64ArrayBuilder : LogicalArrayBuilder + { + private static Func ToPrimitive(TimeUnit unit) + { + return unit switch + { + TimeUnit.Microsecond => TimeSpanExtensions.TotalMicroseconds, + TimeUnit.Nanosecond => TimeSpanExtensions.TotalNanoseconds, + _ => throw new ArgumentException($"Unknwown arrow TimeUnit {unit}"), + }; + } + + public Time64ArrayBuilder(int capacity = ArrayBuilder.DefaultCapacity) : this(TimeType.SystemDefault, capacity) + { + } + + public Time64ArrayBuilder(TimeType dtype, int capacity = ArrayBuilder.DefaultCapacity) : base(dtype, ToPrimitive(dtype.Unit), capacity) + { + } + } + + // Date + public class Date32ArrayBuilder : LogicalArrayBuilder + { + public Date32ArrayBuilder(DateType dtype, int capacity = ArrayBuilder.DefaultCapacity) : base(dtype, DateTimeOffsetExtensions.ToUnixDays, capacity) + { + } + } + + public class Date64ArrayBuilder : LogicalArrayBuilder + { + public Date64ArrayBuilder(DateType dtype, int capacity = ArrayBuilder.DefaultCapacity) : base(dtype, DateTimeOffsetExtensions.ToUnixTimeMilliseconds, capacity) + { + } + } +} + diff --git a/csharp/src/Apache.Arrow/Builder/NestedArrayBuilder.cs b/csharp/src/Apache.Arrow/Builder/NestedArrayBuilder.cs new file mode 100644 index 000000000000..0fc8d43a5d61 --- /dev/null +++ b/csharp/src/Apache.Arrow/Builder/NestedArrayBuilder.cs @@ -0,0 +1,297 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Apache.Arrow.Memory; +using Apache.Arrow.Reflection; +using Apache.Arrow.Types; + +namespace Apache.Arrow.Builder +{ + public abstract class NestedArrayBuilder : ArrayBuilder + { + public NestedArrayBuilder(NestedType dataType, int capacity = DefaultCapacity) + : base( + dataType, + new ITypedBufferBuilder[] { new TypedBufferBuilder(capacity) }, + dataType.Fields.Select(field => ArrayBuilderFactory.MakeBuilder(field.DataType)).ToArray() + ) + { + } + + internal NestedArrayBuilder(ListType dataType, int capacity = ArrayBuilder.DefaultCapacity) + : base( + dataType, + new ITypedBufferBuilder[] { new TypedBufferBuilder(capacity), new TypedBufferBuilder(capacity) }, + dataType.Fields.Select(field => ArrayBuilderFactory.MakeBuilder(field.DataType)).ToArray() + ) + { + } + + public virtual Status Append() => AppendValid(); + public TBuilder GetBuilderAs(int index) where TBuilder : ArrayBuilder => Children[index].As(); + } + + public class ListArrayBuilder : NestedArrayBuilder + { + public new ListType DataType { get; } + public int CurrentOffset { get; internal set; } + + public ListArrayBuilder(ListType dataType, int capacity = ArrayBuilder.DefaultCapacity) : base(dataType, capacity) + { + DataType = dataType; + CurrentOffset = 0; + OffsetsBuffer.AppendValue(CurrentOffset); + } + + public ITypedBufferBuilder OffsetsBuffer => Buffers[1] as ITypedBufferBuilder; + + // Append Valididty + public override Status AppendNull() + { + OffsetsBuffer.AppendValue(CurrentOffset); + return base.AppendNull(); + } + + public override Status AppendNulls(int count) + { + OffsetsBuffer.AppendValues(CurrentOffset, count); + return base.AppendNulls(count); + } + + // Append Value + public override Status AppendScalar(IScalar value) + { + return value switch + { + IBaseListScalar list => AppendScalar(list), + INullableScalar nullable => nullable.IsValid ? AppendScalar(nullable.Value) : AppendNull(), + _ => throw new ArgumentException($"Cannot append scalar {value} in {this}, must implement IBaseListScalar") + }; + } + + public Status AppendValue(IBaseListScalar value) + { + if (value.IsValid) + { + Children[0].AppendArray(value.Array); + return AppendValid(); + } + return AppendNull(); + } + + public override IArrowArray Build(MemoryAllocator allocator = default) => Build(allocator); + + public ListArray Build(MemoryAllocator allocator = default, bool _ = true) + => new ListArray(FinishInternal(allocator)); + + internal override Status AppendPrimitiveValueOffset(ArrayData data) + { + if (data.Length == 0) + return Status.OK; + + // Value Offsets + var offsets = data.Buffers[1].Span.Slice(data.Offset * 4, (data.Length + 1) * 4).CastTo(); + int currentOffset = CurrentOffset; + Span newOffsets = new int[data.Length]; + + // Element length = array[index + 1] - array[index] + for (int i = 0; i < data.Length; i++) + { + // Add element length to current offset + currentOffset += offsets[i + 1] - offsets[i]; + newOffsets[i] = currentOffset; + } + + CurrentOffset = currentOffset; + OffsetsBuffer.AppendValues(newOffsets); + + return Status.OK; + } + } + + public class StructArrayBuilder : NestedArrayBuilder + { + public new StructType DataType { get; } + + public StructArrayBuilder(StructType dataType, int capacity = ArrayBuilder.DefaultCapacity) : base(dataType, capacity) + { + DataType = dataType; + } + + // Append Valididty + public override Status AppendNull() + { + foreach (IArrayBuilder child in Children) + child.AppendNull(); + + return base.AppendNull(); + } + + public override Status AppendNulls(int count) + { + foreach (IArrayBuilder child in Children) + child.AppendNulls(count); + + return base.AppendNulls(count); + } + + public override Status AppendScalar(IScalar value) + { + return value switch + { + IStructScalar svalue => AppendScalar(svalue), + INullableScalar nullable => nullable.IsValid ? AppendScalar(nullable.Value) : AppendNull(), + _ => throw new ArgumentException($"Cannot append scalar {value} in {this}, must implement IStructScalar") + }; + } + + public Status AppendValue(IStructScalar value) + { + if (value.IsValid) + { + for (int i = 0; i < Children.Length; i++) + { + var childValue = value.Fields[i]; + + Children[i].AppendScalar(childValue); + } + return AppendValid(); + } + return AppendNull(); + } + + public Status AppendBatch(RecordBatch batch) => AppendBatch(batch.ArrayList); + + public Status AppendBatch(IReadOnlyCollection arrays) + { + int length = 0; + + for (int i = 0; i < Children.Length; i++) + { + var array = arrays.ElementAt(i); + Children[i].AppendArray(array); + length = array.Length; + } + return AppendValidity(true, length); + } + + public async Task AppendBatchAsync(RecordBatch batch) + => await AppendBatchAsync(batch.ArrayList); + + public async Task AppendBatchAsync(IReadOnlyCollection arrays) + { + Task[] tasks = new Task[Children.Length]; + int length = 0; + + for (int i = 0; i < Children.Length; i++) + { + int index = i; // Create a local copy of the loop variable + var array = arrays.ElementAt(i); + length = array.Length; + tasks[index] = Children[index].AppendArrayAsync(array); + } + + await Task.WhenAll(tasks); + + return AppendValidity(true, length); + } + + public override IArrowArray Build(MemoryAllocator allocator = default) => Build(allocator); + public async override Task BuildAsync(MemoryAllocator allocator = default) + => await BuildAsync(allocator); + + public StructArray Build(MemoryAllocator allocator = default, bool _ = true) + => new StructArray(FinishInternal(allocator)); + + public async Task BuildAsync(MemoryAllocator allocator = default, bool _ = true) + => new StructArray(await FinishInternalAsync(allocator)); + + public RecordBatch BuildRecordBatch(MemoryAllocator allocator = default, IEnumerable> metadata = null) + => new(new Schema(DataType.Fields, metadata), Build(allocator).Fields, Length); + + public async Task BuildRecordBatchAsync(MemoryAllocator allocator = default, IEnumerable> metadata = null) + { + var built = await BuildAsync(allocator); + return new(new Schema(DataType.Fields, metadata), built.Fields, Length); + } + + internal override Status AppendPrimitiveValueOffset(ArrayData data) => Status.OK; + } + + public class ListArrayBuilder : ListArrayBuilder where T : struct + { + public readonly FixedBinaryArrayBuilder ValueBuilder; + + public ListArrayBuilder(int capacity = ArrayBuilder.DefaultCapacity) + : base(new ListType(TypeReflection.ArrowType), capacity) + { + ValueBuilder = GetBuilderAs>(0); + } + + public Status AppendValue(ReadOnlySpan value) + { + CurrentOffset++; + OffsetsBuffer.AppendValue(CurrentOffset); + ValueBuilder.AppendValues(value); + return AppendValid(); + } + + public Status AppendValues(ICollection values) + { + Span memory = new T[values.Sum(row => row.Length)]; + Span offsets = new int[values.Count]; + Span mask = new bool[offsets.Length]; + int offset = 0; + int i = 0; + int nullCount = 0; + + foreach (T[] value in values) + { + if (value is null) + { + offsets[i] = CurrentOffset; + // default is already false + // mask[i] = false; + nullCount++; + } + else + { + // Copy to memory + value.CopyTo(memory.Slice(offset, value.Length)); + + offset += value.Length; + CurrentOffset += value.Length; + + // Fill other buffers + offsets[i] = CurrentOffset; + mask[i] = true; + } + i++; + } + + return AppendValues(memory, offsets, mask, nullCount); + } + + private Status AppendValues( + ReadOnlySpan values, ReadOnlySpan offsets, ReadOnlySpan mask, int nullCount + ) + { + // Append Offset + CurrentOffset = offsets[offsets.Length - 1]; + OffsetsBuffer.AppendValues(offsets); + + // Append Values + ValueBuilder.AppendValues(values); + return AppendValidity(mask, nullCount); + } + } + + public class StructArrayBuilder : StructArrayBuilder where T : struct + { + public StructArrayBuilder(int capacity = ArrayBuilder.DefaultCapacity) : base(TypeReflection.ArrowType as StructType, capacity) + { + } + } +} + diff --git a/csharp/src/Apache.Arrow/Builder/PrimitiveArrayBuilder.cs b/csharp/src/Apache.Arrow/Builder/PrimitiveArrayBuilder.cs new file mode 100644 index 000000000000..c833fc27588b --- /dev/null +++ b/csharp/src/Apache.Arrow/Builder/PrimitiveArrayBuilder.cs @@ -0,0 +1,454 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using Apache.Arrow.Memory; +using Apache.Arrow.Reflection; +using Apache.Arrow.Types; + +namespace Apache.Arrow.Builder +{ + public class VariableBinaryArrayBuilder : ArrayBuilder + { + public ITypedBufferBuilder ValuesBuffer { get; } + + // From the docs: + // + // The offsets buffer contains length + 1 signed integers (either 32-bit or 64-bit, depending on the + // logical type), which encode the start position of each slot in the data buffer. The length of the + // value in each slot is computed using the difference between the offset at that slot’s index and the + // subsequent offset. + // + // In this builder, we choose to append the first offset (zero) upon construction, and each trailing + // offset is then added after each individual item has been appended. + public ITypedBufferBuilder OffsetsBuffer { get; } + + public int CurrentOffset { get; internal set; } + + public VariableBinaryArrayBuilder(IArrowType dataType, int capacity = ArrayBuilder.DefaultCapacity) + : this(dataType, new TypedBufferBuilder(capacity), new TypedBufferBuilder(capacity), new TypedBufferBuilder(-1, capacity)) + { + } + + public VariableBinaryArrayBuilder( + IArrowType dataType, + ITypedBufferBuilder validity, ITypedBufferBuilder offsets, ITypedBufferBuilder values + ) : base(dataType, new ITypedBufferBuilder[] { validity, offsets, values }) + { + ValuesBuffer = values; + OffsetsBuffer = offsets; + CurrentOffset = 0; + + OffsetsBuffer.AppendValue(CurrentOffset); + } + + public override Status AppendNull() + { + // Append Offset + OffsetsBuffer.AppendValue(CurrentOffset); + + // Not Append Value, get is based on offsets + // ValuesBuffer.AppendValue(nullValue); + return base.AppendNull(); + } + + public override Status AppendNulls(int count) + { + // Append Offset + OffsetsBuffer.AppendValues(CurrentOffset, count); + + // Not Append Values, get is based on offsets + // ValuesBuffer.AppendValues(nullValues); + return base.AppendNulls(count); + } + + public virtual Status AppendValue(byte value) + { + // Append Offset + CurrentOffset++; + OffsetsBuffer.AppendValue(CurrentOffset); + + // Not Append Value, get is based on offsets + ValuesBuffer.AppendByte(value); + return AppendValid(); + } + + public virtual Status AppendValue(ReadOnlySpan value) + { + // Append Offset + CurrentOffset += value.Length; + OffsetsBuffer.AppendValue(CurrentOffset); + ValuesBuffer.AppendBytes(value); + return AppendValid(); + } + + /// + /// Append byte values too builder repeated x times. + /// + /// byte value + /// repeat x times + public virtual Status AppendValues(ReadOnlySpan value, int count) + { + ValuesBuffer.AppendBytes(value, count); + + // Append Offsets + int valueLength = value.Length; + + if (valueLength == 0) + OffsetsBuffer.AppendValues(CurrentOffset, count); + else + { + Span offsets = count < MaxIntStackAllocSize ? stackalloc int[count] : new int[count]; + + for (int i = 0; i < count; i++) + { + CurrentOffset += valueLength; + offsets[i] = CurrentOffset; + } + OffsetsBuffer.AppendValues(offsets); + } + + return AppendValidity(true, count); + } + + public virtual Status AppendValues(ICollection bytes) + { + int length = bytes.Count; + int currentOffset = CurrentOffset; + + Span validity = length < MaxBitStackAllocSize ? stackalloc bool[length] : new bool[length]; + Span offsets = length < MaxIntStackAllocSize ? stackalloc int[length] : new int[length]; + + // Append values + ValuesBuffer.AppendBytes(bytes, validity, offsets, currentOffset, out int nullCount); + + // Append offsets + CurrentOffset = currentOffset; + OffsetsBuffer.AppendValues(offsets); + + return AppendValidity(validity, nullCount); + } + + public override Status AppendScalar(IScalar value) + { + return value switch + { + IBaseBinaryScalar binary => AppendScalar(binary), + INullableScalar nullable => nullable.IsValid ? AppendScalar(nullable.Value) : AppendNull(), + _ => throw new ArgumentException($"Cannot append scalar {value} in {this}, must implement IBaseBinaryScalar") + }; + } + + public Status AppendScalar(IBaseBinaryScalar value) + { + //if (!Validate(DataType, value.Type)) + // throw new ArgumentException($"Cannot append '{value}': {value.Type} != {DataType}"); + return AppendValue(value.AsBytes()); + } + + internal override Status AppendPrimitiveValueOffset(ArrayData data) + { + if (data.Length == 0) + return Status.OK; + + // Value Offsets + var offsets = data.Buffers[1].Span.Slice(data.Offset * 4, (data.Length + 1) * 4).CastTo(); + int offsetStart = offsets[0]; + int offsetEnd = offsets[offsets.Length - 1]; + int currentOffset = CurrentOffset; + int length = data.Length; + + Span newOffsets = length < MaxIntStackAllocSize ? stackalloc int[length] : new int[length]; + + // Element length = array[index + 1] - array[index] + for (int i = 0; i < data.Length; i++) + { + // Add element length to current offset + currentOffset += offsets[i + 1] - offsets[i]; + newOffsets[i] = currentOffset; + } + + CurrentOffset = currentOffset; + OffsetsBuffer.AppendValues(newOffsets); + + // Values + // Variable byte encoded, cannot append variable bit based + ValuesBuffer.AppendBytes(data.Buffers[2].Span.Slice(offsetStart, offsetEnd - offsetStart)); + + return Status.OK; + } + } + + public class FixedBinaryArrayBuilder : ArrayBuilder + { + private readonly int _bitSize; + private readonly int _byteSize; + + private readonly bool _isFullByte; + + public ITypedBufferBuilder ValuesBuffer { get; } + + public FixedBinaryArrayBuilder(FixedWidthType dtype, int capacity = ArrayBuilder.DefaultCapacity) + : this(dtype, new TypedBufferBuilder(capacity), new TypedBufferBuilder(dtype.BitWidth, capacity)) + { + } + + public FixedBinaryArrayBuilder( + IArrowType dataType, + ITypedBufferBuilder validity, ITypedBufferBuilder values + ) : base(dataType, new ITypedBufferBuilder[] { validity, values }) + { + ValuesBuffer = values; + + _bitSize = (dataType as FixedWidthType).BitWidth; + _byteSize = _bitSize / 8; + + _isFullByte = _bitSize % 8 == 0; + } + + public override Status AppendNull() + { + // Append Empty values + if (_isFullByte) + ValuesBuffer.AppendEmptyBytes(_byteSize); + else + ValuesBuffer.AppendEmptyBits(_bitSize); + + return base.AppendNull(); + } + + public override Status AppendNulls(int count) + { + // Append Empty values + if (_isFullByte) + ValuesBuffer.AppendEmptyBytes(_byteSize * count); + else + ValuesBuffer.AppendEmptyBits(_bitSize * count); + + return base.AppendNulls(count); + } + + public override Status AppendScalar(IScalar value) + { + return value switch + { + IPrimitiveScalarBase primitive => AppendScalar(primitive), + INullableScalar nullable => nullable.IsValid ? AppendScalar(nullable.Value) : AppendNull(), + _ => throw new ArgumentException($"Cannot append scalar {value} in {this}, must implement IPrimitiveScalarBase") + }; + } + + public Status AppendScalar(IPrimitiveScalarBase value) + { + //if (!Validate(value.Type)) + // throw new ArgumentException($"Cannot append '{value}': {value.Type} != {DataType}"); + return AppendBytes(value.AsBytes(), 1); + } + + // Bulk raw struct several bytes + public Status AppendBytes(ICollection values) + { + int length = values.Count; + Span mask = length < MaxBitStackAllocSize ? stackalloc bool[length] : new bool[length]; + ValuesBuffer.AppendFixedSizeBytes(values, _byteSize, mask, out int nullCount); + + return AppendValidity(mask, nullCount); + } + + public Status AppendValue(bool value) + { + ValuesBuffer.AppendBit(value); + return AppendValid(); + } + + public Status AppendValue(ReadOnlySpan values) + => AppendBytes(values.Slice(0, _byteSize), 1); + + public Status AppendBytes(ReadOnlySpan values, int length) + { + ValuesBuffer.AppendBytes(values); + return AppendValidity(true, length); + } + + public Status AppendRepeatBytes(ReadOnlySpan value, int count) + { + ValuesBuffer.AppendBytes(value, count); + return AppendValidity(true, count); + } + + public Status AppendBytes(ReadOnlySpan values, ReadOnlySpan validity, int nullCount) + { + ValuesBuffer.AppendBytes(values); + return AppendValidity(validity, nullCount); + } + + internal override Status AppendPrimitiveValueOffset(ArrayData data) + { + // Values + var dataValues = data.Buffers[1]; + int bitSize = ValuesBuffer.ValueBitSize; + int byteSize = ValuesBuffer.ValueByteSize; + + if (bitSize % 8 == 0) + { + // Fixed byte encoded + var span = dataValues.Span.Slice(data.Offset * byteSize, data.Length * byteSize); + ValuesBuffer.AppendBytes(span); + } + else if (data.Offset == 0) + { + int dataBitLength = data.Length * bitSize; + int dataByteLength = data.Length * byteSize; + + // Bulk copy bytes + ValuesBuffer.AppendBytes(dataValues.Span.Slice(0, data.Length * byteSize)); + + // Copy remaining bits + Span remainingBits = BitUtility + .BytesToBits(dataValues.Span.Slice(dataByteLength)) + .Slice(0, dataBitLength - dataByteLength * 8); + + ValuesBuffer.AppendBits(remainingBits); + } + else + { + int dataBitLength = data.Length * bitSize; + Span bits = dataBitLength < MaxBitStackAllocSize ? stackalloc bool[dataBitLength] : new bool[dataBitLength]; + bool allTrue = true; + bool allFalse = true; + int bitOffset = data.Offset * bitSize; + + for (int j = 0; j < dataBitLength; j++) + { + bool bit = BitUtility.GetBit(dataValues.Span, bitOffset + j); + + if (bit) + allFalse = false; + else + allTrue = false; + + bits[j] = bit; + } + + if (allFalse) + ValuesBuffer.AppendBits(false, dataBitLength); + else if (allTrue) + ValuesBuffer.AppendBits(true, dataBitLength); + else + ValuesBuffer.AppendBits(bits); + } + + return Status.OK; + } + } + + public class FixedBinaryArrayBuilder : FixedBinaryArrayBuilder where T : struct + { + public new ITypedBufferBuilder ValuesBuffer { get; } + + public FixedBinaryArrayBuilder(int capacity = ArrayBuilder.DefaultCapacity) : this(TypeReflection.ArrowType as FixedWidthType, capacity) + { + } + + public FixedBinaryArrayBuilder(FixedWidthType dtype, int capacity = ArrayBuilder.DefaultCapacity) + : this(dtype, new TypedBufferBuilder(dtype.BitWidth, capacity)) + { + } + + internal FixedBinaryArrayBuilder(FixedWidthType dtype, ITypedBufferBuilder values, int capacity = ArrayBuilder.DefaultCapacity) + : base(dtype, new TypedBufferBuilder(capacity), values) + { + ValuesBuffer = values; + } + + public override Status AppendScalar(IScalar value) + { + return value switch + { + IPrimitiveScalarBase primitive => AppendScalar(primitive), + INullableScalar nullable => nullable.IsValid ? AppendScalar(nullable.Value) : AppendNull(), + IDotNetStruct primitive => AppendValue(primitive.DotNet), + _ => throw new ArgumentException($"Cannot append scalar {value} in {this}, must implement IPrimitiveScalarBase") + }; + } + + public virtual Status AppendValue(T value) + => AppendBytes(TypeReflection.AsBytes(ref value), 1); + + public virtual Status AppendValues(ReadOnlySpan values) + => AppendBytes(MemoryMarshal.AsBytes(values), values.Length); + + public virtual Status AppendValues(ICollection values) + { + int length = values.Count; + Span mask = length < MaxBitStackAllocSize ? stackalloc bool[length] : new bool[length]; + ValuesBuffer.AppendValues(values, mask, out int nullCount); + return AppendValidity(mask, nullCount); + } + + public virtual Status AppendValues(T[] values) + => AppendBytes(MemoryMarshal.AsBytes(values), values.Length); + + public virtual Status AppendValues(T value, int count) + => AppendRepeatBytes(TypeReflection.AsBytes(ref value), count); + + public virtual Status AppendValues(ReadOnlySpan values, ReadOnlySpan validity, int nullCount) + => AppendBytes(MemoryMarshal.AsBytes(values), validity, nullCount); + } + + public class BooleanArrayBuilder : FixedBinaryArrayBuilder + { + public BooleanArrayBuilder(int capacity = ArrayBuilder.DefaultCapacity) : this(BooleanType.Default, capacity) + { + } + + public BooleanArrayBuilder(BooleanType dtype, int capacity = ArrayBuilder.DefaultCapacity) : base(dtype, capacity) + { + } + + public override Status AppendScalar(IScalar value) + { + return value switch + { + BooleanScalar boolean => AppendScalar(boolean), + INullableScalar nullable => nullable.IsValid ? AppendScalar(nullable.Value) : AppendNull(), + _ => throw new ArgumentException($"Cannot append scalar {value} in {this}, must implement BooleanScalar") + }; + } + public Status AppendScalar(BooleanScalar value) => AppendValue(value.DotNet); + + public override Status AppendValue(bool value) + { + ValuesBuffer.AppendBit(value); + return AppendValid(); + } + + public override Status AppendValues(ReadOnlySpan values) + { + ValuesBuffer.AppendBits(values); + return AppendValidity(true, values.Length); + } + + public override Status AppendValues(bool[] values) + { + ValuesBuffer.AppendBits(values); + return AppendValidity(true, values.Length); + } + + public override Status AppendValues(ReadOnlySpan values, ReadOnlySpan validity, int nullCount) + { + ValuesBuffer.AppendBits(values); + return AppendValidity(validity, nullCount); + } + + public override Status AppendValues(bool value, int count) + { + ValuesBuffer.AppendBits(value, count); + return AppendValidity(true, count); + } + + public override IArrowArray Build(MemoryAllocator allocator = default) => Build(allocator); + + public BooleanArray Build(MemoryAllocator allocator = default, bool _ = true) + => new BooleanArray(FinishInternal(allocator)); + } +} diff --git a/csharp/src/Apache.Arrow/ChunkedArray.cs b/csharp/src/Apache.Arrow/ChunkedArray.cs index 5f25acfe04a2..da62ad6a9108 100644 --- a/csharp/src/Apache.Arrow/ChunkedArray.cs +++ b/csharp/src/Apache.Arrow/ChunkedArray.cs @@ -72,8 +72,12 @@ public ChunkedArray Slice(long offset, long length) IList newArrays = new List(); while (curArrayIndex < numArrays && length > 0) { - newArrays.Add(Arrays[curArrayIndex].Slice((int)offset, - length > Arrays[curArrayIndex].Length ? Arrays[curArrayIndex].Length : (int)length)); + var array = Arrays[curArrayIndex] + .Slice( + (int)offset, + length > Arrays[curArrayIndex].Length ? Arrays[curArrayIndex].Length : (int)length + ) as Array; + newArrays.Add(array); length -= Arrays[curArrayIndex].Length - offset; offset = 0; curArrayIndex++; diff --git a/csharp/src/Apache.Arrow/Extensions/DateTimeOffsetExtensions.cs b/csharp/src/Apache.Arrow/Extensions/DateTimeOffsetExtensions.cs new file mode 100644 index 000000000000..20d13c4e470e --- /dev/null +++ b/csharp/src/Apache.Arrow/Extensions/DateTimeOffsetExtensions.cs @@ -0,0 +1,60 @@ +// 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; + +namespace Apache.Arrow +{ + public static class DateTimeOffsetExtensions + { + // Class methods + public static readonly DateTimeOffset UnixEpoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero); + + public static DateTimeOffset FromUnixTimeSeconds(long seconds) => UnixEpoch.AddSeconds(seconds); + public static DateTimeOffset FromUnixTimeSeconds(int seconds) => UnixEpoch.AddSeconds(seconds); + + public static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds) => UnixEpoch.AddMilliseconds(milliseconds); + public static DateTimeOffset FromUnixTimeMilliseconds(int milliseconds) => UnixEpoch.AddMilliseconds(milliseconds); + + public static DateTimeOffset FromUnixTimeMicroseconds(long micros) => UnixEpoch.AddTicks(micros * 10); + public static DateTimeOffset FromUnixTimeMicroseconds(int micros) => UnixEpoch.AddTicks(micros * 10); + + public static DateTimeOffset FromUnixTimeNanoseconds(long nanos) => UnixEpoch.AddTicks(nanos / 100); + public static DateTimeOffset FromUnixTimeNanoseconds(int nanos) => UnixEpoch.AddTicks(nanos / 100); + + // Instance methods + public static int ToUnixDays(this DateTimeOffset date) => (int)Math.Floor((date - UnixEpoch).TotalDays); + public static long ToUnixTimeSeconds(this DateTimeOffset date) => date.ToUnixTimeSeconds(); + public static long ToUnixTimeMilliseconds(this DateTimeOffset date) => date.ToUnixTimeMilliseconds(); + public static long ToUnixTimeMicroseconds(this DateTimeOffset date) => (date.UtcTicks - UnixEpoch.Ticks) / 10; + public static long ToUnixTimeNanoseconds(this DateTimeOffset date) => (date.UtcTicks - UnixEpoch.Ticks) * 100; + + public static DateTimeOffset Truncate(this DateTimeOffset dateTimeOffset, TimeSpan offset) + { + if (offset == TimeSpan.Zero) + { + return dateTimeOffset; + } + + if (dateTimeOffset == DateTimeOffset.MinValue || dateTimeOffset == DateTimeOffset.MaxValue) + { + return dateTimeOffset; + } + + return dateTimeOffset.AddTicks(-(dateTimeOffset.Ticks % offset.Ticks)); + } + + } +} diff --git a/csharp/src/Apache.Arrow/Extensions/TimeSpanExtensions.cs b/csharp/src/Apache.Arrow/Extensions/TimeSpanExtensions.cs index 133156d7b712..861f2411d029 100644 --- a/csharp/src/Apache.Arrow/Extensions/TimeSpanExtensions.cs +++ b/csharp/src/Apache.Arrow/Extensions/TimeSpanExtensions.cs @@ -19,6 +19,21 @@ namespace Apache.Arrow { public static class TimeSpanExtensions { + // Class methods + public static TimeSpan FromNanoseconds(long nanoseconds) => TimeSpan.FromTicks(nanoseconds / 100); + public static TimeSpan FromNanoseconds(int nanoseconds) => TimeSpan.FromTicks(nanoseconds / 100); + + public static TimeSpan FromMicroseconds(long microseconds) => TimeSpan.FromTicks(microseconds * 10); + public static TimeSpan FromMicroseconds(int microseconds) => TimeSpan.FromTicks(microseconds * 10); + + public static TimeSpan FromMilliseconds(long milliseconds) => TimeSpan.FromMilliseconds(milliseconds); + public static TimeSpan FromMilliseconds(int milliseconds) => TimeSpan.FromMilliseconds(milliseconds); + + public static TimeSpan FromSeconds(long seconds) => TimeSpan.FromSeconds(seconds); + public static TimeSpan FromSeconds(int seconds) => TimeSpan.FromSeconds(seconds); + + // Instance methods + /// /// Formats a TimeSpan into an ISO 8601 compliant time offset string. /// @@ -31,5 +46,10 @@ public static string ToTimeZoneOffsetString(this TimeSpan timeSpan) int minutes = Math.Abs(timeSpan.Minutes); return sign + hours.ToString("00") + ":" + minutes.ToString("00"); } + + public static int TotalSeconds(this TimeSpan timeSpan) => (int)timeSpan.TotalSeconds; + public static int TotalMilliseconds(this TimeSpan timeSpan) => (int)timeSpan.Milliseconds; + public static long TotalMicroseconds(this TimeSpan timeSpan) => timeSpan.Ticks / 10; + public static long TotalNanoseconds(this TimeSpan timeSpan) => timeSpan.Ticks * 100; } } diff --git a/csharp/src/Apache.Arrow/Field.Builder.cs b/csharp/src/Apache.Arrow/Field.Builder.cs index 1e7aa192e08b..af99c53e44b4 100644 --- a/csharp/src/Apache.Arrow/Field.Builder.cs +++ b/csharp/src/Apache.Arrow/Field.Builder.cs @@ -13,9 +13,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Apache.Arrow.Types; using System; using System.Collections.Generic; +using System.Linq; +using Apache.Arrow.Reflection; +using Apache.Arrow.Types; namespace Apache.Arrow { @@ -26,6 +28,7 @@ public class Builder private Dictionary _metadata; private string _name; private IArrowType _type; + internal IArrowType CurrentType => _type; private bool _nullable; public Builder() @@ -52,6 +55,125 @@ public Builder DataType(IArrowType type) return this; } + // Build DataType from C# Type + public Builder DataType(System.Type valueType, string defaultTimezone = "+00:00", Dictionary fieldTimezones = null) + { + System.Type child = System.Nullable.GetUnderlyingType(valueType); + + if (child != null) + { + // Nullable Type + DataType(child, defaultTimezone); + Nullable(true); + return this; + } + + // Not Nullable Type + Nullable(false); + + switch (valueType) + { + // Boolean + case var _ when valueType == typeof(bool): + DataType(new BooleanType()); + break; + // String + case var _ when valueType == typeof(string): + DataType(new StringType()); + Nullable(true); + break; + // Integers + case var _ when valueType == typeof(sbyte): + DataType(new Int8Type()); + break; + case var _ when valueType == typeof(short): + DataType(new Int16Type()); + break; + case var _ when valueType == typeof(int): + DataType(new Int32Type()); + break; + case var _ when valueType == typeof(long): + DataType(new Int64Type()); + break; + // Unisgned Integers + case var _ when valueType == typeof(byte): + DataType(new UInt8Type()); + break; + case var _ when valueType == typeof(ushort): + DataType(new UInt16Type()); + break; + case var _ when valueType == typeof(uint): + DataType(new UInt32Type()); + break; + case var _ when valueType == typeof(ulong): + DataType(new UInt64Type()); + break; + // Decimal + case var _ when valueType == typeof(decimal): + DataType(Decimal256Type.SystemDefault); + break; + // Float + case var _ when valueType == typeof(float): + DataType(new FloatType()); + break; + // Double + case var _ when valueType == typeof(double): + DataType(new DoubleType()); + break; + // DateTime + case var _ when valueType == typeof(DateTime) || valueType == typeof(DateTimeOffset): + DataType(new TimestampType(TimeUnit.Nanosecond, defaultTimezone)); + break; + // Time + case var _ when valueType == typeof(TimeSpan): + DataType(new Time64Type(TimeUnit.Nanosecond)); + break; +#if NETCOREAPP3_1_OR_GREATER + // IEnumerable: List, Array, ... + case var list when TypeReflection.IsIterable(valueType): + Type elementType = list.GetGenericArguments()[0]; + + switch (elementType) + { + // Binary + case var _ when valueType == typeof(byte): + DataType(new BinaryType()); + break; + // List of Arrays + default: + DataType(new ListType(new Builder().Name("item").DataType(elementType, defaultTimezone, fieldTimezones).Build())); + break; + } + Nullable(true); + break; + // Struct like: get all properties + case var structure when TypeReflection.IsNestedStruct(valueType): + if (string.IsNullOrEmpty(_name)) + Name(structure.Name); + + DataType(new StructType( + TypeReflection + .GetProperties(structure) + .Select(property => { + // Check if it is not given in parameters, or get default + string fieldTimezone = fieldTimezones?.GetValueOrDefault(structure.Name, defaultTimezone); + + return new Builder().Name(property.Name).DataType(property.PropertyType, fieldTimezone, fieldTimezones).Build(); + }) + .ToArray() + )); + + break; +#endif + // Error + // TODO: Dictionary: IDictionary : should be MapType, not implemented yet + default: + throw new InvalidCastException($"Cannot convert System.Type<{valueType}> to ArrowType"); + } + + return this; + } + public Builder Nullable(bool value) { _nullable = value; diff --git a/csharp/src/Apache.Arrow/Interfaces/IArrowArray.cs b/csharp/src/Apache.Arrow/Interfaces/IArrowArray.cs index 50fbc3af6dd7..c2a352f0b904 100644 --- a/csharp/src/Apache.Arrow/Interfaces/IArrowArray.cs +++ b/csharp/src/Apache.Arrow/Interfaces/IArrowArray.cs @@ -33,8 +33,16 @@ public interface IArrowArray : IDisposable void Accept(IArrowArrayVisitor visitor); + /// + /// Cast current array to another one. + /// + /// Current casted + TArray As() where TArray : IArrowArray; + + IScalar GetScalar(int index); + //IArrowArray Slice(int offset); - //IArrowArray Slice(int offset, int length); + IArrowArray Slice(int offset, int length); } } diff --git a/csharp/src/Apache.Arrow/Interfaces/IScalar.cs b/csharp/src/Apache.Arrow/Interfaces/IScalar.cs new file mode 100644 index 000000000000..303b159f3c17 --- /dev/null +++ b/csharp/src/Apache.Arrow/Interfaces/IScalar.cs @@ -0,0 +1,78 @@ +using System; +using Apache.Arrow.Types; + +namespace Apache.Arrow +{ + // Inspired from C++ implementation + // https://arrow.apache.org/docs/cpp/api/scalar.html + public interface IScalar + { + IArrowType Type { get; } + bool IsValid { get; } + } + + public interface INullableScalar : IScalar + { + IScalar Value { get; } + } + + public interface IArrowTyped where TArrowType : IArrowType + { + TArrowType Type { get; } + } + + public interface IDotNetStruct where T : struct + { + T DotNet { get; } + } + + public interface IPrimitiveScalarBase : IScalar + { + ReadOnlySpan AsBytes(); + } + + public interface IPrimitiveScalar : IPrimitiveScalarBase, IArrowTyped + where TArrowType : IArrowType + { + } + + public interface INumericScalar : IPrimitiveScalar + where TArrowType : IArrowType + { + } + + public interface IBaseBinaryScalar : IPrimitiveScalarBase + { + } + + public interface IBaseBinaryScalar : IBaseBinaryScalar, IArrowTyped + where TArrowType : IArrowType + { + } + + public interface IDecimalScalar : INumericScalar + where TArrowType : IDecimalType + { + } + + // Nested Scalars + public interface IBaseListScalar : IScalar + { + IArrowArray Array { get; } + } + + public interface IBaseListScalar : IBaseListScalar, IArrowTyped + where TArrowType : IArrowType + { + } + + public interface IStructScalar : IScalar + { + IScalar[] Fields { get; } + } + + public interface IStructScalar : IStructScalar, IArrowTyped + where TArrowType : IArrowType + { + } +} diff --git a/csharp/src/Apache.Arrow/Reflection/TypeReflection.cs b/csharp/src/Apache.Arrow/Reflection/TypeReflection.cs new file mode 100644 index 000000000000..67a57564be96 --- /dev/null +++ b/csharp/src/Apache.Arrow/Reflection/TypeReflection.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Apache.Arrow.Types; + +namespace Apache.Arrow.Reflection +{ + public class TypeReflection + { + internal static IArrowType GetArrowType(System.Type type) + => new Field.Builder().DataType(type).CurrentType; + +#if NETCOREAPP2_0_OR_GREATER + internal static IEnumerable GetProperties(System.Type type) => type + .GetProperties(BindingFlags.Instance | BindingFlags.Public) + .Where(p => p.GetIndexParameters().Length == 0); + + internal static bool IsIterable(System.Type type) + => typeof(IEnumerable).IsAssignableFrom(type) && type != typeof(string); + + internal static bool IsNestedStruct(System.Type type) + => type.IsValueType && !type.IsEnum && !type.IsPrimitive; + + internal static ReadOnlySpan CreateReadOnlySpan(ref T value) + => MemoryMarshal.CreateReadOnlySpan(ref value, 1); +#else + internal static ReadOnlySpan CreateReadOnlySpan(ref T value) + => new T[] { value }.AsSpan(); + + internal static IEnumerable GetProperties(System.Type type) + => throw new NotSupportedException("Cannot get properties, need to run on .net core >= 2.0"); +#endif + internal static ReadOnlyMemory AsMemoryBytes(decimal value, IDecimalType type) + { + byte[] bytes = new byte[type.ByteWidth]; + DecimalUtility.GetBytes(value, type.Precision, type.Scale, type.ByteWidth, bytes); + return new ReadOnlyMemory(bytes); + } + + internal static ReadOnlyMemory AsMemoryBytes(T value) where T : struct + { + byte[] bytes = new byte[Unsafe.SizeOf()]; + Unsafe.WriteUnaligned(ref bytes[0], value); + return new ReadOnlyMemory(bytes); + } + + internal static unsafe ReadOnlySpan AsBytes(ref T value) where T : struct + { +#pragma warning disable CS8500 // This takes the address of, gets the size of, or declares a pointer to a managed type + fixed (T* ptr = &value) + { + return new ReadOnlySpan((byte*)ptr, sizeof(T)); + } +#pragma warning restore CS8500 // This takes the address of, gets the size of, or declares a pointer to a managed type + } + + public static unsafe T CastTo(ReadOnlySpan bytes) where T : struct + { + fixed (byte* ptr = &bytes.GetPinnableReference()) + return Marshal.PtrToStructure((IntPtr)ptr); + } + } + + public class TypeReflection : TypeReflection + { + internal static readonly Type DotNetType = typeof(T); + public static readonly IArrowType ArrowType = GetArrowType(DotNetType); + } +} diff --git a/csharp/src/Apache.Arrow/Scalar.cs b/csharp/src/Apache.Arrow/Scalar.cs new file mode 100644 index 000000000000..e3bb1ccdade1 --- /dev/null +++ b/csharp/src/Apache.Arrow/Scalar.cs @@ -0,0 +1,513 @@ +using System; +using System.Text; +using Apache.Arrow.Reflection; +using Apache.Arrow.Types; + +namespace Apache.Arrow +{ + // Inspired from C++ implementation + // https://arrow.apache.org/docs/cpp/api/scalar.html + public struct NullableScalar : INullableScalar + { + public IScalar Value { get; } + public bool IsValid { get; } + public IArrowType Type { get; } + + public NullableScalar(IArrowType type, IScalar value) + : this(type, value != null, value) + { + } + + public NullableScalar(IArrowType type, bool isValid, IScalar value) + { + Type = type; + IsValid = isValid; + Value = value; + } + } + + public struct BinaryScalar : IBaseBinaryScalar + { + public ArrowBuffer Buffer { get; } + public BinaryType Type => BinaryType.Default; + IArrowType IScalar.Type => Type; + public bool IsValid => true; + + public BinaryScalar(ArrowBuffer buffer) + { + Buffer = buffer; + } + + public unsafe ReadOnlySpan AsBytes() => Buffer.Span; + + // Define an implicit conversion + public static implicit operator BinaryScalar(ReadOnlyMemory value) => new(new ArrowBuffer(value)); + } + + public struct FixedSizeBinaryScalar : IBaseBinaryScalar + { + public ArrowBuffer Buffer { get; } + public FixedSizeBinaryType Type { get; } + IArrowType IScalar.Type => Type; + public bool IsValid => true; + + public FixedSizeBinaryScalar(ReadOnlyMemory bytes) + : this(new FixedSizeBinaryType(bytes.Length), new ArrowBuffer(bytes)) + { + } + + public FixedSizeBinaryScalar(FixedSizeBinaryType type, ReadOnlyMemory bytes) + : this(type, new ArrowBuffer(bytes)) + { + } + + internal FixedSizeBinaryScalar(FixedSizeBinaryType type, ArrowBuffer buffer) + { + Type = type; + Buffer = buffer; + } + + public unsafe ReadOnlySpan AsBytes() => Buffer.Span; + + // Define an implicit conversion + public static implicit operator FixedSizeBinaryScalar(ReadOnlyMemory value) => new(value); + } + + public struct StringScalar : IBaseBinaryScalar + { + public static StringScalar Empty => new(ArrowBuffer.Empty); + + public ArrowBuffer Buffer { get; } + public StringType Type => StringType.Default; + IArrowType IScalar.Type => Type; + public bool IsValid => true; + + public StringScalar(string value) + : this(value, StringType.DefaultEncoding) + { + } + + public StringScalar(string value, Encoding encoding) + : this(new ArrowBuffer(encoding.GetBytes(value))) + { + } + + internal StringScalar(ArrowBuffer value) + { + Buffer = value; + } + + public string DotNet => GetString(StringType.DefaultEncoding); + public unsafe ReadOnlySpan AsBytes() => Buffer.Span; + + /// + /// Converts the underlying byte data to a string using the specified encoding. + /// + /// + /// Since strings are not nullable in a StringScalar, if the byte data is empty, it returns . + /// + /// The encoding used to decode the byte data. + /// String representation of the decoded byte data. + public unsafe string GetString(Encoding encoding) + { + fixed (byte* ptr = AsBytes()) + { + if (ptr is null) + return string.Empty; + int charLength = encoding.GetCharCount(ptr, Buffer.Length); + char[] buffer = new char[charLength]; + + fixed (char* bufferPtr = buffer) + { + encoding.GetChars(ptr, Buffer.Length, bufferPtr, charLength); + } + + return new string(buffer); + } + } + + // Define an implicit conversion + public static implicit operator StringScalar(string value) => new(value); + public static implicit operator string(StringScalar scalar) => scalar.DotNet; + } + +#pragma warning disable CS9084 // Struct member returns 'this' or other instance members by reference + public struct BooleanScalar : IPrimitiveScalar, IDotNetStruct + { + private bool _value; + public bool DotNet => _value; + public BooleanType Type => BooleanType.Default; + IArrowType IScalar.Type => Type; + public bool IsValid => true; + + public BooleanScalar(bool value) + { + _value = value; + } + public unsafe ReadOnlySpan AsBytes() => TypeReflection.AsBytes(ref _value); + + // Define an implicit conversion + public static implicit operator BooleanScalar(bool value) => new(value); + public static implicit operator bool(BooleanScalar scalar) => scalar.DotNet; + } + + // Numeric scalars + public struct UInt8Scalar : INumericScalar, IDotNetStruct + { + private byte _value; + public byte DotNet => _value; + public UInt8Type Type => UInt8Type.Default; + IArrowType IScalar.Type => Type; + public bool IsValid => true; + + public UInt8Scalar(byte value) + { + _value = value; + } + + internal UInt8Scalar(ArrowBuffer value) : this(TypeReflection.CastTo(value.Span)) + { + } + + public unsafe ReadOnlySpan AsBytes() => TypeReflection.AsBytes(ref _value); + + // Define an implicit conversion + public static implicit operator UInt8Scalar(byte value) => new(value); + public static implicit operator byte(UInt8Scalar scalar) => scalar.DotNet; + } + + public struct Int8Scalar : INumericScalar, IDotNetStruct + { + private sbyte _value; + public sbyte DotNet => _value; + public Int8Type Type => Int8Type.Default; + IArrowType IScalar.Type => Type; + public bool IsValid => true; + + public Int8Scalar(sbyte value) + { + _value = value; + } + + internal Int8Scalar(ArrowBuffer value) : this(TypeReflection.CastTo(value.Span)) + { + } + + public unsafe ReadOnlySpan AsBytes() => TypeReflection.AsBytes(ref _value); + + // Define an implicit conversion + public static implicit operator Int8Scalar(sbyte value) => new(value); + public static implicit operator sbyte(Int8Scalar scalar) => scalar.DotNet; + } + + public struct UInt16Scalar : INumericScalar, IDotNetStruct + { + private ushort _value; + public ushort DotNet => _value; + public UInt16Type Type => UInt16Type.Default; + IArrowType IScalar.Type => Type; + public bool IsValid => true; + + public UInt16Scalar(ushort value) + { + _value = value; + } + + internal UInt16Scalar(ArrowBuffer value) : this(TypeReflection.CastTo(value.Span)) + { + } + + public unsafe ReadOnlySpan AsBytes() => TypeReflection.AsBytes(ref _value); + + // Define an implicit conversion + public static implicit operator UInt16Scalar(ushort value) => new(value); + public static implicit operator ushort(UInt16Scalar scalar) => scalar.DotNet; + } + public struct Int16Scalar : INumericScalar, IDotNetStruct + { + private short _value; + public short DotNet => _value; + public Int16Type Type => Int16Type.Default; + IArrowType IScalar.Type => Type; + public bool IsValid => true; + + public Int16Scalar(short value) + { + _value = value; + } + + internal Int16Scalar(ArrowBuffer value) : this(TypeReflection.CastTo(value.Span)) + { + } + + public unsafe ReadOnlySpan AsBytes() => TypeReflection.AsBytes(ref _value); + + // Define an implicit conversion + public static implicit operator Int16Scalar(short value) => new(value); + public static implicit operator short(Int16Scalar scalar) => scalar.DotNet; + } + + public struct UInt32Scalar : INumericScalar, IDotNetStruct + { + private uint _value; + public uint DotNet => _value; + public UInt32Type Type => UInt32Type.Default; + IArrowType IScalar.Type => Type; + public bool IsValid => true; + + public UInt32Scalar(uint value) + { + _value = value; + } + + internal UInt32Scalar(ArrowBuffer value) : this(TypeReflection.CastTo(value.Span)) + { + } + + public unsafe ReadOnlySpan AsBytes() => TypeReflection.AsBytes(ref _value); + + // Define an implicit conversion + public static implicit operator UInt32Scalar(uint value) => new(value); + public static implicit operator uint(UInt32Scalar scalar) => scalar.DotNet; + } + + public struct Int32Scalar : INumericScalar, IDotNetStruct + { + private int _value; + public int DotNet => _value; + public Int32Type Type => Int32Type.Default; + IArrowType IScalar.Type => Type; + public bool IsValid => true; + + public Int32Scalar(int value) + { + _value = value; + } + + internal Int32Scalar(ArrowBuffer value) : this(TypeReflection.CastTo(value.Span)) + { + } + + public unsafe ReadOnlySpan AsBytes() => TypeReflection.AsBytes(ref _value); + + // Define an implicit conversion + public static implicit operator Int32Scalar(int value) => new(value); + public static implicit operator int(Int32Scalar scalar) => scalar.DotNet; + } + + public struct UInt64Scalar : INumericScalar, IDotNetStruct + { + private ulong _value; + public ulong DotNet => _value; + public UInt64Type Type => UInt64Type.Default; + IArrowType IScalar.Type => Type; + public bool IsValid => true; + + public UInt64Scalar(ulong value) + { + _value = value; + } + + internal UInt64Scalar(ArrowBuffer value) : this(TypeReflection.CastTo(value.Span)) + { + } + + public unsafe ReadOnlySpan AsBytes() => TypeReflection.AsBytes(ref _value); + + // Define an implicit conversion + public static implicit operator UInt64Scalar(ulong value) => new(value); + public static implicit operator ulong(UInt64Scalar scalar) => scalar.DotNet; + } + + public struct Int64Scalar : INumericScalar, IDotNetStruct + { + private long _value; + public long DotNet => _value; + public Int64Type Type => Int64Type.Default; + IArrowType IScalar.Type => Type; + public bool IsValid => true; + + public Int64Scalar(long value) + { + _value = value; + } + + internal Int64Scalar(ArrowBuffer value) : this(TypeReflection.CastTo(value.Span)) + { + } + + public unsafe ReadOnlySpan AsBytes() => TypeReflection.AsBytes(ref _value); + + // Define an implicit conversion + public static implicit operator Int64Scalar(long value) => new(value); + public static implicit operator long(Int64Scalar scalar) => scalar.DotNet; + } + + public struct FloatScalar : INumericScalar, IDotNetStruct + { + private float _value; + public float DotNet => _value; + public FloatType Type => FloatType.Default; + IArrowType IScalar.Type => Type; + public bool IsValid => true; + + public FloatScalar(float value) + { + _value = value; + } + + internal FloatScalar(ArrowBuffer value) : this(TypeReflection.CastTo(value.Span)) + { + } + + public unsafe ReadOnlySpan AsBytes() => TypeReflection.AsBytes(ref _value); + + // Define an implicit conversion + public static implicit operator FloatScalar(float value) => new(value); + public static implicit operator float(FloatScalar scalar) => scalar.DotNet; + } + + public struct DoubleScalar : INumericScalar, IDotNetStruct + { + private double _value; + public double DotNet => _value; + public DoubleType Type => DoubleType.Default; + IArrowType IScalar.Type => Type; + public bool IsValid => true; + + public DoubleScalar(double value) + { + _value = value; + } + + internal DoubleScalar(ArrowBuffer value) : this(TypeReflection.CastTo(value.Span)) + { + } + + public unsafe ReadOnlySpan AsBytes() => TypeReflection.AsBytes(ref _value); + + // Define an implicit conversion + public static implicit operator DoubleScalar(double value) => new(value); + public static implicit operator double(DoubleScalar scalar) => scalar.DotNet; + } + +#if NET5_0_OR_GREATER + public struct HalfFloatScalar : INumericScalar, IDotNetStruct + { + private Half _value; + public Half DotNet => _value; + public HalfFloatType Type => HalfFloatType.Default; + IArrowType IScalar.Type => Type; + public bool IsValid => true; + + public HalfFloatScalar(Half value) + { + _value = value; + } + + internal HalfFloatScalar(ArrowBuffer value) : this(TypeReflection.CastTo(value.Span)) + { + } + + public unsafe ReadOnlySpan AsBytes() => TypeReflection.AsBytes(ref _value); + + // Define an implicit conversion + public static implicit operator HalfFloatScalar(Half value) => new(value); + public static implicit operator Half(HalfFloatScalar scalar) => scalar.DotNet; + } +#endif +#pragma warning restore CS9084 // Struct member returns 'this' or other instance members by reference + + public struct Decimal128Scalar : INumericScalar, IDotNetStruct + { + public ArrowBuffer Buffer { get; } + public Decimal128Type Type { get; } + IArrowType IScalar.Type => Type; + public bool IsValid => true; + + public Decimal128Scalar(decimal value) + : this(Decimal128Type.Default, value) + { + } + + public Decimal128Scalar(Decimal128Type type, decimal value) + : this(type, new ArrowBuffer(TypeReflection.AsMemoryBytes(value, type))) + { + } + + internal Decimal128Scalar(Decimal128Type type, ArrowBuffer value) + { + Type = type; + Buffer = value; + } + + public decimal DotNet => DecimalUtility.GetDecimal(Buffer, 0, Type.Scale, Type.ByteWidth); + public unsafe ReadOnlySpan AsBytes() => Buffer.Span; + + // Define an implicit conversion + public static implicit operator Decimal128Scalar(decimal value) => new(value); + public static implicit operator decimal(Decimal128Scalar scalar) => scalar.DotNet; + } + + public struct Decimal256Scalar : IDecimalScalar, IDotNetStruct + { + public ArrowBuffer Buffer { get; } + public Decimal256Type Type { get; } + IArrowType IScalar.Type => Type; + public bool IsValid => true; + + public Decimal256Scalar(decimal value) + : this(Decimal256Type.SystemDefault, value) + { + } + + public Decimal256Scalar(Decimal256Type type, decimal value) + : this(type, new ArrowBuffer(TypeReflection.AsMemoryBytes(value, type))) + { + } + + internal Decimal256Scalar(Decimal256Type type, ArrowBuffer value) + { + Type = type; + Buffer = value; + } + + public decimal DotNet => DecimalUtility.GetDecimal(Buffer, 0, Type.Scale, Type.ByteWidth); + public unsafe ReadOnlySpan AsBytes() => Buffer.Span; + + // Define an implicit conversion + public static implicit operator Decimal256Scalar(decimal value) => new(value); + public static implicit operator decimal(Decimal256Scalar scalar) => scalar.DotNet; + } + + // Nested scalars + public struct ListScalar : IBaseListScalar + { + public ListType Type { get; } + IArrowType IScalar.Type => Type; + public IArrowArray Array { get; } + public bool IsValid { get; } + + public ListScalar(ListType type, IArrowArray array, bool isValid = true) + { + Type = type; + Array = array; + IsValid = isValid; + } + } + + public struct StructScalar : IStructScalar + { + public StructType Type { get; } + IArrowType IScalar.Type => Type; + public IScalar[] Fields { get; } + public bool IsValid { get; } + + public StructScalar(StructType type, IScalar[] fields, bool isValid = true) + { + Type = type; + Fields = fields; + IsValid = isValid; + } + } +} diff --git a/csharp/src/Apache.Arrow/Status.cs b/csharp/src/Apache.Arrow/Status.cs new file mode 100644 index 000000000000..92261a26c70b --- /dev/null +++ b/csharp/src/Apache.Arrow/Status.cs @@ -0,0 +1,39 @@ +namespace Apache.Arrow +{ + public enum StatusCode + { + OK = 0, + OutOfMemory = 1, + KeyError = 2, + TypeError = 3, + Invalid = 4, + IOError = 5, + CapacityError = 6, + IndexError = 7, + Cancelled = 8, + UnknownError = 9, + NotImplemented = 10, + SerializationError = 11, + RError = 13, + // Gandiva range of errors + CodeGenError = 40, + ExpressionValidationError = 41, + ExecutionError = 42, + // Continue generic codes. + AlreadyExists = 45 + } + + public class Status + { + public static readonly Status OK = new(StatusCode.OK); + + public readonly StatusCode Code; + public readonly string Message; + + public Status(StatusCode code, string msg = null) + { + Code = code; + Message = msg; + } + } +} diff --git a/csharp/src/Apache.Arrow/Types/Decimal128Type.cs b/csharp/src/Apache.Arrow/Types/Decimal128Type.cs index e00b9da10ead..397df1c3acab 100644 --- a/csharp/src/Apache.Arrow/Types/Decimal128Type.cs +++ b/csharp/src/Apache.Arrow/Types/Decimal128Type.cs @@ -15,8 +15,10 @@ namespace Apache.Arrow.Types { - public sealed class Decimal128Type : FixedSizeBinaryType + public sealed class Decimal128Type : FixedSizeBinaryType, IDecimalType { + // Arbitrary chose to max byte encoding + public static readonly Decimal128Type Default = new(23, 9); public override ArrowTypeId TypeId => ArrowTypeId.Decimal128; public override string Name => "decimal128"; diff --git a/csharp/src/Apache.Arrow/Types/Decimal256Type.cs b/csharp/src/Apache.Arrow/Types/Decimal256Type.cs index b184deb3cde9..9ab01b360cb8 100644 --- a/csharp/src/Apache.Arrow/Types/Decimal256Type.cs +++ b/csharp/src/Apache.Arrow/Types/Decimal256Type.cs @@ -15,8 +15,11 @@ namespace Apache.Arrow.Types { - public sealed class Decimal256Type: FixedSizeBinaryType + public sealed class Decimal256Type: FixedSizeBinaryType, IDecimalType { + // max int decimal 79228162514264337593543950335M : precision = 29 + // max scaled decimal 1.2345678901234567890123456789M : scale = 28 + public static readonly Decimal256Type SystemDefault = new(29, 28); public override ArrowTypeId TypeId => ArrowTypeId.Decimal256; public override string Name => "decimal256"; diff --git a/csharp/src/Apache.Arrow/Types/IArrowType.cs b/csharp/src/Apache.Arrow/Types/IArrowType.cs index 15c9a0244515..565a7863d665 100644 --- a/csharp/src/Apache.Arrow/Types/IArrowType.cs +++ b/csharp/src/Apache.Arrow/Types/IArrowType.cs @@ -58,6 +58,12 @@ public interface IArrowType void Accept(IArrowTypeVisitor visitor); bool IsFixedWidth { get; } - + } + + public interface IDecimalType : IArrowType + { + int ByteWidth { get; } + int Precision { get; } + int Scale { get; } } } diff --git a/csharp/src/Apache.Arrow/Types/StringType.cs b/csharp/src/Apache.Arrow/Types/StringType.cs index 33620aad9e9c..cb8dd69b8920 100644 --- a/csharp/src/Apache.Arrow/Types/StringType.cs +++ b/csharp/src/Apache.Arrow/Types/StringType.cs @@ -14,10 +14,13 @@ // limitations under the License. +using System.Text; + namespace Apache.Arrow.Types { public sealed class StringType : ArrowType { + public static readonly Encoding DefaultEncoding = Encoding.UTF8; public static StringType Default = new StringType(); public override ArrowTypeId TypeId => ArrowTypeId.String; diff --git a/csharp/src/Apache.Arrow/Types/TimeType.cs b/csharp/src/Apache.Arrow/Types/TimeType.cs index 9afa3fb62cdc..0f2666a3acc4 100644 --- a/csharp/src/Apache.Arrow/Types/TimeType.cs +++ b/csharp/src/Apache.Arrow/Types/TimeType.cs @@ -26,6 +26,7 @@ public enum TimeUnit public abstract class TimeType: FixedWidthType { + public static readonly Time64Type SystemDefault = new Time64Type(TimeUnit.Nanosecond); public TimeUnit Unit { get; } protected TimeType(TimeUnit unit) diff --git a/csharp/src/Apache.Arrow/Types/TimestampType.cs b/csharp/src/Apache.Arrow/Types/TimestampType.cs index 66b6ca60971c..5970143e16db 100644 --- a/csharp/src/Apache.Arrow/Types/TimestampType.cs +++ b/csharp/src/Apache.Arrow/Types/TimestampType.cs @@ -20,6 +20,7 @@ namespace Apache.Arrow.Types { public sealed class TimestampType : FixedWidthType { + public static readonly TimestampType SystemDefault = new TimestampType(TimeUnit.Nanosecond, "+00:00"); public static readonly TimestampType Default = new TimestampType(TimeUnit.Millisecond, "+00:00"); public override ArrowTypeId TypeId => ArrowTypeId.Timestamp; diff --git a/csharp/test/Apache.Arrow.Tests/BitUtilityTests.cs b/csharp/test/Apache.Arrow.Tests/BitUtilityTests.cs index 5e18716a0627..ef2906fb45e4 100644 --- a/csharp/test/Apache.Arrow.Tests/BitUtilityTests.cs +++ b/csharp/test/Apache.Arrow.Tests/BitUtilityTests.cs @@ -167,5 +167,60 @@ public void ReturnsZeroWhenSizeIsLessThanOrEqualToZero(int size) BitUtility.RoundUpToMultipleOf64(size)); } } + + public class ToByte + { + [Theory] + [InlineData(new bool[] { false, false, false, false, false, false, false, false }, 0b_00000000)] + [InlineData(new bool[] { false, false, false, false, false, false, false, true }, 0b_10000000)] + [InlineData(new bool[] { true, false, false, false, false, false, false, false }, 0b_00000001)] + [InlineData(new bool[] { true, true, true, true, true, true, true, true }, 0b_11111111)] + [InlineData(new bool[] { true, false, true, false, true, false, true, true }, 0b_11010101)] + public void ToByte_ReturnsExpectedValue(bool[] input, byte expected) + { + byte data = 0b_00000000; + BitUtility.SetBits(ref data, input); + Assert.Equal(expected, data); + } + + [Theory] + [InlineData(new byte[] { 0b_00000000, 0b_00000000 }, new bool[] { false, false, false, false, false, false, false, false })] + [InlineData(new byte[] { 0b_10000000, 0b_00000000 }, new bool[] { false, false, false, false, false, false, false, true })] + [InlineData(new byte[] { 0b_11111111, 0b_00000000 }, new bool[] { true, true, true, true, true, true, true, true })] + [InlineData(new byte[] { 0b_01010101, 0b_01000000 }, new bool[] { true, false, true, false, true, false, true, false, false, false, false, false, false, false, true, false })] + public void ToBytes_ReturnsExpectedValue(byte[] expected, bool[] bits) + { + byte[] bytes = new byte[2]; + BitUtility.SetBits(bytes.AsSpan(), bits); + Assert.Equal(expected, bytes); + } + } + + public class ToBits + { + [Theory] + [InlineData(0b_00000000, new bool[] { false, false, false, false, false, false, false, false })] + [InlineData(0b_00000001, new bool[] { true, false, false, false, false, false, false, false })] + [InlineData(0b_10000000, new bool[] { false, false, false, false, false, false, false, true })] + [InlineData(0b_11111111, new bool[] { true, true, true, true, true, true, true, true })] + [InlineData(0b_10101011, new bool[] { true, true, false, true, false, true, false, true })] + public void ToBits_ReturnsExpectedValue(byte input, bool[] expected) + { + bool[] result = new bool[8]; + BitUtility.ByteToBits(input, result); + Assert.Equal(expected, result); + } + + [Theory] + [InlineData(new byte[] { 0b_00000000, 0b_00000000 }, new bool[] { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false })] + [InlineData(new byte[] { 0b_10000000, 0b_00000000 }, new bool[] { false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false })] + [InlineData(new byte[] { 0b_11111111, 0b_00000000 }, new bool[] { true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false })] + [InlineData(new byte[] { 0b_01010101, 0b_01000000 }, new bool[] { true, false, true, false, true, false, true, false, false, false, false, false, false, false, true, false })] + public void ToBits_ReturnsExpectedValues(byte[] input, bool[] expected) + { + bool[] result = BitUtility.BytesToBits(input).ToArray(); + Assert.Equal(expected, result); + } + } } } diff --git a/csharp/test/Apache.Arrow.Tests/Builder/ArrayBuilderTests.cs b/csharp/test/Apache.Arrow.Tests/Builder/ArrayBuilderTests.cs new file mode 100644 index 000000000000..d869cbdeb642 --- /dev/null +++ b/csharp/test/Apache.Arrow.Tests/Builder/ArrayBuilderTests.cs @@ -0,0 +1,674 @@ +// 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.Threading.Tasks; +using Apache.Arrow.Arrays; +using Apache.Arrow.Builder; +using Apache.Arrow.Types; +using Xunit; + +namespace Apache.Arrow.Tests.Builder +{ + public class ArrayBuilderTests + { + [Fact] + public void ArrayBuilder_Should_AppendArrowArray() + { + var builder = new FixedBinaryArrayBuilder() as ArrayBuilder; + long[] values = new long[] { 0, 1, -12 }; + + var arrayBuilder = new FixedBinaryArrayBuilder(values.Length); + arrayBuilder.AppendValues(values); + + builder.AppendNull(); + builder.AppendArray(arrayBuilder.Build()); + + var array = builder.Build() as Int64Array; + + Assert.Equal(4, array.Length); + Assert.Equal(1, array.NullCount); + + Assert.False(array.IsValid(0)); + Assert.True(array.IsValid(2)); + + Assert.Equal(0L, array.GetValue(1)); + Assert.Equal(1L, array.GetValue(2)); + Assert.Equal(-12L, array.GetValue(3)); + } + + [Fact] + public void ArrayBuilder_Should_AppendArrowArraySlice() + { + var builder = new FixedBinaryArrayBuilder() as ArrayBuilder; + long?[] values = new long?[] { 0, 1, -12, null, 965 }; + + var arrayBuilder = new FixedBinaryArrayBuilder(values.Length); + arrayBuilder.AppendValues(values); + + builder.AppendNull(); + builder.AppendArray(arrayBuilder.Build().Slice(1, 3)); + + var array = builder.Build() as Int64Array; + + Assert.Equal(4, array.Length); + Assert.Equal(2, array.NullCount); + + Assert.False(array.IsValid(0)); + Assert.True(array.IsValid(2)); + + Assert.Equal(1L, array.GetValue(1)); + Assert.Equal(-12L, array.GetValue(2)); + Assert.Null(array.GetValue(3)); + } + } + + public class BooleanArrayBuilderTests + { + [Fact] + public void BooleanBuilder_Should_AppendBool() + { + var builder = new BooleanArrayBuilder(); + + builder.AppendValue(true); + builder.AppendNull(); + builder.AppendValues(new bool[] { true, false, true }); + builder.AppendNulls(3); + builder.AppendValue(false); + + var array = builder.Build(); + + Assert.Equal(9, array.Length); + Assert.Equal(4, array.NullCount); + + Assert.True(array.IsValid(0)); + Assert.False(array.IsValid(1)); + Assert.True(array.IsValid(2)); + Assert.True(array.IsValid(3)); + Assert.True(array.IsValid(4)); + Assert.False(array.IsValid(5)); + Assert.False(array.IsValid(6)); + Assert.False(array.IsValid(7)); + Assert.True(array.IsValid(8)); + + Assert.True(array.GetValue(0)); + Assert.Null(array.GetValue(1)); + Assert.True(array.GetValue(2)); + Assert.False(array.GetValue(3)); + Assert.True(array.GetValue(4)); + Assert.Null(array.GetValue(5)); + Assert.Null(array.GetValue(6)); + Assert.Null(array.GetValue(7)); + Assert.False(array.GetValue(8)); + } + + [Fact] + public void BooleanBuilder_Should_AppendArray() + { + var builder = new BooleanArrayBuilder(); + + builder.AppendValue(true); + + var vb = new BooleanArrayBuilder(); + vb.AppendNull(); + vb.AppendValues(new bool[] { true, false, true }); + vb.AppendNulls(3); + + builder.AppendArray(vb.Build()); + builder.AppendValue(false); + + var array = builder.Build(); + + Assert.Equal(9, array.Length); + Assert.Equal(4, array.NullCount); + + Assert.True(array.IsValid(0)); + Assert.False(array.IsValid(1)); + Assert.True(array.IsValid(2)); + Assert.True(array.IsValid(3)); + Assert.True(array.IsValid(4)); + Assert.False(array.IsValid(5)); + Assert.False(array.IsValid(6)); + Assert.False(array.IsValid(7)); + Assert.True(array.IsValid(8)); + + Assert.True(array.GetValue(0)); + Assert.Null(array.GetValue(1)); + Assert.True(array.GetValue(2)); + Assert.False(array.GetValue(3)); + Assert.True(array.GetValue(4)); + Assert.Null(array.GetValue(5)); + Assert.Null(array.GetValue(6)); + Assert.Null(array.GetValue(7)); + Assert.False(array.GetValue(8)); + } + } + + public class BinaryArrayBuilderTests + { + [Fact] + public void BinaryBuilder_Should_AppendBinary() + { + var builder = new BinaryArrayBuilder(); + + builder.AppendValue(123); + builder.AppendNull(); + builder.AppendValue(new byte[] { 1, 0, 12 }); + builder.AppendValues(new byte[][] { + new byte[] { }, + null, + new byte[] { 9, 42 } + }); + + var array = builder.Build(); + + Assert.Equal(6, array.Length); + Assert.Equal(2, array.NullCount); + + Assert.Equal(new byte[] { 123 }, array.GetBytes(0).ToArray()); + Assert.Equal(new byte[] { }, array.GetBytes(1).ToArray()); + Assert.Equal(new byte[] { 1, 0, 12 }, array.GetBytes(2).ToArray()); + Assert.Equal(new byte[] { }, array.GetBytes(3).ToArray()); + Assert.Equal(new byte[] { }, array.GetBytes(4).ToArray()); + Assert.Equal(new byte[] { 9, 42 }, array.GetBytes(5).ToArray()); + + Assert.True(array.IsValid(0)); + Assert.False(array.IsValid(1)); + Assert.False(array.IsValid(4)); + Assert.True(array.IsValid(5)); + } + + [Fact] + public void BinaryBuilder_Should_AppendArray() + { + var builder = new BinaryArrayBuilder(); + + var a0b = new BinaryArrayBuilder(); + a0b.AppendValues(new byte[][] { + new byte[] { }, + null, + new byte[] { 9, 42 } + }); + var a0 = a0b.Build(); + + var a1b = new BinaryArrayBuilder(); + a1b.AppendValues(new byte[][] { + null, + new byte[] { 1, 2, 3, 4 }, + new byte[] { 8, 7 } + }); + var a1 = a1b.Build(); + + builder.AppendNull(); + builder.AppendArray(a0); + builder.AppendArray(a1); + + var array = builder.Build(); + + Assert.Equal(7, array.Length); + Assert.Equal(3, array.NullCount); + + Assert.False(array.IsValid(0)); + Assert.True(array.IsValid(1)); + Assert.False(array.IsValid(2)); + Assert.True(array.IsValid(3)); + Assert.False(array.IsValid(4)); + Assert.True(array.IsValid(5)); + Assert.True(array.IsValid(6)); + + Assert.Equal(new byte[] { }, array.GetBytes(0).ToArray()); + Assert.Equal(new byte[] { }, array.GetBytes(1).ToArray()); + Assert.Equal(new byte[] { }, array.GetBytes(2).ToArray()); + Assert.Equal(new byte[] { 9, 42 }, array.GetBytes(3).ToArray()); + Assert.Equal(new byte[] { }, array.GetBytes(4).ToArray()); + Assert.Equal(new byte[] { 1, 2, 3, 4 }, array.GetBytes(5).ToArray()); + Assert.Equal(new byte[] { 8, 7 }, array.GetBytes(6).ToArray()); + } + + [Fact] + public void BinaryBuilder_Should_AppendArraySlice() + { + var builder = new BinaryArrayBuilder(); + + var a0b = new BinaryArrayBuilder(); + a0b.AppendValues(new byte[][] { + new byte[] { }, + null, + new byte[] { 9, 42 }, + new byte[] { 1, 2, 32, 4 } + }); + var a0 = a0b.Build(); + + var a1b = new BinaryArrayBuilder(); + a1b.AppendValues(new byte[][] { + null, + new byte[] { 1, 2, 3, 4 }, + new byte[] { 8, 7 }, + null + }); + var a1 = a1b.Build(); + + builder.AppendNull(); + builder.AppendArray(a0.Slice(2, 1)); + builder.AppendArray(a1.Slice(1, 3)); + + var array = builder.Build(); + + Assert.Equal(5, array.Length); + Assert.Equal(2, array.NullCount); + + Assert.False(array.IsValid(0)); + Assert.True(array.IsValid(1)); + Assert.True(array.IsValid(2)); + Assert.True(array.IsValid(3)); + Assert.False(array.IsValid(4)); + + Assert.Equal(new byte[] { }, array.GetBytes(0).ToArray()); + Assert.Equal(new byte[] { 9, 42 }, array.GetBytes(1).ToArray()); + Assert.Equal(new byte[] { 1, 2, 3, 4 }, array.GetBytes(2).ToArray()); + Assert.Equal(new byte[] { 8, 7 }, array.GetBytes(3).ToArray()); + Assert.Equal(new byte[] { }, array.GetBytes(4).ToArray()); + } + } + + public class StringArrayBuilderTests + { + [Fact] + public void StringBuilder_Should_AppendStrings() + { + var builder = new StringArrayBuilder(); + string[] values = new string[] { "abc123", "", null, "965" }; + builder.AppendValue("0"); + builder.AppendValues(values); + builder.AppendNull(); + var array = builder.Build(); + + Assert.Equal(6, array.Length); + Assert.Equal(2, array.NullCount); + + Assert.False(array.IsValid(3)); + Assert.True(array.IsValid(2)); + + Assert.Equal("0", array.GetString(0)); + Assert.Equal("abc123", array.GetString(1)); + Assert.Equal("", array.GetString(2)); + Assert.Null(array.GetString(3)); + Assert.Null(array.GetString(5)); + } + + [Fact] + public void StringBuilder_Should_AppendRepeatedStrings() + { + var builder = new StringArrayBuilder(); + builder.AppendValue("0"); + builder.AppendValues("azerty", 3); + builder.AppendNull(); + var array = builder.Build(); + + Assert.Equal(5, array.Length); + Assert.Equal(1, array.NullCount); + + Assert.False(array.IsValid(4)); + Assert.True(array.IsValid(2)); + + Assert.Equal("0", array.GetString(0)); + Assert.Equal("azerty", array.GetString(1)); + Assert.Equal("azerty", array.GetString(2)); + Assert.Equal("azerty", array.GetString(3)); + Assert.Null(array.GetString(4)); + } + + [Fact] + public void StringBuilder_Should_AppendRepeatedEmptyStrings() + { + var builder = new StringArrayBuilder(); + builder.AppendValue("0"); + builder.AppendValues("", 2); + builder.AppendNull(); + var array = builder.Build(); + + Assert.Equal(4, array.Length); + Assert.Equal(1, array.NullCount); + + Assert.False(array.IsValid(4)); + Assert.True(array.IsValid(2)); + + Assert.Equal("0", array.GetString(0)); + Assert.Equal("", array.GetString(1)); + Assert.Equal("", array.GetString(2)); + Assert.Null(array.GetString(4)); + } + + [Fact] + public void StringArrayBuilder_Should_Build() + { + var builder = new StringArrayBuilder(); + + builder.AppendValue(""); + builder.AppendNull(); + builder.AppendValue("def"); + + var array = builder.Build(); + + Assert.Equal(3, array.Length); + Assert.Equal(1, array.NullCount); + + Assert.Equal("", array.GetString(0)); + Assert.Null(array.GetString(1)); + Assert.Equal("def", array.GetString(2)); + + Assert.True(array.IsValid(0)); + Assert.False(array.IsValid(1)); + } + + [Fact] + public void StringBuilder_Should_AppendArrowArray() + { + var builder = new StringArrayBuilder(); + string[] values = new string[] { "0", "abc123", "", null, "965" }; + + var arrayBuilder = new StringArrayBuilder(values.Length); + arrayBuilder.AppendValues(values); + + builder.AppendNull(); + builder.AppendArray(arrayBuilder.Build()); + + var array = builder.Build(); + + Assert.Equal(6, array.Length); + Assert.Equal(2, array.NullCount); + + Assert.False(array.IsValid(0)); + Assert.True(array.IsValid(2)); + + Assert.Equal("0", array.GetString(1)); + Assert.Equal("abc123", array.GetString(2)); + Assert.Equal("", array.GetString(3)); + Assert.Null(array.GetString(4)); + } + + [Fact] + public void StringBuilder_Should_AppendArrowArraySlice() + { + var builder = new StringArrayBuilder(); + string[] values = new string[] { "0", "abc123", "", null, "965" }; + + var arrayBuilder = new StringArrayBuilder(values.Length); + arrayBuilder.AppendValues(values); + + builder.AppendNull(); + builder.AppendArray(arrayBuilder.Build().Slice(1, 3)); + + var array = builder.Build(); + + Assert.Equal(4, array.Length); + Assert.Equal(2, array.NullCount); + + Assert.False(array.IsValid(0)); + Assert.True(array.IsValid(2)); + + Assert.Equal("abc123", array.GetString(1)); + Assert.Equal("", array.GetString(2)); + Assert.Null(array.GetString(3)); + } + } + + public class ValueArrayBuilderTests + { + [Fact] + public void ValueArrayBuilder_Should_InferFromCSharp() + { + var builder = new FixedBinaryArrayBuilder(); + + builder.AppendValue(123); + builder.AppendValues(new int[] { 1, 0, -12 }); + builder.AppendNull(); + + var array = builder.Build() as Int32Array; + + Assert.Equal(5, array.Length); + Assert.Equal(1, array.NullCount); + + Assert.Equal(123, array.GetValue(0)); + Assert.Equal(1, array.GetValue(1)); + Assert.Equal(-12, array.GetValue(3)); + + Assert.True(array.IsValid(0)); + Assert.True(array.IsValid(2)); + Assert.False(array.IsValid(4)); + } + } + + public class FixedBinaryArrayBuilderTests + { + [Fact] + public void FixedSizeBinary_Should_InsertInArray() + { + var builder = new FixedBinaryArrayBuilder(new FixedSizeBinaryType(4)); + + builder.AppendValue(new byte[] { 1, 2, 3, 4, 5 }); + builder.AppendNull(); + builder.AppendBytes(new byte[][] + { + new byte[] { }, + null, + new byte[] { 1, 5 }, + new byte[] { 9, 8, 7, 6, 5, 4 } + }); + var array = builder.Build() as FixedSizeBinaryArray; + + Assert.Equal(6, array.Length); + Assert.Equal(2, array.NullCount); + + Assert.Equal(new byte[] { 1, 2, 3, 4 }, array.GetBytes(0).ToArray()); + Assert.Equal(new byte[] { }, array.GetBytes(1).ToArray()); + Assert.Equal(new byte[] { 0, 0, 0, 0 }, array.GetBytes(2).ToArray()); + Assert.Equal(new byte[] { 1, 5, 0, 0 }, array.GetBytes(4).ToArray()); + Assert.Equal(new byte[] { 9, 8, 7, 6 }, array.GetBytes(5).ToArray()); + + Assert.True(array.IsValid(0)); + Assert.False(array.IsValid(1)); + Assert.True(array.IsValid(2)); + Assert.False(array.IsValid(3)); + Assert.True(array.IsValid(4)); + } + } + + public class StructArrayBuilderTests + { + [Fact] + public void StructArrayBuilder_Should_Build() + { + var builder = new StructArrayBuilder(); + + // Start new valid block, need to fill all builders + builder.Append(); + builder.GetBuilderAs(0).AppendValue("abc"); + builder.GetBuilderAs>(1).AppendValue(1); + // Append null block + builder.AppendNull(); + + StructArray array = builder.Build(); + + Assert.IsType(array); + Assert.Equal(2, array.Length); + Assert.Equal(1, array.NullCount); + + Assert.True(array.IsValid(0)); + Assert.False(array.IsValid(1)); + } + + [Fact] + public void StructArrayBuilder_Should_AppendScalar() + { + var builder = new StructArrayBuilder(); + var scalar = new StructScalar(builder.DataType, new IScalar[] + { + new StringScalar("abc"), new Int32Scalar(123) + }); + + builder.AppendNull(); + builder.AppendValue(scalar); + builder.AppendNull(); + + StructArray array = builder.Build(); + var names = array.Fields[0] as StringArray; + var int32s = array.Fields[1] as Int32Array; + + Assert.Equal(3, array.Length); + Assert.Equal(2, array.NullCount); + + Assert.Equal("abc", names.GetString(1)); + Assert.Equal(123, int32s.GetValue(1)); + + Assert.False(array.IsValid(0)); + Assert.True(array.IsValid(1)); + Assert.False(array.IsValid(2)); + } + + [Fact] + public void StructArrayBuilder_Should_BuildRecordBatch() + { + var builder = new StructArrayBuilder(); + var scalar = new StructScalar(builder.DataType, new IScalar[] + { + new StringScalar("abc"), new Int32Scalar(123) + }); + + builder.AppendNull(); + builder.AppendValue(scalar); + builder.AppendNull(); + + var batch = builder.BuildRecordBatch(); + var names = batch.Column(0) as StringArray; + var int32s = batch.Column(1) as Int32Array; + + Assert.Equal(3, batch.Length); + + Assert.Equal("abc", names.GetString(1)); + Assert.Equal(123, int32s.GetValue(1)); + } + + [Fact] + public async Task StructArrayBuilder_Should_BuildRecordBatchAsync() + { + var builder = new StructArrayBuilder(); + var scalar = new StructScalar(builder.DataType, new IScalar[] + { + new StringScalar("abc"), new Int32Scalar(123) + }); + + builder.AppendNull(); + builder.AppendValue(scalar); + builder.AppendNull(); + + var batch = await builder.BuildRecordBatchAsync(); + var names = batch.Column(0) as StringArray; + var int32s = batch.Column(1) as Int32Array; + + Assert.Equal(3, batch.Length); + + Assert.Equal("abc", names.GetString(1)); + Assert.Equal(123, int32s.GetValue(1)); + } + + private static RecordBatch GetRecordBatch() + { + var builder = new StructArrayBuilder(); + var scalar = new StructScalar(builder.DataType, new IScalar[] + { + new StringScalar("abc"), new Int32Scalar(123) + }); + + builder.AppendNull(); + builder.AppendValue(scalar); + builder.AppendNull(); + + return builder.BuildRecordBatch(); + } + + [Fact] + public void StructArrayBuilder_Should_AppendRecordBatch() + { + var builder = new StructArrayBuilder(); + + builder.AppendNull(); + builder.AppendBatch(GetRecordBatch()); + builder.AppendNull(); + + var batch = builder.BuildRecordBatch(); + var names = batch.Column(0) as StringArray; + var int32s = batch.Column(1) as Int32Array; + + Assert.Equal(5, batch.Length); + + Assert.Equal("abc", names.GetString(2)); + Assert.Equal(123, int32s.GetValue(2)); + } + + [Fact] + public async Task StructArrayBuilder_Should_AppendRecordBatchAsync() + { + var builder = new StructArrayBuilder(); + + builder.AppendNull(); + builder.AppendBatch(GetRecordBatch()); + builder.AppendNull(); + + var batch = await builder.BuildRecordBatchAsync(); + var names = batch.Column(0) as StringArray; + var int32s = batch.Column(1) as Int32Array; + + Assert.Equal(5, batch.Length); + + Assert.Equal("abc", names.GetString(2)); + Assert.Equal(123, int32s.GetValue(2)); + } + } + + public class ListArrayBuilderTests + { + [Fact] + public void ListArrayBuilder_Should_Build() + { + var builder = new ListArrayBuilder(); + + builder.AppendNulls(3); + builder.AppendValue(new long[] { 1, 0, -1 }); + builder.AppendNull(); + builder.AppendValues(new long[][] + { + new long[] { 12, 3 }, + new long[] { } + }); + var array = builder.Build(); + + Assert.Equal(7, array.Length); + Assert.Equal(4, array.NullCount); + + Assert.False(array.IsValid(0)); + Assert.False(array.IsValid(1)); + Assert.False(array.IsValid(2)); + Assert.True(array.IsValid(3)); + Assert.False(array.IsValid(4)); + Assert.True(array.IsValid(5)); + } + } + + public struct TestStruct + { + public string Name { get; set; } + public int Value { get; set; } + } +} diff --git a/csharp/test/Apache.Arrow.Tests/Builder/BufferBuilderTests.cs b/csharp/test/Apache.Arrow.Tests/Builder/BufferBuilderTests.cs new file mode 100644 index 000000000000..febd19b7e1b2 --- /dev/null +++ b/csharp/test/Apache.Arrow.Tests/Builder/BufferBuilderTests.cs @@ -0,0 +1,180 @@ +// 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 Apache.Arrow.Builder; +using Xunit; + +namespace Apache.Arrow.Tests.Builder +{ + public class BufferBuilderTests + { + [Fact] + public void BufferBuilder_Should_AppendBytes() + { + var builder = new BufferBuilder(8); + + builder.AppendByte(0x01); + + Assert.Equal(1, builder.ByteLength); + Assert.Equal(0, builder.BitOffset); + + builder.AppendBytes(new byte[] { 0x02, 0x03 }); + + Assert.Equal(3, builder.ByteLength); + Assert.Equal(0, builder.BitOffset); + + var built = builder.Build(); + + Assert.Equal(0x01, built.Span[0]); + Assert.Equal(0x02, built.Span[1]); + Assert.Equal(0x03, built.Span[2]); + Assert.Equal(0x00, built.Span[3]); + + Assert.Equal(64, built.Length); + } + + [Fact] + public void BufferBuilder_Should_AppendBits() + { + var builder = new BufferBuilder(8); + + builder.AppendBit(true); + + Assert.Equal(0, builder.ByteLength); + Assert.Equal(1, builder.BitOffset); + + builder.AppendBits(new bool[] { true, false, true }); + + Assert.Equal(0, builder.ByteLength); + Assert.Equal(4, builder.BitOffset); + + builder.AppendBits(new bool[] { true, false, true, false, true, true }); + + Assert.Equal(1, builder.ByteLength); + Assert.Equal(2, builder.BitOffset); + + builder.AppendBits(new bool[] { false, false, true }); + + Assert.Equal(1, builder.ByteLength); + Assert.Equal(5, builder.BitOffset); + + var built = builder.Build(); + + Assert.Equal(0b_01011011, built.Span[0]); + Assert.Equal(0b_00010011, built.Span[1]); + Assert.Equal(0b_00000000, built.Span[2]); + + Assert.True(BitUtility.GetBit(built.Span, 9)); + + Assert.Equal(64, built.Length); + } + + [Fact] + public void BufferBuilder_Should_AppendBitsLargeRange() + { + var builder = new BufferBuilder(8); + + builder.AppendBit(true); + builder.AppendBits(new bool[] { false, true, false, true, false, true }); + builder.AppendBits(new bool[] { false, true, false, true, false, true, false, true, false, true, false, true }); + + var built = builder.Build(); + + Assert.True(BitUtility.GetBit(built.Span, 0)); + Assert.False(BitUtility.GetBit(built.Span, 1)); + Assert.True(BitUtility.GetBit(built.Span, 2)); + Assert.False(BitUtility.GetBit(built.Span, 17)); + Assert.True(BitUtility.GetBit(built.Span, 18)); + } + + [Fact] + public void BufferBuilder_Should_AppendBitRepetitionLarge() + { + var builder = new BufferBuilder(8); + + builder.AppendBits(true, 12); + builder.AppendBit(false); + + var built = builder.Build(); + + Assert.True(BitUtility.GetBit(built.Span, 4)); + Assert.True(BitUtility.GetBit(built.Span, 5)); + Assert.True(BitUtility.GetBit(built.Span, 6)); + Assert.True(BitUtility.GetBit(built.Span, 7)); + Assert.False(BitUtility.GetBit(built.Span, 12)); + } + + [Fact] + public void BufferBuilder_Should_AppendBitRepetitionLarge_AfterAppend() + { + var builder = new BufferBuilder(8); + + builder.AppendBit(false); + builder.AppendBit(false); + builder.AppendBits(true, 12); + builder.AppendBit(false); + + var built = builder.Build(); + + Assert.False(BitUtility.GetBit(built.Span, 0)); + Assert.False(BitUtility.GetBit(built.Span, 1)); + Assert.True(BitUtility.GetBit(built.Span, 5)); + Assert.True(BitUtility.GetBit(built.Span, 6)); + Assert.True(BitUtility.GetBit(built.Span, 7)); + Assert.False(BitUtility.GetBit(built.Span, 14)); + } + + [Fact] + public void BufferBuilder_Should_AppendBitRepetition() + { + var builder = new BufferBuilder(8); + + builder.AppendBit(true); + builder.AppendBits(false, 3); + builder.AppendBits(true, 4); + + var built = builder.Build(); + + Assert.True(BitUtility.GetBit(built.Span, 0)); + Assert.False(BitUtility.GetBit(built.Span, 1)); + Assert.False(BitUtility.GetBit(built.Span, 2)); + Assert.False(BitUtility.GetBit(built.Span, 3)); + Assert.True(BitUtility.GetBit(built.Span, 4)); + Assert.True(BitUtility.GetBit(built.Span, 5)); + Assert.True(BitUtility.GetBit(built.Span, 6)); + Assert.True(BitUtility.GetBit(built.Span, 7)); + } + + [Fact] + public void TypedBufferBuilder_Should_AppendStructs() + { + var builder = new TypedBufferBuilder(8); + + builder.AppendValue(123); + builder.AppendValues(new int[] { 0, -1 }); + + var built = builder.Build(); + var results = built.Span.CastTo(); + + Assert.Equal(123, results[0]); + Assert.Equal(0, results[1]); + Assert.Equal(-1, results[2]); + Assert.Equal(0, results[3]); + + Assert.Equal(64, built.Length); + } + } +} diff --git a/csharp/test/Apache.Arrow.Tests/Extensions/DateTimeOffsetExtensions.cs b/csharp/test/Apache.Arrow.Tests/Extensions/DateTimeOffsetExtensions.cs deleted file mode 100644 index 4375c39cdfaf..000000000000 --- a/csharp/test/Apache.Arrow.Tests/Extensions/DateTimeOffsetExtensions.cs +++ /dev/null @@ -1,40 +0,0 @@ -// 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.Collections.Generic; -using System.Text; - -namespace Apache.Arrow.Tests -{ - public static class DateTimeOffsetExtensions - { - public static DateTimeOffset Truncate(this DateTimeOffset dateTimeOffset, TimeSpan offset) - { - if (offset == TimeSpan.Zero) - { - return dateTimeOffset; - } - - if (dateTimeOffset == DateTimeOffset.MinValue || dateTimeOffset == DateTimeOffset.MaxValue) - { - return dateTimeOffset; - } - - return dateTimeOffset.AddTicks(-(dateTimeOffset.Ticks % offset.Ticks)); - } - - } -} diff --git a/csharp/test/Apache.Arrow.Tests/Extensions/DateTimeOffsetExtensionsTests.cs b/csharp/test/Apache.Arrow.Tests/Extensions/DateTimeOffsetExtensionsTests.cs new file mode 100644 index 000000000000..27f3277afb37 --- /dev/null +++ b/csharp/test/Apache.Arrow.Tests/Extensions/DateTimeOffsetExtensionsTests.cs @@ -0,0 +1,78 @@ +// 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 Xunit; + +namespace Apache.Arrow.Tests +{ + public class DateTimeOffsetExtensionsTests + { + [Fact] + public void UnixEpoch_ShoudleBe_Right() + { + // Assert + Assert.Equal(DateTimeOffsetExtensions.UnixEpoch, new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero)); + } + + [Fact] + public void FromUnixTimeSeconds_ReturnsExpectedDateTimeOffset() + { + // Assert + Assert.Equal(DateTimeOffsetExtensions.UnixEpoch.AddSeconds(1), DateTimeOffsetExtensions.FromUnixTimeSeconds(1)); + Assert.Equal(DateTimeOffsetExtensions.UnixEpoch.AddSeconds(-1), DateTimeOffsetExtensions.FromUnixTimeSeconds(-1)); + } + + [Fact] + public void FromUnixTimeMilliseconds_ReturnsExpectedDateTimeOffset() + { + // Assert + Assert.Equal(DateTimeOffsetExtensions.UnixEpoch.AddSeconds(1), DateTimeOffsetExtensions.FromUnixTimeMilliseconds(1000)); + Assert.Equal(DateTimeOffsetExtensions.UnixEpoch.AddSeconds(-1), DateTimeOffsetExtensions.FromUnixTimeMilliseconds(-1000)); + } + + [Fact] + public void FromUnixTimeMicroseconds_ReturnsExpectedDateTimeOffset() + { + // Assert + Assert.Equal(DateTimeOffsetExtensions.UnixEpoch.AddSeconds(1), DateTimeOffsetExtensions.FromUnixTimeMicroseconds(1000000)); + Assert.Equal(DateTimeOffsetExtensions.UnixEpoch.AddSeconds(-1), DateTimeOffsetExtensions.FromUnixTimeMicroseconds(-1000000)); + } + + [Fact] + public void FromUnixTimeNanoseconds_ReturnsExpectedDateTimeOffset() + { + // Assert + Assert.Equal(DateTimeOffsetExtensions.UnixEpoch.AddSeconds(1), DateTimeOffsetExtensions.FromUnixTimeNanoseconds(1000000000)); + Assert.Equal(DateTimeOffsetExtensions.UnixEpoch.AddSeconds(-1), DateTimeOffsetExtensions.FromUnixTimeNanoseconds(-1000000000)); + } + + [Fact] + public void ToUnixTimeMicroseconds_ReturnsExpectedValue() + { + // Assert + Assert.Equal(123000000, DateTimeOffsetExtensions.UnixEpoch.AddSeconds(123).ToUnixTimeMicroseconds()); + Assert.Equal(-123000000, DateTimeOffsetExtensions.UnixEpoch.AddSeconds(-123).ToUnixTimeMicroseconds()); + } + + [Fact] + public void ToUnixTimeNanoseconds_ReturnsExpectedValue() + { + // Assert + Assert.Equal(123000000000, DateTimeOffsetExtensions.UnixEpoch.AddSeconds(123).ToUnixTimeNanoseconds()); + Assert.Equal(-123000000000, DateTimeOffsetExtensions.UnixEpoch.AddSeconds(-123).ToUnixTimeNanoseconds()); + } + } +} diff --git a/csharp/test/Apache.Arrow.Tests/ScalarTests.cs b/csharp/test/Apache.Arrow.Tests/ScalarTests.cs new file mode 100644 index 000000000000..2a311a6afb7f --- /dev/null +++ b/csharp/test/Apache.Arrow.Tests/ScalarTests.cs @@ -0,0 +1,559 @@ +// 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 Apache.Arrow.Types; +using Xunit; + +namespace Apache.Arrow.Tests +{ + public class IntegerScalarTests + { + [Fact] + public void UInt8Scalar_Should_BuildFromDotNet() + { + byte expected = 128; + var value = new UInt8Scalar(expected); + byte casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(UInt8Type.Default, value.Type); + Assert.Equal(new byte[] { 128 }, value.AsBytes().ToArray()); + } + + [Fact] + public void UInt8Scalar_Should_BuildFromMaxValue() + { + byte expected = byte.MaxValue; + var value = new UInt8Scalar(expected); + byte casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(UInt8Type.Default, value.Type); + Assert.Equal(new byte[] { byte.MaxValue }, value.AsBytes().ToArray()); + } + + [Fact] + public void UInt8Scalar_Should_BuildFromZero() + { + byte expected = 0; + var value = new UInt8Scalar(expected); + byte casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(UInt8Type.Default, value.Type); + Assert.Equal(new byte[] { 0 }, value.AsBytes().ToArray()); + } + + [Fact] + public void Int8Scalar_Should_BuildFromDotNet() + { + sbyte expected = -56; + var value = new Int8Scalar(expected); + sbyte casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(Int8Type.Default, value.Type); + Assert.Equal(new byte[] { 200 }, value.AsBytes().ToArray()); + } + + [Fact] + public void Int8Scalar_Should_BuildFromMaxValue() + { + sbyte expected = sbyte.MaxValue; + var value = new Int8Scalar(expected); + sbyte casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(Int8Type.Default, value.Type); + Assert.Equal(new byte[] { 127 }, value.AsBytes().ToArray()); + } + + [Fact] + public void Int8Scalar_Should_BuildFromMinValue() + { + sbyte expected = sbyte.MinValue; + var value = new Int8Scalar(expected); + sbyte casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(Int8Type.Default, value.Type); + Assert.Equal(new byte[] { 128 }, value.AsBytes().ToArray()); + } + + [Fact] + public void Int16Scalar_Should_BuildFromDotNet() + { + short expected = -3456; + var value = new Int16Scalar(expected); + short casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(Int16Type.Default, value.Type); + Assert.Equal(new byte[] { 128, 242 }, value.AsBytes().ToArray()); + } + + [Fact] + public void Int16Scalar_Should_BuildFromMaxValue() + { + short expected = short.MaxValue; + var value = new Int16Scalar(expected); + short casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(Int16Type.Default, value.Type); + Assert.Equal(new byte[] { 255, 127 }, value.AsBytes().ToArray()); + } + + [Fact] + public void Int16Scalar_Should_BuildFromMinValue() + { + short expected = short.MinValue; + var value = new Int16Scalar(expected); + short casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(Int16Type.Default, value.Type); + Assert.Equal(new byte[] { 0, 128 }, value.AsBytes().ToArray()); + } + + [Fact] + public void UInt16Scalar_Should_BuildFromDotNet() + { + ushort expected = 56789; + var value = new UInt16Scalar(expected); + ushort casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(UInt16Type.Default, value.Type); + Assert.Equal(new byte[] { 213, 221 }, value.AsBytes().ToArray()); + } + + [Fact] + public void UInt16Scalar_Should_BuildFromMaxValue() + { + ushort expected = ushort.MaxValue; + var value = new UInt16Scalar(expected); + ushort casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(UInt16Type.Default, value.Type); + Assert.Equal(new byte[] { 255, 255 }, value.AsBytes().ToArray()); + } + + [Fact] + public void UInt16Scalar_Should_BuildFromZero() + { + ushort expected = 0; + var value = new UInt16Scalar(expected); + ushort casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(UInt16Type.Default, value.Type); + Assert.Equal(new byte[] { 0, 0 }, value.AsBytes().ToArray()); + } + + [Fact] + public void Int32Scalar_Should_BuildFromDotNet() + { + int expected = 123456789; + var value = new Int32Scalar(expected); + int casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(Int32Type.Default, value.Type); + Assert.Equal(new byte[] { 21, 205, 91, 7 }, value.AsBytes().ToArray()); + } + + [Fact] + public void Int32Scalar_Should_BuildFromMaxValue() + { + int expected = int.MaxValue; + var value = new Int32Scalar(expected); + int casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(Int32Type.Default, value.Type); + Assert.Equal(new byte[] { 255, 255, 255, 127 }, value.AsBytes().ToArray()); + } + + [Fact] + public void Int32Scalar_Should_BuildFromMinValue() + { + int expected = int.MinValue; + var value = new Int32Scalar(expected); + int casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(Int32Type.Default, value.Type); + Assert.Equal(new byte[] { 0, 0, 0, 128 }, value.AsBytes().ToArray()); + } + + [Fact] + public void UInt32Scalar_Should_BuildFromDotNet() + { + uint expected = 3456789012; + var value = new UInt32Scalar(expected); + uint casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(UInt32Type.Default, value.Type); + Assert.Equal(new byte[] { 20, 106, 10, 206 }, value.AsBytes().ToArray()); + } + + [Fact] + public void UInt32Scalar_Should_BuildFromMaxValue() + { + uint expected = uint.MaxValue; + var value = new UInt32Scalar(expected); + uint casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(UInt32Type.Default, value.Type); + Assert.Equal(new byte[] { 255, 255, 255, 255 }, value.AsBytes().ToArray()); + } + + [Fact] + public void UInt32Scalar_Should_BuildFromZero() + { + uint expected = 0; + var value = new UInt32Scalar(expected); + uint casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(UInt32Type.Default, value.Type); + Assert.Equal(new byte[] { 0, 0, 0, 0 }, value.AsBytes().ToArray()); + } + + [Fact] + public void Int64Scalar_Should_BuildFromDotNet() + { + long expected = 1234567890123456789; + var value = new Int64Scalar(expected); + long casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(Int64Type.Default, value.Type); + Assert.Equal(new byte[] { 21, 129, 233, 125, 244, 16, 34, 17 }, value.AsBytes().ToArray()); + } + + [Fact] + public void Int64Scalar_Should_BuildFromMaxValue() + { + long expected = long.MaxValue; + var value = new Int64Scalar(expected); + long casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(Int64Type.Default, value.Type); + Assert.Equal(new byte[] { 255, 255, 255, 255, 255, 255, 255, 127 }, value.AsBytes().ToArray()); + } + + [Fact] + public void Int64Scalar_Should_BuildFromMinValue() + { + long expected = long.MinValue; + var value = new Int64Scalar(expected); + long casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(Int64Type.Default, value.Type); + Assert.Equal(new byte[] { 0, 0, 0, 0, 0, 0, 0, 128 }, value.AsBytes().ToArray()); + } + + [Fact] + public void UInt64Scalar_Should_BuildFromDotNet() + { + ulong expected = 12345678901234567890; + var value = new UInt64Scalar(expected); + ulong casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(UInt64Type.Default, value.Type); + Assert.Equal(new byte[] { 210, 10, 31, 235, 140, 169, 84, 171 }, value.AsBytes().ToArray()); + } + + [Fact] + public void UInt64Scalar_Should_BuildFromMaxValue() + { + ulong expected = ulong.MaxValue; + var value = new UInt64Scalar(expected); + ulong casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(UInt64Type.Default, value.Type); + Assert.Equal(new byte[] { 255, 255, 255, 255, 255, 255, 255, 255 }, value.AsBytes().ToArray()); + } + + [Fact] + public void UInt64Scalar_Should_BuildFromZero() + { + ulong expected = 0; + var value = new UInt64Scalar(expected); + ulong casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(UInt64Type.Default, value.Type); + Assert.Equal(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }, value.AsBytes().ToArray()); + } + } + + public class FloatScalarTests + { + [Fact] + public void FloatScalar_Should_BuildFromDotNet() + { + float expected = 1234.567f; + var value = new FloatScalar(expected); + float casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(FloatType.Default, value.Type); + Assert.Equal(new byte[] { 37, 82, 154, 68 }, value.AsBytes().ToArray()); + } + + [Fact] + public void FloatScalar_Should_BuildFromMaxValue() + { + float expected = float.MaxValue; + var value = new FloatScalar(expected); + + Assert.Equal(expected, value.DotNet); + Assert.Equal(FloatType.Default, value.Type); + Assert.Equal(new byte[] { 255, 255, 127, 127 }, value.AsBytes().ToArray()); + } + + [Fact] + public void FloatScalar_Should_BuildFromMinValue() + { + float expected = float.MinValue; + var value = new FloatScalar(expected); + float casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(FloatType.Default, value.Type); + Assert.Equal(new byte[] { 255, 255, 127, 255 }, value.AsBytes().ToArray()); + } + } + + public class HalfScalarTests + { + [Fact] + public void HalfScalar_Should_BuildFromDotNet() + { + Half expected = Half.Epsilon; + var value = new HalfFloatScalar(expected); + Half casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(HalfFloatType.Default, value.Type); + Assert.Equal(new byte[] { 1, 0 }, value.AsBytes().ToArray()); + } + + [Fact] + public void HalfScalar_Should_BuildFromMaxValue() + { + Half expected = Half.MaxValue; + var value = new HalfFloatScalar(expected); + Half casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(HalfFloatType.Default, value.Type); + Assert.Equal(new byte[] { 255, 123 }, value.AsBytes().ToArray()); + } + + [Fact] + public void HalfScalar_Should_BuildFromMinValue() + { + Half expected = Half.MinValue; + var value = new HalfFloatScalar(expected); + Half casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(HalfFloatType.Default, value.Type); + Assert.Equal(new byte[] { 255, 251 }, value.AsBytes().ToArray()); + } + } + + public class DoubleScalarTests + { + [Fact] + public void DoubleScalar_Should_BuildFromDotNet() + { + double expected = 1234.56789; + var value = new DoubleScalar(expected); + double casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(DoubleType.Default, value.Type); + Assert.Equal(new byte[] { 231, 198, 244, 132, 69, 74, 147, 64 }, value.AsBytes().ToArray()); + } + + [Fact] + public void DoubleScalar_Should_BuildFromMaxValue() + { + double expected = double.MaxValue; + var value = new DoubleScalar(expected); + double casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(DoubleType.Default, value.Type); + Assert.Equal(new byte[] { 255, 255, 255, 255, 255, 255, 239, 127 }, value.AsBytes().ToArray()); + } + + [Fact] + public void DoubleScalar_Should_BuildFromMinValue() + { + double expected = double.MinValue; + var value = new DoubleScalar(expected); + double casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(DoubleType.Default, value.Type); + Assert.Equal(new byte[] { 255, 255, 255, 255, 255, 255, 239, 255 }, value.AsBytes().ToArray()); + } + } + + public class Decimal128ScalarTests + { + [Fact] + public void Decimal128Scalar_Should_BuildWithCustomType() + { + decimal expected = 123.00001m; + var value = new Decimal128Scalar(new Decimal128Type(15,5), expected); + decimal casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(new byte[] { + 225, 174, 187, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }, value.AsBytes().ToArray()); + } + + [Fact] + public void Decimal128Scalar_Should_BuildFromDotNet() + { + decimal expected = 123.00001m; + var value = new Decimal128Scalar(expected); + decimal casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(Decimal128Type.Default, value.Type); + Assert.Equal(expected, value.DotNet); + Assert.Equal(new byte[] { + 16, 53, 95, 163, 28, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }, value.AsBytes().ToArray()); + } + + [Fact] + public void Decimal128Scalar_Should_BuildFromNegativeDotNet() + { + decimal expected = -987.00001m; + var value = new Decimal128Scalar(expected); + decimal casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(Decimal128Type.Default, value.Type); + Assert.Equal(expected, value.DotNet); + Assert.Equal(new byte[] { + 240, 10, 55, 50, 26, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 + }, value.AsBytes().ToArray()); + } + } + + public class Decimal256ScalarTests + { + [Fact] + public void Decimal256Scalar_Should_BuildWithCustomType() + { + decimal expected = 123.000000000000000000000001m; + var value = new Decimal256Scalar(new Decimal256Type(32, 27), expected); + decimal casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(new byte[] { + 232, 3, 0, 120, 67, 157, 45, 201, 32, 55, 111, 141, 1, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }, value.AsBytes().ToArray()); + } + + [Fact] + public void Decimal256Scalar_Should_BuildFromDotNet() + { + decimal expected = 123.000000000000000000000001m; + var value = new Decimal256Scalar(expected); + var bytes = new byte[] { + 16, 39, 0, 176, 162, 36, 200, 219, 71, 39, 88, 134, 15, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + decimal casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(Decimal256Type.SystemDefault, value.Type); + Assert.Equal(bytes, value.AsBytes().ToArray()); + } + + [Fact] + public void Decimal256Scalar_Should_BuildFromNegativeDotNet() + { + decimal expected = -987.000000000000000000000001m; + var value = new Decimal256Scalar(expected); + var bytes = new byte[] { + 240, 216, 255, 79, 199, 211, 79, 103, 166, 90, 79, 108, 131, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 + }; + decimal casted = value; + + Assert.Equal(casted, value.DotNet); + Assert.Equal(expected, value.DotNet); + Assert.Equal(Decimal256Type.SystemDefault, value.Type); + Assert.Equal(bytes, value.AsBytes().ToArray()); + } + } +} diff --git a/csharp/test/Apache.Arrow.Tests/TypeTests.cs b/csharp/test/Apache.Arrow.Tests/TypeTests.cs index c279d6984796..4cc9c23dd26a 100644 --- a/csharp/test/Apache.Arrow.Tests/TypeTests.cs +++ b/csharp/test/Apache.Arrow.Tests/TypeTests.cs @@ -128,4 +128,154 @@ public void TestListTypeConstructor() } + + public class FieldBuild + { + [Fact] + public void DataType_Should_ThrowInvalidCastException() + { + // Arrange + var builder = new Field.Builder().Name("test"); + + // Act & Assert + try + { + builder.DataType(typeof(object)); + } + catch (InvalidCastException e) + { + Assert.Equal($"Cannot convert System.Type<{typeof(object)}> to ArrowType", e.Message); + } + } + + [Fact] + public void DataType_Should_InferDataType_From_NullableInt() + { + // Arrange + Field builder = new Field.Builder().Name("test").DataType(typeof(int?)).Build(); + + // Assert + Assert.Equal(typeof(Int32Type), builder.DataType.GetType()); + Assert.True(builder.IsNullable); + } + + [Fact] + public void DataType_Should_InferDataType_From_Int() + { + // Arrange + Field builder = new Field.Builder().Name("test").DataType(typeof(int)).Build(); + + // Assert + Assert.Equal(typeof(Int32Type), builder.DataType.GetType()); + Assert.False(builder.IsNullable); + } + + [Fact] + public void DataType_Should_InferDataType_From_NullableDecimal() + { + // Arrange + Field builder = new Field.Builder().Name("test").DataType(typeof(decimal?)).Build(); + var dtype = builder.DataType as Decimal256Type; + + // Assert + Assert.Equal(typeof(Decimal256Type), builder.DataType.GetType()); + Assert.Equal(29, dtype.Precision); + Assert.Equal(28, dtype.Scale); + Assert.True(builder.IsNullable); + } + + [Fact] + public void DataType_Should_InferDataType_From_Decimal() + { + // Arrange + Field builder = new Field.Builder().Name("test").DataType(typeof(decimal)).Build(); + var dtype = builder.DataType as Decimal256Type; + + // Assert + Assert.Equal(typeof(Decimal256Type), builder.DataType.GetType()); + Assert.Equal(29, dtype.Precision); + Assert.Equal(28, dtype.Scale); + Assert.False(builder.IsNullable); + } + +#if NETCOREAPP3_1_OR_GREATER + [Fact] + public void DataType_Should_InferDataType_From_IEnumerable() + { + // Arrange + Field builder = new Field.Builder().Name("test").DataType(typeof(IEnumerable)).Build(); + var dtype = builder.DataType as ListType; + Field child = dtype.Fields[0]; + + // Assert + Assert.Equal(typeof(ListType), builder.DataType.GetType()); + Assert.Equal(typeof(StringType), child.DataType.GetType()); + Assert.Equal("item", child.Name); + Assert.True(dtype.Fields[0].IsNullable); + } + + [Fact] + public void DataType_Should_InferDataType_From_Structure() + { + // Arrange + Field field = new Field.Builder().DataType(typeof(TestStruct)).Build(); + var dtype = field.DataType as StructType; + Field name = dtype.Fields[0]; + Field value = dtype.Fields[1]; + Field abc = dtype.Fields[2]; + + // Assert + Assert.Equal(3, dtype.Fields.Count); + Assert.False(field.IsNullable); + Assert.Equal("TestStruct", field.Name); + + Assert.Equal(typeof(StringType), name.DataType.GetType()); + Assert.Equal("Name", name.Name); + Assert.True(name.IsNullable); + + Assert.Equal(typeof(Decimal256Type), value.DataType.GetType()); + Assert.Equal("value", value.Name); + Assert.True(value.IsNullable); + + Assert.Equal(typeof(Int32Type), abc.DataType.GetType()); + Assert.Equal("aBc", abc.Name); + Assert.False(abc.IsNullable); + } + + [Fact] + public void DataType_Should_InferDataType_From_NullableStructure() + { + // Arrange + Field field = new Field.Builder().DataType(typeof(TestStruct?)).Build(); + var dtype = field.DataType as StructType; + Field name = dtype.Fields[0]; + Field value = dtype.Fields[1]; + Field abc = dtype.Fields[2]; + + // Assert + Assert.Equal(3, dtype.Fields.Count); + Assert.True(field.IsNullable); + Assert.Equal("TestStruct", field.Name); + + Assert.Equal(typeof(StringType), name.DataType.GetType()); + Assert.Equal("Name", name.Name); + Assert.True(name.IsNullable); + + Assert.Equal(typeof(Decimal256Type), value.DataType.GetType()); + Assert.Equal("value", value.Name); + Assert.True(value.IsNullable); + + Assert.Equal(typeof(Int32Type), abc.DataType.GetType()); + Assert.Equal("aBc", abc.Name); + Assert.False(abc.IsNullable); + } +#endif + + public struct TestStruct + { + public string Name { get; set; } + public decimal? value { get; set; } + public int aBc { get; set; } + } + } }