eerhardt commented on code in PR #34133: URL: https://github.com/apache/arrow/pull/34133#discussion_r1132921630
########## csharp/src/Apache.Arrow/C/CArrowSchema.cs: ########## @@ -0,0 +1,122 @@ +// 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.Runtime.InteropServices; +using Apache.Arrow.Types; + +namespace Apache.Arrow.C +{ + /// <summary> + /// An Arrow C Data Interface Schema, which represents a type, field, or schema. + /// </summary> + /// + /// <remarks> + /// This is used to export <see cref="ArrowType"/>, <see cref="Field"/>, or + /// <see cref="Schema"/> to other languages. It matches the layout of the + /// ArrowSchema struct described in https://github.com/apache/arrow/blob/main/cpp/src/arrow/c/abi.h. + /// </remarks> + [StructLayout(LayoutKind.Sequential)] + public unsafe struct CArrowSchema + { + public byte* format; + public byte* name; + public byte* metadata; + public long flags; + public long n_children; + public CArrowSchema** children; + public CArrowSchema* dictionary; + public delegate* unmanaged[Stdcall]<CArrowSchema*, void> release; + public void* private_data; + + + public static unsafe CArrowSchema* New() Review Comment: ```suggestion public static CArrowSchema* Create() ``` 1. The whole struct is unsafe. Don't need this on every method. 2. I'd prefer `Create` over `New` to not confuse this with a constructor. ########## csharp/src/Apache.Arrow/C/CArrowSchema.cs: ########## @@ -0,0 +1,122 @@ +// 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.Runtime.InteropServices; +using Apache.Arrow.Types; + +namespace Apache.Arrow.C +{ + /// <summary> + /// An Arrow C Data Interface Schema, which represents a type, field, or schema. + /// </summary> + /// + /// <remarks> + /// This is used to export <see cref="ArrowType"/>, <see cref="Field"/>, or + /// <see cref="Schema"/> to other languages. It matches the layout of the + /// ArrowSchema struct described in https://github.com/apache/arrow/blob/main/cpp/src/arrow/c/abi.h. + /// </remarks> + [StructLayout(LayoutKind.Sequential)] + public unsafe struct CArrowSchema + { + public byte* format; + public byte* name; + public byte* metadata; + public long flags; + public long n_children; + public CArrowSchema** children; + public CArrowSchema* dictionary; + public delegate* unmanaged[Stdcall]<CArrowSchema*, void> release; + public void* private_data; + + + public static unsafe CArrowSchema* New() + { + var ptr = (CArrowSchema*)Marshal.AllocHGlobal(Marshal.SizeOf<CArrowSchema>()); + + ptr->format = null; + ptr->name = null; + ptr->metadata = null; + ptr->flags = 0; + ptr->n_children = 0; + ptr->children = null; + ptr->dictionary = null; + ptr->release = null; + ptr->private_data = null; + + return ptr; + } + + /// <summary> + /// Free a pointer that was allocated in <see cref="AllocateAsPtr"/>. + /// </summary> + /// <remarks> + /// Do not call this on a pointer that was allocated elsewhere. + /// </remarks> + public static unsafe void Free(CArrowSchema* schema) + { + if (schema->release != null) + { + // Call release if not already called. + schema->release(schema); + } + Marshal.FreeHGlobal((IntPtr)schema); + } + + + /// <summary> + /// Whether this field is semantically nullable (regardless of whether it actually has null values) + /// </summary> + public const long ArrowFlagDictionaryOrdered = 1; + /// <summary> + /// For dictionary-encoded types, whether the ordering of dictionary indices is semantically meaningful. + /// </summary> + public const long ArrowFlagNullable = 2; + /// <summary> + /// For map types, whether the keys within each map value are sorted. + /// </summary> + public const long ArrowFlagMapKeysSorted = 4; + + /// <summary> + /// Get the value of a particular flag. + /// </summary> + /// <remarks> + /// Known valid flags are <see cref="ArrowFlagDictionaryOrdered" />, + /// <see cref="ArrowFlagNullable" />, and <see cref="ArrowFlagMapKeysSorted" />. + /// </remarks> + public bool GetFlag(long flag) + { + return (flags & flag) == flag; + } + + internal CArrowSchema* GetChild(int i) Review Comment: ```suggestion internal readonly CArrowSchema* GetChild(int i) ``` ########## csharp/src/Apache.Arrow/C/StringUtil.cs: ########## @@ -0,0 +1,66 @@ +// 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.Runtime.InteropServices; + +// Adapted from: +// https://github.com/G-Research/ParquetSharp/blob/467d99298fb5a5b9d5935b9c8dbde95e63954dd3/csharp/StringUtil.cs + +namespace Apache.Arrow.C +{ + + internal static class StringUtil + { + public static unsafe byte* ToCStringUtf8(string str) + { + var utf8 = System.Text.Encoding.UTF8; + int byteCount = utf8.GetByteCount(str); + byte* byteArray = (byte*)Marshal.AllocHGlobal(byteCount + 1); + + fixed (char* chars = str) + { + utf8.GetBytes(chars, str.Length, byteArray, byteCount); + } + + // Need to make sure it is nul-terminated. + byteArray[byteCount] = 0; + + return byteArray; + } + + public static unsafe string PtrToStringUtf8(byte* ptr) + { +#if NETSTANDARD2_1_OR_GREATER + return Marshal.PtrToStringUTF8(ptr); +#else + if (ptr == null) + { + return null; + } + + unsafe + { Review Comment: ```suggestion ``` The method is already unsafe. ########## csharp/src/Apache.Arrow/C/StringUtil.cs: ########## @@ -0,0 +1,66 @@ +// 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.Runtime.InteropServices; + +// Adapted from: +// https://github.com/G-Research/ParquetSharp/blob/467d99298fb5a5b9d5935b9c8dbde95e63954dd3/csharp/StringUtil.cs + +namespace Apache.Arrow.C +{ + + internal static class StringUtil + { + public static unsafe byte* ToCStringUtf8(string str) + { + var utf8 = System.Text.Encoding.UTF8; + int byteCount = utf8.GetByteCount(str); + byte* byteArray = (byte*)Marshal.AllocHGlobal(byteCount + 1); + + fixed (char* chars = str) + { + utf8.GetBytes(chars, str.Length, byteArray, byteCount); + } + + // Need to make sure it is nul-terminated. Review Comment: ```suggestion // Need to make sure it is null-terminated. ``` ########## csharp/src/Apache.Arrow/C/CArrowSchema.cs: ########## @@ -0,0 +1,122 @@ +// 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.Runtime.InteropServices; +using Apache.Arrow.Types; + +namespace Apache.Arrow.C +{ + /// <summary> + /// An Arrow C Data Interface Schema, which represents a type, field, or schema. + /// </summary> + /// + /// <remarks> + /// This is used to export <see cref="ArrowType"/>, <see cref="Field"/>, or + /// <see cref="Schema"/> to other languages. It matches the layout of the + /// ArrowSchema struct described in https://github.com/apache/arrow/blob/main/cpp/src/arrow/c/abi.h. + /// </remarks> + [StructLayout(LayoutKind.Sequential)] + public unsafe struct CArrowSchema + { + public byte* format; + public byte* name; + public byte* metadata; + public long flags; + public long n_children; + public CArrowSchema** children; + public CArrowSchema* dictionary; + public delegate* unmanaged[Stdcall]<CArrowSchema*, void> release; + public void* private_data; + + + public static unsafe CArrowSchema* New() + { + var ptr = (CArrowSchema*)Marshal.AllocHGlobal(Marshal.SizeOf<CArrowSchema>()); + + ptr->format = null; + ptr->name = null; + ptr->metadata = null; + ptr->flags = 0; + ptr->n_children = 0; + ptr->children = null; + ptr->dictionary = null; + ptr->release = null; + ptr->private_data = null; + + return ptr; + } + + /// <summary> + /// Free a pointer that was allocated in <see cref="AllocateAsPtr"/>. + /// </summary> + /// <remarks> + /// Do not call this on a pointer that was allocated elsewhere. + /// </remarks> + public static unsafe void Free(CArrowSchema* schema) + { + if (schema->release != null) + { + // Call release if not already called. + schema->release(schema); + } + Marshal.FreeHGlobal((IntPtr)schema); + } + + + /// <summary> + /// Whether this field is semantically nullable (regardless of whether it actually has null values) + /// </summary> + public const long ArrowFlagDictionaryOrdered = 1; + /// <summary> + /// For dictionary-encoded types, whether the ordering of dictionary indices is semantically meaningful. + /// </summary> + public const long ArrowFlagNullable = 2; + /// <summary> + /// For map types, whether the keys within each map value are sorted. + /// </summary> + public const long ArrowFlagMapKeysSorted = 4; + + /// <summary> + /// Get the value of a particular flag. + /// </summary> + /// <remarks> + /// Known valid flags are <see cref="ArrowFlagDictionaryOrdered" />, + /// <see cref="ArrowFlagNullable" />, and <see cref="ArrowFlagMapKeysSorted" />. + /// </remarks> + public bool GetFlag(long flag) + { + return (flags & flag) == flag; + } + + internal CArrowSchema* GetChild(int i) + { + if (i >= n_children) + { + throw new ArgumentOutOfRangeException("Child index out of bounds."); + } + if (children == null) + { + throw new Exception("Children array is null but n_children is not zero."); + } + unsafe + { + return children[i]; + } Review Comment: ```suggestion return children[i]; ``` Whole struct is unsafe. ########## csharp/src/Apache.Arrow/C/CArrowSchema.cs: ########## @@ -0,0 +1,122 @@ +// 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.Runtime.InteropServices; +using Apache.Arrow.Types; + +namespace Apache.Arrow.C +{ + /// <summary> + /// An Arrow C Data Interface Schema, which represents a type, field, or schema. + /// </summary> + /// Review Comment: ```suggestion ``` No need for this blank line. ########## csharp/src/Apache.Arrow/C/CArrowSchema.cs: ########## @@ -0,0 +1,122 @@ +// 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.Runtime.InteropServices; +using Apache.Arrow.Types; + +namespace Apache.Arrow.C +{ + /// <summary> + /// An Arrow C Data Interface Schema, which represents a type, field, or schema. + /// </summary> + /// + /// <remarks> + /// This is used to export <see cref="ArrowType"/>, <see cref="Field"/>, or + /// <see cref="Schema"/> to other languages. It matches the layout of the + /// ArrowSchema struct described in https://github.com/apache/arrow/blob/main/cpp/src/arrow/c/abi.h. + /// </remarks> + [StructLayout(LayoutKind.Sequential)] + public unsafe struct CArrowSchema + { + public byte* format; + public byte* name; + public byte* metadata; + public long flags; + public long n_children; + public CArrowSchema** children; + public CArrowSchema* dictionary; + public delegate* unmanaged[Stdcall]<CArrowSchema*, void> release; + public void* private_data; + + + public static unsafe CArrowSchema* New() + { + var ptr = (CArrowSchema*)Marshal.AllocHGlobal(Marshal.SizeOf<CArrowSchema>()); Review Comment: ```suggestion var ptr = (CArrowSchema*)Marshal.AllocHGlobal(sizeof(CArrowSchema)); ``` Using `sizeof` keyword here is better because it becomes a constant, and not a runtime call. Also it is "safe" with NativeAOT and Trimming. ########## csharp/src/Apache.Arrow/C/CArrowSchema.cs: ########## @@ -0,0 +1,122 @@ +// 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.Runtime.InteropServices; +using Apache.Arrow.Types; + +namespace Apache.Arrow.C +{ + /// <summary> + /// An Arrow C Data Interface Schema, which represents a type, field, or schema. + /// </summary> + /// + /// <remarks> + /// This is used to export <see cref="ArrowType"/>, <see cref="Field"/>, or + /// <see cref="Schema"/> to other languages. It matches the layout of the + /// ArrowSchema struct described in https://github.com/apache/arrow/blob/main/cpp/src/arrow/c/abi.h. + /// </remarks> + [StructLayout(LayoutKind.Sequential)] + public unsafe struct CArrowSchema + { + public byte* format; + public byte* name; + public byte* metadata; + public long flags; + public long n_children; + public CArrowSchema** children; + public CArrowSchema* dictionary; + public delegate* unmanaged[Stdcall]<CArrowSchema*, void> release; + public void* private_data; + + Review Comment: ```suggestion ``` (nit) - only one blank line between members. ########## csharp/src/Apache.Arrow/C/CArrowSchema.cs: ########## @@ -0,0 +1,122 @@ +// 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.Runtime.InteropServices; +using Apache.Arrow.Types; + +namespace Apache.Arrow.C +{ + /// <summary> + /// An Arrow C Data Interface Schema, which represents a type, field, or schema. + /// </summary> + /// + /// <remarks> + /// This is used to export <see cref="ArrowType"/>, <see cref="Field"/>, or + /// <see cref="Schema"/> to other languages. It matches the layout of the + /// ArrowSchema struct described in https://github.com/apache/arrow/blob/main/cpp/src/arrow/c/abi.h. + /// </remarks> + [StructLayout(LayoutKind.Sequential)] + public unsafe struct CArrowSchema + { + public byte* format; + public byte* name; + public byte* metadata; + public long flags; + public long n_children; + public CArrowSchema** children; + public CArrowSchema* dictionary; + public delegate* unmanaged[Stdcall]<CArrowSchema*, void> release; + public void* private_data; + + + public static unsafe CArrowSchema* New() + { + var ptr = (CArrowSchema*)Marshal.AllocHGlobal(Marshal.SizeOf<CArrowSchema>()); + + ptr->format = null; + ptr->name = null; + ptr->metadata = null; + ptr->flags = 0; + ptr->n_children = 0; + ptr->children = null; + ptr->dictionary = null; + ptr->release = null; + ptr->private_data = null; + + return ptr; + } + + /// <summary> + /// Free a pointer that was allocated in <see cref="AllocateAsPtr"/>. + /// </summary> + /// <remarks> + /// Do not call this on a pointer that was allocated elsewhere. + /// </remarks> + public static unsafe void Free(CArrowSchema* schema) + { + if (schema->release != null) + { + // Call release if not already called. + schema->release(schema); + } + Marshal.FreeHGlobal((IntPtr)schema); + } + + + /// <summary> + /// Whether this field is semantically nullable (regardless of whether it actually has null values) + /// </summary> + public const long ArrowFlagDictionaryOrdered = 1; + /// <summary> + /// For dictionary-encoded types, whether the ordering of dictionary indices is semantically meaningful. + /// </summary> + public const long ArrowFlagNullable = 2; + /// <summary> + /// For map types, whether the keys within each map value are sorted. + /// </summary> + public const long ArrowFlagMapKeysSorted = 4; + + /// <summary> + /// Get the value of a particular flag. + /// </summary> + /// <remarks> + /// Known valid flags are <see cref="ArrowFlagDictionaryOrdered" />, + /// <see cref="ArrowFlagNullable" />, and <see cref="ArrowFlagMapKeysSorted" />. + /// </remarks> + public bool GetFlag(long flag) + { + return (flags & flag) == flag; + } + + internal CArrowSchema* GetChild(int i) Review Comment: ```suggestion internal CArrowSchema* GetChild(long i) ``` Since n_children is a `long`, does it make sense for this to be a `long`? ########## csharp/src/Apache.Arrow/C/CArrowSchema.cs: ########## @@ -0,0 +1,122 @@ +// 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.Runtime.InteropServices; +using Apache.Arrow.Types; + +namespace Apache.Arrow.C +{ + /// <summary> + /// An Arrow C Data Interface Schema, which represents a type, field, or schema. + /// </summary> + /// + /// <remarks> + /// This is used to export <see cref="ArrowType"/>, <see cref="Field"/>, or + /// <see cref="Schema"/> to other languages. It matches the layout of the + /// ArrowSchema struct described in https://github.com/apache/arrow/blob/main/cpp/src/arrow/c/abi.h. + /// </remarks> + [StructLayout(LayoutKind.Sequential)] + public unsafe struct CArrowSchema + { + public byte* format; + public byte* name; + public byte* metadata; + public long flags; + public long n_children; + public CArrowSchema** children; + public CArrowSchema* dictionary; + public delegate* unmanaged[Stdcall]<CArrowSchema*, void> release; + public void* private_data; + + + public static unsafe CArrowSchema* New() + { + var ptr = (CArrowSchema*)Marshal.AllocHGlobal(Marshal.SizeOf<CArrowSchema>()); + + ptr->format = null; + ptr->name = null; + ptr->metadata = null; + ptr->flags = 0; + ptr->n_children = 0; + ptr->children = null; + ptr->dictionary = null; + ptr->release = null; + ptr->private_data = null; + + return ptr; + } + + /// <summary> + /// Free a pointer that was allocated in <see cref="AllocateAsPtr"/>. + /// </summary> + /// <remarks> + /// Do not call this on a pointer that was allocated elsewhere. + /// </remarks> + public static unsafe void Free(CArrowSchema* schema) + { + if (schema->release != null) + { + // Call release if not already called. + schema->release(schema); + } + Marshal.FreeHGlobal((IntPtr)schema); + } + + + /// <summary> + /// Whether this field is semantically nullable (regardless of whether it actually has null values) + /// </summary> + public const long ArrowFlagDictionaryOrdered = 1; + /// <summary> + /// For dictionary-encoded types, whether the ordering of dictionary indices is semantically meaningful. + /// </summary> + public const long ArrowFlagNullable = 2; + /// <summary> + /// For map types, whether the keys within each map value are sorted. + /// </summary> + public const long ArrowFlagMapKeysSorted = 4; + + /// <summary> + /// Get the value of a particular flag. + /// </summary> + /// <remarks> + /// Known valid flags are <see cref="ArrowFlagDictionaryOrdered" />, + /// <see cref="ArrowFlagNullable" />, and <see cref="ArrowFlagMapKeysSorted" />. + /// </remarks> + public bool GetFlag(long flag) + { + return (flags & flag) == flag; + } + + internal CArrowSchema* GetChild(int i) + { + if (i >= n_children) Review Comment: ```suggestion if ((ulong)i >= (ulong)n_children) ``` This is a trick we use a lot in the dotnet/runtime. It does 2 checks at once: 1. Checks if the index is larger than the n_children. 2. Checks if the index is negative. ########## csharp/src/Apache.Arrow/C/CArrowSchema.cs: ########## @@ -0,0 +1,122 @@ +// 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.Runtime.InteropServices; +using Apache.Arrow.Types; + +namespace Apache.Arrow.C +{ + /// <summary> + /// An Arrow C Data Interface Schema, which represents a type, field, or schema. + /// </summary> + /// + /// <remarks> + /// This is used to export <see cref="ArrowType"/>, <see cref="Field"/>, or + /// <see cref="Schema"/> to other languages. It matches the layout of the + /// ArrowSchema struct described in https://github.com/apache/arrow/blob/main/cpp/src/arrow/c/abi.h. + /// </remarks> + [StructLayout(LayoutKind.Sequential)] + public unsafe struct CArrowSchema + { + public byte* format; + public byte* name; + public byte* metadata; + public long flags; + public long n_children; + public CArrowSchema** children; + public CArrowSchema* dictionary; + public delegate* unmanaged[Stdcall]<CArrowSchema*, void> release; + public void* private_data; + + + public static unsafe CArrowSchema* New() + { + var ptr = (CArrowSchema*)Marshal.AllocHGlobal(Marshal.SizeOf<CArrowSchema>()); + + ptr->format = null; + ptr->name = null; + ptr->metadata = null; + ptr->flags = 0; + ptr->n_children = 0; + ptr->children = null; + ptr->dictionary = null; + ptr->release = null; + ptr->private_data = null; + + return ptr; + } + + /// <summary> + /// Free a pointer that was allocated in <see cref="AllocateAsPtr"/>. + /// </summary> + /// <remarks> + /// Do not call this on a pointer that was allocated elsewhere. + /// </remarks> + public static unsafe void Free(CArrowSchema* schema) + { + if (schema->release != null) + { + // Call release if not already called. + schema->release(schema); + } + Marshal.FreeHGlobal((IntPtr)schema); + } + + + /// <summary> + /// Whether this field is semantically nullable (regardless of whether it actually has null values) + /// </summary> + public const long ArrowFlagDictionaryOrdered = 1; + /// <summary> + /// For dictionary-encoded types, whether the ordering of dictionary indices is semantically meaningful. + /// </summary> + public const long ArrowFlagNullable = 2; + /// <summary> + /// For map types, whether the keys within each map value are sorted. + /// </summary> + public const long ArrowFlagMapKeysSorted = 4; + + /// <summary> + /// Get the value of a particular flag. + /// </summary> + /// <remarks> + /// Known valid flags are <see cref="ArrowFlagDictionaryOrdered" />, + /// <see cref="ArrowFlagNullable" />, and <see cref="ArrowFlagMapKeysSorted" />. + /// </remarks> + public bool GetFlag(long flag) + { + return (flags & flag) == flag; + } + + internal CArrowSchema* GetChild(int i) + { + if (i >= n_children) + { + throw new ArgumentOutOfRangeException("Child index out of bounds."); Review Comment: ```suggestion throw new ArgumentOutOfRangeException($"Child index '{i}' out of bounds."); ``` ########## csharp/src/Apache.Arrow/C/CArrowSchema.cs: ########## @@ -0,0 +1,122 @@ +// 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.Runtime.InteropServices; +using Apache.Arrow.Types; + +namespace Apache.Arrow.C +{ + /// <summary> + /// An Arrow C Data Interface Schema, which represents a type, field, or schema. + /// </summary> + /// + /// <remarks> + /// This is used to export <see cref="ArrowType"/>, <see cref="Field"/>, or + /// <see cref="Schema"/> to other languages. It matches the layout of the + /// ArrowSchema struct described in https://github.com/apache/arrow/blob/main/cpp/src/arrow/c/abi.h. + /// </remarks> + [StructLayout(LayoutKind.Sequential)] + public unsafe struct CArrowSchema + { + public byte* format; + public byte* name; + public byte* metadata; + public long flags; + public long n_children; + public CArrowSchema** children; + public CArrowSchema* dictionary; + public delegate* unmanaged[Stdcall]<CArrowSchema*, void> release; + public void* private_data; + + + public static unsafe CArrowSchema* New() + { + var ptr = (CArrowSchema*)Marshal.AllocHGlobal(Marshal.SizeOf<CArrowSchema>()); + + ptr->format = null; + ptr->name = null; + ptr->metadata = null; + ptr->flags = 0; + ptr->n_children = 0; + ptr->children = null; + ptr->dictionary = null; + ptr->release = null; + ptr->private_data = null; + + return ptr; + } + + /// <summary> + /// Free a pointer that was allocated in <see cref="AllocateAsPtr"/>. + /// </summary> + /// <remarks> + /// Do not call this on a pointer that was allocated elsewhere. + /// </remarks> + public static unsafe void Free(CArrowSchema* schema) + { + if (schema->release != null) + { + // Call release if not already called. + schema->release(schema); + } + Marshal.FreeHGlobal((IntPtr)schema); + } + + + /// <summary> + /// Whether this field is semantically nullable (regardless of whether it actually has null values) + /// </summary> + public const long ArrowFlagDictionaryOrdered = 1; + /// <summary> + /// For dictionary-encoded types, whether the ordering of dictionary indices is semantically meaningful. + /// </summary> + public const long ArrowFlagNullable = 2; + /// <summary> + /// For map types, whether the keys within each map value are sorted. + /// </summary> + public const long ArrowFlagMapKeysSorted = 4; + + /// <summary> + /// Get the value of a particular flag. + /// </summary> + /// <remarks> + /// Known valid flags are <see cref="ArrowFlagDictionaryOrdered" />, + /// <see cref="ArrowFlagNullable" />, and <see cref="ArrowFlagMapKeysSorted" />. + /// </remarks> + public bool GetFlag(long flag) Review Comment: ```suggestion public readonly bool GetFlag(long flag) ``` ########## csharp/src/Apache.Arrow/C/CArrowSchema.cs: ########## @@ -0,0 +1,122 @@ +// 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.Runtime.InteropServices; +using Apache.Arrow.Types; + +namespace Apache.Arrow.C +{ + /// <summary> + /// An Arrow C Data Interface Schema, which represents a type, field, or schema. + /// </summary> + /// + /// <remarks> + /// This is used to export <see cref="ArrowType"/>, <see cref="Field"/>, or + /// <see cref="Schema"/> to other languages. It matches the layout of the + /// ArrowSchema struct described in https://github.com/apache/arrow/blob/main/cpp/src/arrow/c/abi.h. + /// </remarks> + [StructLayout(LayoutKind.Sequential)] + public unsafe struct CArrowSchema + { + public byte* format; + public byte* name; + public byte* metadata; + public long flags; + public long n_children; + public CArrowSchema** children; + public CArrowSchema* dictionary; + public delegate* unmanaged[Stdcall]<CArrowSchema*, void> release; + public void* private_data; + + + public static unsafe CArrowSchema* New() + { + var ptr = (CArrowSchema*)Marshal.AllocHGlobal(Marshal.SizeOf<CArrowSchema>()); + + ptr->format = null; + ptr->name = null; + ptr->metadata = null; + ptr->flags = 0; + ptr->n_children = 0; + ptr->children = null; + ptr->dictionary = null; + ptr->release = null; + ptr->private_data = null; + + return ptr; + } + + /// <summary> + /// Free a pointer that was allocated in <see cref="AllocateAsPtr"/>. + /// </summary> + /// <remarks> + /// Do not call this on a pointer that was allocated elsewhere. + /// </remarks> + public static unsafe void Free(CArrowSchema* schema) + { + if (schema->release != null) + { + // Call release if not already called. + schema->release(schema); + } + Marshal.FreeHGlobal((IntPtr)schema); + } + + + /// <summary> + /// Whether this field is semantically nullable (regardless of whether it actually has null values) + /// </summary> + public const long ArrowFlagDictionaryOrdered = 1; + /// <summary> + /// For dictionary-encoded types, whether the ordering of dictionary indices is semantically meaningful. + /// </summary> + public const long ArrowFlagNullable = 2; + /// <summary> + /// For map types, whether the keys within each map value are sorted. + /// </summary> + public const long ArrowFlagMapKeysSorted = 4; + + /// <summary> + /// Get the value of a particular flag. + /// </summary> + /// <remarks> + /// Known valid flags are <see cref="ArrowFlagDictionaryOrdered" />, + /// <see cref="ArrowFlagNullable" />, and <see cref="ArrowFlagMapKeysSorted" />. + /// </remarks> + public bool GetFlag(long flag) + { + return (flags & flag) == flag; + } + + internal CArrowSchema* GetChild(int i) Review Comment: Any reason this is `internal`? ########## csharp/src/Apache.Arrow/C/CArrowSchema.cs: ########## @@ -0,0 +1,122 @@ +// 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.Runtime.InteropServices; +using Apache.Arrow.Types; + +namespace Apache.Arrow.C +{ + /// <summary> + /// An Arrow C Data Interface Schema, which represents a type, field, or schema. + /// </summary> + /// + /// <remarks> + /// This is used to export <see cref="ArrowType"/>, <see cref="Field"/>, or + /// <see cref="Schema"/> to other languages. It matches the layout of the + /// ArrowSchema struct described in https://github.com/apache/arrow/blob/main/cpp/src/arrow/c/abi.h. + /// </remarks> + [StructLayout(LayoutKind.Sequential)] + public unsafe struct CArrowSchema + { + public byte* format; + public byte* name; + public byte* metadata; + public long flags; + public long n_children; + public CArrowSchema** children; + public CArrowSchema* dictionary; + public delegate* unmanaged[Stdcall]<CArrowSchema*, void> release; + public void* private_data; + + + public static unsafe CArrowSchema* New() + { + var ptr = (CArrowSchema*)Marshal.AllocHGlobal(Marshal.SizeOf<CArrowSchema>()); + + ptr->format = null; + ptr->name = null; + ptr->metadata = null; + ptr->flags = 0; + ptr->n_children = 0; + ptr->children = null; + ptr->dictionary = null; + ptr->release = null; + ptr->private_data = null; + + return ptr; + } + + /// <summary> + /// Free a pointer that was allocated in <see cref="AllocateAsPtr"/>. Review Comment: What is `AllocateAsPtr`? ########## csharp/src/Apache.Arrow/C/CArrowSchemaImporter.cs: ########## @@ -0,0 +1,285 @@ +// 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.IO; +using System.Linq; +using Apache.Arrow.Types; + +namespace Apache.Arrow.C +{ + public static class CArrowSchemaImporter + { + /// <summary> + /// Import C pointer as an <see cref="ArrowType"/>. + /// </summary> + /// <examples> + /// Typically, you will allocate a uninitialized CArrowSchema pointer, + /// pass that to external function, and then use this method to import + /// the result. + /// + /// <code> + /// CArrowSchema* importedPtr = CArrowSchema.New(); + /// foreign_export_function(importedPtr); + /// ArrowType importedType = CArrowSchemaImporter.ImportType(importedPtr); + /// CArrowSchema.Free(importedPtr); + /// </code> + /// </examples> + public static unsafe ArrowType ImportType(CArrowSchema* ptr) + { + using var importedType = new ImportedArrowSchema(ptr); + return importedType.GetAsType(); + } + + /// <summary> + /// Import C pointer as an <see cref="Field"/>. + /// </summary> + /// <examples> + /// Typically, you will allocate a uninitialized CArrowSchema pointer, + /// pass that to external function, and then use this method to import + /// the result. + /// + /// <code> + /// CArrowSchema* importedPtr = CArrowSchema.New(); + /// foreign_export_function(importedPtr); + /// Field importedField = CArrowSchemaImporter.ImportField(importedPtr); + /// CArrowSchema.Free(importedPtr); + /// </code> + /// </examples> + public static unsafe Field ImportField(CArrowSchema* ptr) + { + using var importedField = new ImportedArrowSchema(ptr); + return importedField.GetAsField(); + } + + /// <summary> + /// Import C pointer as an <see cref="Schema"/>. + /// </summary> + /// <examples> + /// Typically, you will allocate a uninitialized CArrowSchema pointer, + /// pass that to external function, and then use this method to import + /// the result. + /// + /// <code> + /// CArrowSchema* importedPtr = CArrowSchema.New(); + /// foreign_export_function(importedPtr); + /// Field importedSchema = CArrowSchemaImporter.ImportSchema(importedPtr); + /// CArrowSchema.Free(importedPtr); + /// </code> + /// </examples> + public static unsafe Schema ImportSchema(CArrowSchema* ptr) + { + using var importedSchema = new ImportedArrowSchema(ptr); + return importedSchema.GetAsSchema(); + } + + private sealed unsafe class ImportedArrowSchema : IDisposable + { + private readonly CArrowSchema* _data; + private readonly bool _isRoot; + + public ImportedArrowSchema(CArrowSchema* handle) + { + _data = (CArrowSchema*)handle; + if (_data->release == null) + { + throw new ArgumentException("Tried to import a schema that has already been released."); + } + _isRoot = true; + } + + public ImportedArrowSchema(CArrowSchema* handle, bool isRoot) : this(handle) + { + _isRoot = isRoot; + } + + public void Dispose() + { + // We only call release on a root-level schema, not child ones. + if (_isRoot && _data->release != null) + { + _data->release(_data); + } + } + + public ArrowType GetAsType() + { + var format = StringUtil.PtrToStringUtf8(_data->format); + if (_data->dictionary != null) + { + ArrowType indicesType = format switch + { + "c" => new Int8Type(), + "C" => new UInt8Type(), + "s" => new Int16Type(), + "S" => new UInt16Type(), + "i" => new Int32Type(), + "I" => new UInt32Type(), + "l" => new Int64Type(), + "L" => new UInt64Type(), + _ => throw new InvalidDataException($"Indices must be an integer, but got format string {format}"), + }; + + var dictionarySchema = new ImportedArrowSchema(_data->dictionary, isRoot: false); + ArrowType dictionaryType = dictionarySchema.GetAsType(); + + bool ordered = _data->GetFlag(CArrowSchema.ArrowFlagDictionaryOrdered); + + return new DictionaryType(indicesType, dictionaryType, ordered); + } + + // Special handling for nested types + if (format == "+l") + { + if (_data->n_children != 1) + { + throw new InvalidDataException("Expected list type to have exactly one child."); + } + ImportedArrowSchema childSchema; + if (_data->GetChild(0) == null) + { + throw new InvalidDataException("Expected list type child to be non-null."); + } + childSchema = new ImportedArrowSchema(_data->GetChild(0), isRoot: false); + + Field childField = childSchema.GetAsField(); + + return new ListType(childField); + } + else if (format == "+s") + { + var child_schemas = new ImportedArrowSchema[_data->n_children]; + + for (int i = 0; i < _data->n_children; i++) + { + if (_data->GetChild(i) == null) + { + throw new InvalidDataException("Expected struct type child to be non-null."); + } + child_schemas[i] = new ImportedArrowSchema(_data->GetChild(i), isRoot: false); + } + + + List<Field> childFields = child_schemas.Select(schema => schema.GetAsField()).ToList(); + + return new StructType(childFields); + } + // TODO: Map type and large list type + + // Decimals + if (format.StartsWith("d:")) + { + bool is256 = format.EndsWith(",256"); + string parameters_part = format.Remove(0, 2); + if (is256) parameters_part.Substring(0, parameters_part.Length - 5); + string[] parameters = parameters_part.Split(','); + int precision = Int32.Parse(parameters[0]); + int scale = Int32.Parse(parameters[1]); + if (is256) + { + return new Decimal256Type(precision, scale); + } + else + { + return new Decimal128Type(precision, scale); + } + } + + // Timestamps + if (format.StartsWith("ts")) + { + TimeUnit timeUnit = format[2] switch + { + 's' => TimeUnit.Second, + 'm' => TimeUnit.Millisecond, + 'u' => TimeUnit.Microsecond, + 'n' => TimeUnit.Nanosecond, + _ => throw new InvalidDataException($"Unsupported time unit for import: {format[2]}"), + }; + + string timezone = format.Split(':')[1]; + return new TimestampType(timeUnit, timezone); + } + + // Fixed-width binary + if (format.StartsWith("w:")) + { + int width = Int32.Parse(format.Substring(2)); + return new FixedSizeBinaryType(width); + } + + return format switch + { + // Primitives + "n" => new NullType(), + "b" => new BooleanType(), + "c" => new Int8Type(), + "C" => new UInt8Type(), + "s" => new Int16Type(), + "S" => new UInt16Type(), + "i" => new Int32Type(), + "I" => new UInt32Type(), + "l" => new Int64Type(), + "L" => new UInt64Type(), + "e" => new HalfFloatType(), + "f" => new FloatType(), + "g" => new DoubleType(), Review Comment: These should all use the `.Default` property, where applicable. No reason to allocate extra objects here. ########## csharp/src/Apache.Arrow/C/CArrowSchemaExporter.cs: ########## @@ -0,0 +1,268 @@ +// 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.IO; +using System.Linq; +using System.Runtime.InteropServices; +using Apache.Arrow.Types; + +namespace Apache.Arrow.C +{ + public static class CArrowSchemaExporter + { + /// <summary> + /// Export a type to a <see cref="CArrowSchema"/>. + /// </summary> + /// <param name="datatype">The datatype to export</param> + /// <param name="schema">An allocated but uninitialized CArrowSchema pointer.</param> + /// <example> + /// <code> + /// CArrowSchema* exportPtr = CArrowSchema.New(); + /// CArrowSchemaExporter.ExportType(dataType, exportPtr); + /// foreign_import_function(exportPtr); + /// CArrowSchema.Free(exportPtr); + /// </code> + /// </example> + public static unsafe void ExportType(IArrowType datatype, CArrowSchema* schema) + { + if (schema == null) + { + throw new ArgumentNullException("Cannot export schema to a null pointer."); + } + if (schema->release != null) + { + throw new ArgumentException("Cannot export schema to a struct that is already initialized."); + } + + schema->format = StringUtil.ToCStringUtf8(GetFormat(datatype)); + schema->name = null; + schema->metadata = null; + schema->flags = GetFlags(datatype); + + schema->children = ConstructChildren(datatype, out var numChildren); + schema->n_children = numChildren; + + schema->dictionary = ConstructDictionary(datatype); + + schema->release = (delegate* unmanaged[Stdcall]<CArrowSchema*, void>)Marshal.GetFunctionPointerForDelegate( + ReleaseCArrowSchema); + + schema->private_data = null; + } + + /// <summary> + /// Export a field to a <see cref="CArrowSchema"/>. + /// </summary> + /// <param name="field">The field to export</param> + /// <param name="schema">An allocated but uninitialized CArrowSchema pointer.</param> + /// <example> + /// <code> + /// CArrowSchema* exportPtr = CArrowSchema.New(); + /// CArrowSchemaExporter.ExportType(field, exportPtr); + /// foreign_import_function(exportPtr); + /// CArrowSchema.Free(exportPtr); + /// </code> + /// </example> + public static unsafe void ExportField(Field field, CArrowSchema* schema) + { + ExportType(field.DataType, schema); + schema->name = StringUtil.ToCStringUtf8(field.Name); + // TODO: field metadata + schema->metadata = null; + schema->flags = GetFlags(field.DataType, field.IsNullable); + } + + /// <summary> + /// Export a schema to a <see cref="CArrowSchema"/>. + /// </summary> + /// <param name="schema">The schema to export</param> + /// <param name="out_schema">An allocated but uninitialized CArrowSchema pointer.</param> + /// <example> + /// <code> + /// CArrowSchema* exportPtr = CArrowSchema.New(); + /// CArrowSchemaExporter.ExportType(schema, exportPtr); + /// foreign_import_function(exportPtr); + /// CArrowSchema.Free(exportPtr); + /// </code> + /// </example> + public static unsafe void ExportSchema(Schema schema, CArrowSchema* out_schema) + { + var structType = new StructType(schema.FieldsList); + // TODO: top-level metadata + ExportType(structType, out_schema); + } + + private static char FormatTimeUnit(TimeUnit unit) => unit switch + { + TimeUnit.Second => 's', + TimeUnit.Millisecond => 'm', + TimeUnit.Microsecond => 'u', + TimeUnit.Nanosecond => 'n', + _ => throw new InvalidDataException($"Unsupported time unit for export: {unit}"), + }; + + private static string GetFormat(IArrowType datatype) + { + switch (datatype) + { + case NullType _: return "n"; + case BooleanType _: return "b"; + // Integers + case Int8Type _: return "c"; + case UInt8Type _: return "C"; + case Int16Type _: return "s"; + case UInt16Type _: return "S"; + case Int32Type _: return "i"; + case UInt32Type _: return "I"; + case Int64Type _: return "l"; + case UInt64Type _: return "L"; + // Floats + case HalfFloatType _: return "e"; + case FloatType _: return "f"; + case DoubleType _: return "g"; + // Decimal + case Decimal128Type decimalType: + return $"d:{decimalType.Precision},{decimalType.Scale}"; + case Decimal256Type decimalType: + return $"d:{decimalType.Precision},{decimalType.Scale},256"; + // Binary + case BinaryType _: return "z"; + case StringType _: return "u"; + case FixedSizeBinaryType binaryType: + return $"w:{binaryType.ByteWidth}"; + // Date + case Date32Type _: return "tdD"; + case Date64Type _: return "tdm"; + // Time + case Time32Type timeType: + return String.Format("tt{0}", FormatTimeUnit(timeType.Unit)); + case Time64Type timeType: + // Same prefix as Time32, but allowed time units are different. + return String.Format("tt{0}", FormatTimeUnit(timeType.Unit)); + // Timestamp + case TimestampType timestampType: + return String.Format("ts{0}:{1}", FormatTimeUnit(timestampType.Unit), timestampType.Timezone); + // Nested + case ListType _: return "+l"; + case StructType _: return "+s"; + // Dictionary + case DictionaryType dictionaryType: + return GetFormat(dictionaryType.IndexType); + default: throw new NotImplementedException($"Exporting {datatype.Name} not implemented"); + }; + } + + private static long GetFlags(IArrowType datatype, bool nullable = true) + { + long flags = 0; + + if (nullable) + { + flags |= CArrowSchema.ArrowFlagNullable; + } + + if (datatype is DictionaryType dictionaryType) + { + if (dictionaryType.Ordered) + { + flags |= CArrowSchema.ArrowFlagDictionaryOrdered; + } + } + + // TODO: when we implement MapType, make sure to set the KEYS_SORTED flag. + return flags; + } + + private static unsafe CArrowSchema** ConstructChildren(IArrowType datatype, out long numChildren) + { + if (datatype is NestedType nestedType) + { + IReadOnlyList<Field> fields = nestedType.Fields; + int numFields = fields.Count; + numChildren = numFields; + + unsafe + { + var pointerList = (CArrowSchema**)Marshal.AllocHGlobal(numFields * IntPtr.Size); + + for (var i = 0; i < numChildren; i++) + { + CArrowSchema* cSchema = CArrowSchema.New(); + ExportField(fields[i], cSchema); + pointerList[i] = cSchema; + } + + return pointerList; + } + + } + else + { + numChildren = 0; + return null; + } + } + + private static unsafe CArrowSchema* ConstructDictionary(IArrowType datatype) + { + if (datatype is DictionaryType dictType) + { + CArrowSchema* cSchema = CArrowSchema.New(); + ExportType(dictType.ValueType, cSchema); + return cSchema; + } + else + { + return null; + } + } + + private static unsafe void ReleaseCArrowSchema(CArrowSchema* schema) + { + if (schema == null) return; + if (schema->release == null) return; Review Comment: Why is this check necessary? ########## csharp/src/Apache.Arrow/C/CArrowSchemaImporter.cs: ########## @@ -0,0 +1,285 @@ +// 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.IO; +using System.Linq; +using Apache.Arrow.Types; + +namespace Apache.Arrow.C +{ + public static class CArrowSchemaImporter + { + /// <summary> + /// Import C pointer as an <see cref="ArrowType"/>. + /// </summary> + /// <examples> + /// Typically, you will allocate a uninitialized CArrowSchema pointer, + /// pass that to external function, and then use this method to import + /// the result. + /// + /// <code> + /// CArrowSchema* importedPtr = CArrowSchema.New(); + /// foreign_export_function(importedPtr); + /// ArrowType importedType = CArrowSchemaImporter.ImportType(importedPtr); + /// CArrowSchema.Free(importedPtr); + /// </code> + /// </examples> + public static unsafe ArrowType ImportType(CArrowSchema* ptr) + { + using var importedType = new ImportedArrowSchema(ptr); + return importedType.GetAsType(); + } + + /// <summary> + /// Import C pointer as an <see cref="Field"/>. + /// </summary> + /// <examples> + /// Typically, you will allocate a uninitialized CArrowSchema pointer, + /// pass that to external function, and then use this method to import + /// the result. + /// + /// <code> + /// CArrowSchema* importedPtr = CArrowSchema.New(); + /// foreign_export_function(importedPtr); + /// Field importedField = CArrowSchemaImporter.ImportField(importedPtr); + /// CArrowSchema.Free(importedPtr); + /// </code> + /// </examples> + public static unsafe Field ImportField(CArrowSchema* ptr) + { + using var importedField = new ImportedArrowSchema(ptr); + return importedField.GetAsField(); + } + + /// <summary> + /// Import C pointer as an <see cref="Schema"/>. + /// </summary> + /// <examples> + /// Typically, you will allocate a uninitialized CArrowSchema pointer, + /// pass that to external function, and then use this method to import + /// the result. + /// + /// <code> + /// CArrowSchema* importedPtr = CArrowSchema.New(); + /// foreign_export_function(importedPtr); + /// Field importedSchema = CArrowSchemaImporter.ImportSchema(importedPtr); + /// CArrowSchema.Free(importedPtr); + /// </code> + /// </examples> + public static unsafe Schema ImportSchema(CArrowSchema* ptr) + { + using var importedSchema = new ImportedArrowSchema(ptr); + return importedSchema.GetAsSchema(); + } + + private sealed unsafe class ImportedArrowSchema : IDisposable + { + private readonly CArrowSchema* _data; + private readonly bool _isRoot; + + public ImportedArrowSchema(CArrowSchema* handle) + { + _data = (CArrowSchema*)handle; Review Comment: (nit) The ctor parameter should be the same name as the backing field. It makes it easier to read and know that these things are the same thing. ########## csharp/src/Apache.Arrow/C/CArrowSchemaImporter.cs: ########## @@ -0,0 +1,285 @@ +// 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.IO; +using System.Linq; +using Apache.Arrow.Types; + +namespace Apache.Arrow.C +{ + public static class CArrowSchemaImporter + { + /// <summary> + /// Import C pointer as an <see cref="ArrowType"/>. + /// </summary> + /// <examples> + /// Typically, you will allocate a uninitialized CArrowSchema pointer, + /// pass that to external function, and then use this method to import + /// the result. + /// + /// <code> + /// CArrowSchema* importedPtr = CArrowSchema.New(); + /// foreign_export_function(importedPtr); + /// ArrowType importedType = CArrowSchemaImporter.ImportType(importedPtr); + /// CArrowSchema.Free(importedPtr); + /// </code> + /// </examples> + public static unsafe ArrowType ImportType(CArrowSchema* ptr) + { + using var importedType = new ImportedArrowSchema(ptr); + return importedType.GetAsType(); + } + + /// <summary> + /// Import C pointer as an <see cref="Field"/>. + /// </summary> + /// <examples> + /// Typically, you will allocate a uninitialized CArrowSchema pointer, + /// pass that to external function, and then use this method to import + /// the result. + /// + /// <code> + /// CArrowSchema* importedPtr = CArrowSchema.New(); + /// foreign_export_function(importedPtr); + /// Field importedField = CArrowSchemaImporter.ImportField(importedPtr); + /// CArrowSchema.Free(importedPtr); + /// </code> + /// </examples> + public static unsafe Field ImportField(CArrowSchema* ptr) + { + using var importedField = new ImportedArrowSchema(ptr); + return importedField.GetAsField(); + } + + /// <summary> + /// Import C pointer as an <see cref="Schema"/>. + /// </summary> + /// <examples> + /// Typically, you will allocate a uninitialized CArrowSchema pointer, + /// pass that to external function, and then use this method to import + /// the result. + /// + /// <code> + /// CArrowSchema* importedPtr = CArrowSchema.New(); + /// foreign_export_function(importedPtr); + /// Field importedSchema = CArrowSchemaImporter.ImportSchema(importedPtr); + /// CArrowSchema.Free(importedPtr); + /// </code> + /// </examples> + public static unsafe Schema ImportSchema(CArrowSchema* ptr) + { + using var importedSchema = new ImportedArrowSchema(ptr); + return importedSchema.GetAsSchema(); + } + + private sealed unsafe class ImportedArrowSchema : IDisposable + { + private readonly CArrowSchema* _data; + private readonly bool _isRoot; + + public ImportedArrowSchema(CArrowSchema* handle) Review Comment: Are we checking the `handle` pointer for `null`? This is passed directly here from a public API. ########## csharp/src/Apache.Arrow/C/CArrowSchemaImporter.cs: ########## @@ -0,0 +1,285 @@ +// 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.IO; +using System.Linq; +using Apache.Arrow.Types; + +namespace Apache.Arrow.C +{ + public static class CArrowSchemaImporter + { + /// <summary> + /// Import C pointer as an <see cref="ArrowType"/>. + /// </summary> + /// <examples> + /// Typically, you will allocate a uninitialized CArrowSchema pointer, + /// pass that to external function, and then use this method to import + /// the result. + /// + /// <code> + /// CArrowSchema* importedPtr = CArrowSchema.New(); + /// foreign_export_function(importedPtr); + /// ArrowType importedType = CArrowSchemaImporter.ImportType(importedPtr); + /// CArrowSchema.Free(importedPtr); + /// </code> + /// </examples> + public static unsafe ArrowType ImportType(CArrowSchema* ptr) + { + using var importedType = new ImportedArrowSchema(ptr); + return importedType.GetAsType(); + } + + /// <summary> + /// Import C pointer as an <see cref="Field"/>. + /// </summary> + /// <examples> + /// Typically, you will allocate a uninitialized CArrowSchema pointer, + /// pass that to external function, and then use this method to import + /// the result. + /// + /// <code> + /// CArrowSchema* importedPtr = CArrowSchema.New(); + /// foreign_export_function(importedPtr); + /// Field importedField = CArrowSchemaImporter.ImportField(importedPtr); + /// CArrowSchema.Free(importedPtr); + /// </code> + /// </examples> + public static unsafe Field ImportField(CArrowSchema* ptr) + { + using var importedField = new ImportedArrowSchema(ptr); + return importedField.GetAsField(); + } + + /// <summary> + /// Import C pointer as an <see cref="Schema"/>. + /// </summary> + /// <examples> + /// Typically, you will allocate a uninitialized CArrowSchema pointer, + /// pass that to external function, and then use this method to import + /// the result. + /// + /// <code> + /// CArrowSchema* importedPtr = CArrowSchema.New(); + /// foreign_export_function(importedPtr); + /// Field importedSchema = CArrowSchemaImporter.ImportSchema(importedPtr); + /// CArrowSchema.Free(importedPtr); + /// </code> + /// </examples> + public static unsafe Schema ImportSchema(CArrowSchema* ptr) + { + using var importedSchema = new ImportedArrowSchema(ptr); + return importedSchema.GetAsSchema(); + } + + private sealed unsafe class ImportedArrowSchema : IDisposable + { + private readonly CArrowSchema* _data; + private readonly bool _isRoot; + + public ImportedArrowSchema(CArrowSchema* handle) + { + _data = (CArrowSchema*)handle; Review Comment: ```suggestion _data = handle; ``` ########## csharp/src/Apache.Arrow/C/CArrowSchemaImporter.cs: ########## @@ -0,0 +1,285 @@ +// 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.IO; +using System.Linq; +using Apache.Arrow.Types; + +namespace Apache.Arrow.C +{ + public static class CArrowSchemaImporter + { + /// <summary> + /// Import C pointer as an <see cref="ArrowType"/>. + /// </summary> + /// <examples> + /// Typically, you will allocate a uninitialized CArrowSchema pointer, + /// pass that to external function, and then use this method to import + /// the result. + /// + /// <code> + /// CArrowSchema* importedPtr = CArrowSchema.New(); + /// foreign_export_function(importedPtr); + /// ArrowType importedType = CArrowSchemaImporter.ImportType(importedPtr); + /// CArrowSchema.Free(importedPtr); + /// </code> + /// </examples> + public static unsafe ArrowType ImportType(CArrowSchema* ptr) + { + using var importedType = new ImportedArrowSchema(ptr); + return importedType.GetAsType(); + } + + /// <summary> + /// Import C pointer as an <see cref="Field"/>. + /// </summary> + /// <examples> + /// Typically, you will allocate a uninitialized CArrowSchema pointer, + /// pass that to external function, and then use this method to import + /// the result. + /// + /// <code> + /// CArrowSchema* importedPtr = CArrowSchema.New(); + /// foreign_export_function(importedPtr); + /// Field importedField = CArrowSchemaImporter.ImportField(importedPtr); + /// CArrowSchema.Free(importedPtr); + /// </code> + /// </examples> + public static unsafe Field ImportField(CArrowSchema* ptr) + { + using var importedField = new ImportedArrowSchema(ptr); + return importedField.GetAsField(); + } + + /// <summary> + /// Import C pointer as an <see cref="Schema"/>. + /// </summary> + /// <examples> + /// Typically, you will allocate a uninitialized CArrowSchema pointer, + /// pass that to external function, and then use this method to import + /// the result. + /// + /// <code> + /// CArrowSchema* importedPtr = CArrowSchema.New(); + /// foreign_export_function(importedPtr); + /// Field importedSchema = CArrowSchemaImporter.ImportSchema(importedPtr); + /// CArrowSchema.Free(importedPtr); + /// </code> + /// </examples> + public static unsafe Schema ImportSchema(CArrowSchema* ptr) + { + using var importedSchema = new ImportedArrowSchema(ptr); + return importedSchema.GetAsSchema(); + } + + private sealed unsafe class ImportedArrowSchema : IDisposable + { + private readonly CArrowSchema* _data; + private readonly bool _isRoot; + + public ImportedArrowSchema(CArrowSchema* handle) + { + _data = (CArrowSchema*)handle; + if (_data->release == null) + { + throw new ArgumentException("Tried to import a schema that has already been released."); + } + _isRoot = true; + } + + public ImportedArrowSchema(CArrowSchema* handle, bool isRoot) : this(handle) + { + _isRoot = isRoot; + } + + public void Dispose() + { + // We only call release on a root-level schema, not child ones. + if (_isRoot && _data->release != null) + { + _data->release(_data); Review Comment: I don't think we should be releasing anything that we don't own. `_data` was passed by the public API, right? We don't own it, we shouldn't dispose of it. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
