From 54f8fb010c28ac0ce594a53a61ebdb8a645ce1db Mon Sep 17 00:00:00 2001 From: Raul Santos Date: Fri, 20 Jan 2023 20:18:56 +0100 Subject: [PATCH] Sync C# Array with Core - Add `AddRange` method. - Add `Fill` method. - Add `Max` and `Min` methods. - Add `PickRandom` method. - Add `Reverse` method. - Add `RecursiveEqual` method. - Add `Sort` method. - Add `Slice` and `GetSliceRange` methods. - Add `IndexOf` overload that takes an index parameter. - Add `LastIndexOf` method. - Add `BinarySearch` method. - Add/update documentation. --- core/variant/array.cpp | 4 +- core/variant/array.h | 4 +- doc/classes/Array.xml | 26 +- .../glue/GodotSharp/GodotSharp/Core/Array.cs | 907 +++++++++++++++++- .../Core/NativeInterop/NativeFuncs.cs | 27 +- modules/mono/glue/runtime_interop.cpp | 89 +- 6 files changed, 1008 insertions(+), 49 deletions(-) diff --git a/core/variant/array.cpp b/core/variant/array.cpp index 94d1596514a..c38af726bdd 100644 --- a/core/variant/array.cpp +++ b/core/variant/array.cpp @@ -612,14 +612,14 @@ void Array::shuffle() { } } -int Array::bsearch(const Variant &p_value, bool p_before) { +int Array::bsearch(const Variant &p_value, bool p_before) const { Variant value = p_value; ERR_FAIL_COND_V(!_p->typed.validate(value, "binary search"), -1); SearchArray avs; return avs.bisect(_p->array.ptrw(), _p->array.size(), value, p_before); } -int Array::bsearch_custom(const Variant &p_value, const Callable &p_callable, bool p_before) { +int Array::bsearch_custom(const Variant &p_value, const Callable &p_callable, bool p_before) const { Variant value = p_value; ERR_FAIL_COND_V(!_p->typed.validate(value, "custom binary search"), -1); diff --git a/core/variant/array.h b/core/variant/array.h index d9ca3278fbb..7b30e57de3b 100644 --- a/core/variant/array.h +++ b/core/variant/array.h @@ -84,8 +84,8 @@ public: void sort(); void sort_custom(const Callable &p_callable); void shuffle(); - int bsearch(const Variant &p_value, bool p_before = true); - int bsearch_custom(const Variant &p_value, const Callable &p_callable, bool p_before = true); + int bsearch(const Variant &p_value, bool p_before = true) const; + int bsearch_custom(const Variant &p_value, const Callable &p_callable, bool p_before = true) const; void reverse(); int find(const Variant &p_value, int p_from = 0) const; diff --git a/doc/classes/Array.xml b/doc/classes/Array.xml index 1ac1c0745eb..994a8b07145 100644 --- a/doc/classes/Array.xml +++ b/doc/classes/Array.xml @@ -207,7 +207,7 @@ [b]Note:[/b] Calling this function is not the same as writing [code]array[-1][/code]. If the array is empty, accessing by index will pause project execution when running from the editor. - + @@ -216,7 +216,7 @@ [b]Note:[/b] Calling [method bsearch] on an unsorted array results in unexpected behavior. - + @@ -269,7 +269,7 @@ array.fill(0) # Initialize the 10 elements to 0. [/gdscript] [csharp] - var array = new Godot.Collections.Array{}; + var array = new Godot.Collections.Array(); array.Resize(10); array.Fill(0); // Initialize the 10 elements to 0. [/csharp] @@ -340,7 +340,7 @@ print(["inside", 7].has("7")) # False [/gdscript] [csharp] - var arr = new Godot.Collections.Array{"inside", 7}; + var arr = new Godot.Collections.Array { "inside", 7 }; // has is renamed to Contains GD.Print(arr.Contains("inside")); // True GD.Print(arr.Contains("outside")); // False @@ -357,7 +357,7 @@ [/gdscript] [csharp] // As there is no "in" keyword in C#, you have to use Contains - var array = new Godot.Collections.Array{2, 4, 6, 8}; + var array = new Godot.Collections.Array { 2, 4, 6, 8 }; if (array.Contains(2)) { GD.Print("Contains!"); @@ -440,10 +440,16 @@ Returns a random value from the target array. - [codeblock] + [codeblocks] + [gdscript] var array: Array[int] = [1, 2, 3, 4] print(array.pick_random()) # Prints either of the four numbers. - [/codeblock] + [/gdscript] + [csharp] + var array = new Godot.Collections.Array { 1, 2, 3, 4 }; + GD.Print(array.PickRandom()); // Prints either of the four numbers. + [/csharp] + [/codeblocks] @@ -562,7 +568,7 @@ Returns the slice of the [Array], from [param begin] (inclusive) to [param end] (exclusive), as a new [Array]. The absolute value of [param begin] and [param end] will be clamped to the array size, so the default value for [param end] makes it slice to the size of the array by default (i.e. [code]arr.slice(1)[/code] is a shorthand for [code]arr.slice(1, arr.size())[/code]). If either [param begin] or [param end] are negative, they will be relative to the end of the array (i.e. [code]arr.slice(0, -2)[/code] is a shorthand for [code]arr.slice(0, arr.size() - 2)[/code]). - If specified, [param step] is the relative index between source elements. It can be negative, then [param begin] must be higher than [param end]. For example, [code][0, 1, 2, 3, 4, 5].slice(5, 1, -2)[/code] returns [code][5, 3][/code]). + If specified, [param step] is the relative index between source elements. It can be negative, then [param begin] must be higher than [param end]. For example, [code][0, 1, 2, 3, 4, 5].slice(5, 1, -2)[/code] returns [code][5, 3][/code]. If [param deep] is true, each element will be copied by value rather than by reference. @@ -579,7 +585,9 @@ print(strings) # Prints [string1, string10, string11, string2] [/gdscript] [csharp] - // There is no sort support for Godot.Collections.Array + var strings = new Godot.Collections.Array { "string1", "string2", "string10", "string11" }; + strings.Sort(); + GD.Print(strings); // Prints [string1, string10, string11, string2] [/csharp] [/codeblocks] To perform natural order sorting, you can use [method sort_custom] with [method String.naturalnocasecmp_to] as follows: diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs index a61c5403b90..8598c32760e 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Collections; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Runtime.CompilerServices; using Godot.NativeInterop; @@ -174,7 +175,15 @@ namespace Godot.Collections } /// - /// Duplicates this . + /// Returns a copy of the . + /// If is , a deep copy if performed: + /// all nested arrays and dictionaries are duplicated and will not be shared with + /// the original array. If , a shallow copy is made and + /// references to the original nested arrays and dictionaries are kept, so that + /// modifying a sub-array or dictionary in the copy will also impact those + /// referenced in the source array. Note that any derived + /// elements will be shallow copied regardless of the + /// setting. /// /// If , performs a deep copy. /// A new Godot Array. @@ -187,7 +196,102 @@ namespace Godot.Collections } /// - /// Resizes this to the given size. + /// Assigns the given value to all elements in the array. This can typically be + /// used together with to create an array with a given + /// size and initialized elements. + /// Note: If is of a reference type ( + /// derived, or , etc.) then the array + /// is filled with the references to the same object, i.e. no duplicates are + /// created. + /// + /// + /// + /// var array = new Godot.Collections.Array(); + /// array.Resize(10); + /// array.Fill(0); // Initialize the 10 elements to 0. + /// + /// + /// + /// The array is read-only. + /// + /// The value to fill the array with. + public void Fill(Variant value) + { + ThrowIfReadOnly(); + + godot_variant variantValue = (godot_variant)value.NativeVar; + var self = (godot_array)NativeValue; + NativeFuncs.godotsharp_array_fill(ref self, variantValue); + } + + /// + /// Returns the maximum value contained in the array if all elements are of + /// comparable types. If the elements can't be compared, + /// is returned. + /// + /// The maximum value contained in the array. + public Variant Max() + { + godot_variant resVariant; + var self = (godot_array)NativeValue; + NativeFuncs.godotsharp_array_max(ref self, out resVariant); + return Variant.CreateTakingOwnershipOfDisposableValue(resVariant); + } + + /// + /// Returns the minimum value contained in the array if all elements are of + /// comparable types. If the elements can't be compared, + /// is returned. + /// + /// The minimum value contained in the array. + public Variant Min() + { + godot_variant resVariant; + var self = (godot_array)NativeValue; + NativeFuncs.godotsharp_array_min(ref self, out resVariant); + return Variant.CreateTakingOwnershipOfDisposableValue(resVariant); + } + + /// + /// Returns a random value from the target array. + /// + /// + /// + /// var array = new Godot.Collections.Array { 1, 2, 3, 4 }; + /// GD.Print(array.PickRandom()); // Prints either of the four numbers. + /// + /// + /// A random element from the array. + public Variant PickRandom() + { + godot_variant resVariant; + var self = (godot_array)NativeValue; + NativeFuncs.godotsharp_array_pick_random(ref self, out resVariant); + return Variant.CreateTakingOwnershipOfDisposableValue(resVariant); + } + + /// + /// Compares this against the + /// recursively. Returns if the + /// sizes and contents of the arrays are equal, + /// otherwise. + /// + /// The other array to compare against. + /// + /// if the sizes and contents of the arrays are equal, + /// otherwise. + /// + public bool RecursiveEqual(Array other) + { + var self = (godot_array)NativeValue; + var otherVariant = (godot_array)other.NativeValue; + return NativeFuncs.godotsharp_array_recursive_equal(ref self, otherVariant).ToBool(); + } + + /// + /// Resizes the array to contain a different number of elements. If the array + /// size is smaller, elements are cleared, if bigger, new elements are + /// . /// /// /// The array is read-only. @@ -203,7 +307,25 @@ namespace Godot.Collections } /// - /// Shuffles the contents of this into a random order. + /// Reverses the order of the elements in the array. + /// + /// + /// The array is read-only. + /// + public void Reverse() + { + ThrowIfReadOnly(); + + var self = (godot_array)NativeValue; + NativeFuncs.godotsharp_array_reverse(ref self); + } + + /// + /// Shuffles the array such that the items will have a random order. + /// This method uses the global random number generator common to methods + /// such as . Call to + /// ensure that a new seed will be used each time if you want + /// non-reproducible shuffling. /// /// /// The array is read-only. @@ -217,7 +339,104 @@ namespace Godot.Collections } /// - /// Concatenates these two s. + /// Creates a shallow copy of a range of elements in the source . + /// + /// + /// is less than 0 or greater than the array's size. + /// + /// The zero-based index at which the range starts. + /// A new array that contains the elements inside the slice range. + public Array Slice(int start) + { + if (start < 0 || start > Count) + throw new ArgumentOutOfRangeException(nameof(start)); + + return GetSliceRange(start, Count, step: 1, deep: false); + } + + /// + /// Creates a shallow copy of a range of elements in the source . + /// + /// + /// is less than 0 or greater than the array's size. + /// -or- + /// is less than 0 or greater than the array's size. + /// + /// The zero-based index at which the range starts. + /// The length of the range. + /// A new array that contains the elements inside the slice range. + // The Slice method must have this signature to get implicit Range support. + public Array Slice(int start, int length) + { + if (start < 0 || start > Count) + throw new ArgumentOutOfRangeException(nameof(start)); + + if (length < 0 || length > Count) + throw new ArgumentOutOfRangeException(nameof(start)); + + return GetSliceRange(start, start + length, step: 1, deep: false); + } + + /// + /// Returns the slice of the , from + /// (inclusive) to (exclusive), as a new . + /// The absolute value of and + /// will be clamped to the array size. + /// If either or are negative, they + /// will be relative to the end of the array (i.e. arr.GetSliceRange(0, -2) + /// is a shorthand for arr.GetSliceRange(0, arr.Count - 2)). + /// If specified, is the relative index between source + /// elements. It can be negative, then must be higher than + /// . For example, [0, 1, 2, 3, 4, 5].GetSliceRange(5, 1, -2) + /// returns [5, 3]. + /// If is true, each element will be copied by value + /// rather than by reference. + /// + /// The zero-based index at which the range starts. + /// The zero-based index at which the range ends. + /// The relative index between source elements to take. + /// If , performs a deep copy. + /// A new array that contains the elements inside the slice range. + public Array GetSliceRange(int start, int end, int step = 1, bool deep = false) + { + godot_array newArray; + var self = (godot_array)NativeValue; + NativeFuncs.godotsharp_array_slice(ref self, start, end, step, deep.ToGodotBool(), out newArray); + return CreateTakingOwnershipOfDisposableValue(newArray); + } + + /// + /// Sorts the array. + /// Note: The sorting algorithm used is not stable. This means that values + /// considered equal may have their order changed when using . + /// Note: Strings are sorted in alphabetical order (as opposed to natural order). + /// This may lead to unexpected behavior when sorting an array of strings ending + /// with a sequence of numbers. + /// To sort with a custom predicate use + /// . + /// + /// + /// + /// var strings = new Godot.Collections.Array { "string1", "string2", "string10", "string11" }; + /// strings.Sort(); + /// GD.Print(strings); // Prints [string1, string10, string11, string2] + /// + /// + /// + /// The array is read-only. + /// + public void Sort() + { + ThrowIfReadOnly(); + + var self = (godot_array)NativeValue; + NativeFuncs.godotsharp_array_sort(ref self); + } + + /// + /// Concatenates two s together, with the + /// being added to the end of the specified in . + /// For example, [1, 2] + [3, 4] results in [1, 2, 3, 4]. /// /// The first array. /// The second array. @@ -253,6 +472,9 @@ namespace Godot.Collections /// /// The property is assigned and the array is read-only. /// + /// + /// is less than 0 or greater than the array's size. + /// /// The item at the given . public unsafe Variant this[int index] { @@ -294,14 +516,146 @@ namespace Godot.Collections } /// - /// Checks if this contains the given item. + /// Adds the elements of the specified collection to the end of this . /// + /// + /// The array is read-only. + /// + /// + /// The is . + /// + /// Collection of items to add. + public void AddRange<[MustBeVariant] T>(IEnumerable collection) + { + ThrowIfReadOnly(); + + if (collection == null) + throw new ArgumentNullException(nameof(collection), "Value cannot be null."); + + // If the collection is another Godot Array, we can add the items + // with a single interop call. + if (collection is Array array) + { + var self = (godot_array)NativeValue; + var collectionNative = (godot_array)array.NativeValue; + _ = NativeFuncs.godotsharp_array_add_range(ref self, collectionNative); + return; + } + if (collection is Array typedArray) + { + var self = (godot_array)NativeValue; + var collectionNative = (godot_array)typedArray.NativeValue; + _ = NativeFuncs.godotsharp_array_add_range(ref self, collectionNative); + return; + } + + // If we can retrieve the count of the collection without enumerating it + // (e.g.: the collections is a List), use it to resize the array once + // instead of growing it as we add items. + if (collection.TryGetNonEnumeratedCount(out int count)) + { + Resize(Count + count); + + using var enumerator = collection.GetEnumerator(); + + for (int i = 0; i < count; i++) + { + enumerator.MoveNext(); + this[count + i] = Variant.From(enumerator.Current); + } + + return; + } + + foreach (var item in collection) + { + Add(Variant.From(item)); + } + } + + /// + /// Finds the index of an existing value using binary search. + /// If the value is not present in the array, it returns the bitwise + /// complement of the insertion index that maintains sorting order. + /// Note: Calling on an + /// unsorted array results in unexpected behavior. + /// + /// + /// is less than 0. + /// -or- + /// is less than 0. + /// + /// + /// and do not denote + /// a valid range in the . + /// + /// The starting index of the range to search. + /// The length of the range to search. + /// The object to locate. + /// + /// The index of the item in the array, if is found; + /// otherwise, a negative number that is the bitwise complement of the index + /// of the next element that is larger than or, if + /// there is no larger element, the bitwise complement of . + /// + public int BinarySearch(int index, int count, Variant item) + { + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index), "index cannot be negative."); + if (count < 0) + throw new ArgumentOutOfRangeException(nameof(count), "count cannot be negative."); + if (Count - index < count) + throw new ArgumentException("length is out of bounds or count is greater than the number of elements."); + + if (Count == 0) + { + // Special case for empty array to avoid an interop call. + return -1; + } + + godot_variant variantValue = (godot_variant)item.NativeVar; + var self = (godot_array)NativeValue; + return NativeFuncs.godotsharp_array_binary_search(ref self, index, count, variantValue); + } + + /// + /// Finds the index of an existing value using binary search. + /// If the value is not present in the array, it returns the bitwise + /// complement of the insertion index that maintains sorting order. + /// Note: Calling on an unsorted + /// array results in unexpected behavior. + /// + /// The object to locate. + /// + /// The index of the item in the array, if is found; + /// otherwise, a negative number that is the bitwise complement of the index + /// of the next element that is larger than or, if + /// there is no larger element, the bitwise complement of . + /// + public int BinarySearch(Variant item) + { + return BinarySearch(0, Count, item); + } + + /// + /// Returns if the array contains the given value. + /// + /// + /// + /// var arr = new Godot.Collections.Array { "inside", 7 }; + /// GD.Print(arr.Contains("inside")); // True + /// GD.Print(arr.Contains("outside")); // False + /// GD.Print(arr.Contains(7)); // True + /// GD.Print(arr.Contains("7")); // False + /// + /// /// The item to look for. /// Whether or not this array contains the given item. public bool Contains(Variant item) => IndexOf(item) != -1; /// - /// Erases all items from this . + /// Clears the array. This is the equivalent to using + /// with a size of 0 /// /// /// The array is read-only. @@ -309,27 +663,104 @@ namespace Godot.Collections public void Clear() => Resize(0); /// - /// Searches this for an item - /// and returns its index or -1 if not found. + /// Searches the array for a value and returns its index or -1 if not found. /// /// The item to search for. /// The index of the item, or -1 if not found. public int IndexOf(Variant item) { + if (Count == 0) + { + // Special case for empty array to avoid an interop call. + return -1; + } + godot_variant variantValue = (godot_variant)item.NativeVar; var self = (godot_array)NativeValue; return NativeFuncs.godotsharp_array_index_of(ref self, variantValue); } /// - /// Inserts a new item at a given position in the array. - /// The position must be a valid position of an existing item, - /// or the position at the end of the array. + /// Searches the array for a value and returns its index or -1 if not found. + /// + /// + /// is less than 0 or greater than the array's size. + /// + /// The item to search for. + /// The initial search index to start from. + /// The index of the item, or -1 if not found. + public int IndexOf(Variant item, int index) + { + if (index < 0 || index > Count) + throw new ArgumentOutOfRangeException(nameof(index)); + + if (Count == 0) + { + // Special case for empty array to avoid an interop call. + return -1; + } + + godot_variant variantValue = (godot_variant)item.NativeVar; + var self = (godot_array)NativeValue; + return NativeFuncs.godotsharp_array_index_of(ref self, variantValue, index); + } + + /// + /// Searches the array for a value in reverse order and returns its index + /// or -1 if not found. + /// + /// The item to search for. + /// The index of the item, or -1 if not found. + public int LastIndexOf(Variant item) + { + if (Count == 0) + { + // Special case for empty array to avoid an interop call. + return -1; + } + + godot_variant variantValue = (godot_variant)item.NativeVar; + var self = (godot_array)NativeValue; + return NativeFuncs.godotsharp_array_last_index_of(ref self, variantValue, Count - 1); + } + + /// + /// Searches the array for a value in reverse order and returns its index + /// or -1 if not found. + /// + /// + /// is less than 0 or greater than the array's size. + /// + /// The item to search for. + /// The initial search index to start from. + /// The index of the item, or -1 if not found. + public int LastIndexOf(Variant item, int index) + { + if (index < 0 || index >= Count) + throw new ArgumentOutOfRangeException(nameof(index)); + + if (Count == 0) + { + // Special case for empty array to avoid an interop call. + return -1; + } + + godot_variant variantValue = (godot_variant)item.NativeVar; + var self = (godot_array)NativeValue; + return NativeFuncs.godotsharp_array_last_index_of(ref self, variantValue, index); + } + + /// + /// Inserts a new element at a given position in the array. The position + /// must be valid, or at the end of the array (pos == Count - 1). /// Existing items will be moved to the right. /// /// /// The array is read-only. /// + /// + /// is less than 0 or greater than the array's size. + /// /// The index to insert at. /// The item to insert. public void Insert(int index, Variant item) @@ -367,11 +798,16 @@ namespace Godot.Collections } /// - /// Removes an element from this by index. + /// Removes an element from the array by index. + /// To remove an element by searching for its value, use + /// instead. /// /// /// The array is read-only. /// + /// + /// is less than 0 or greater than the array's size. + /// /// The index of the element to remove. public void RemoveAt(int index) { @@ -424,6 +860,9 @@ namespace Godot.Collections /// Copies the elements of this to the given /// C# array, starting at the given index. /// + /// + /// is less than 0 or greater than the array's size. + /// /// The array to copy to. /// The index to start at. public void CopyTo(Variant[] array, int arrayIndex) @@ -518,6 +957,9 @@ namespace Godot.Collections /// /// The variant returned via the parameter is owned by the Array and must not be disposed. /// + /// + /// is less than 0 or greater than the array's size. + /// internal void GetVariantBorrowElementAt(int index, out godot_variant elem) { if (index < 0 || index >= Count) @@ -657,6 +1099,97 @@ namespace Godot.Collections return new Array(_underlyingArray.Duplicate(deep)); } + /// + /// Assigns the given value to all elements in the array. This can typically be + /// used together with to create an array with a given + /// size and initialized elements. + /// Note: If is of a reference type ( + /// derived, or , etc.) then the array + /// is filled with the references to the same object, i.e. no duplicates are + /// created. + /// + /// + /// + /// var array = new Godot.Collections.Array<int>(); + /// array.Resize(10); + /// array.Fill(0); // Initialize the 10 elements to 0. + /// + /// + /// + /// The array is read-only. + /// + /// The value to fill the array with. + public void Fill(T value) + { + ThrowIfReadOnly(); + + godot_variant variantValue = VariantUtils.CreateFrom(value); + var self = (godot_array)_underlyingArray.NativeValue; + NativeFuncs.godotsharp_array_fill(ref self, variantValue); + } + + /// + /// Returns the maximum value contained in the array if all elements are of + /// comparable types. If the elements can't be compared, + /// is returned. + /// + /// The maximum value contained in the array. + public T Max() + { + godot_variant resVariant; + var self = (godot_array)_underlyingArray.NativeValue; + NativeFuncs.godotsharp_array_max(ref self, out resVariant); + return VariantUtils.ConvertTo(resVariant); + } + + /// + /// Returns the minimum value contained in the array if all elements are of + /// comparable types. If the elements can't be compared, + /// is returned. + /// + /// The minimum value contained in the array. + public T Min() + { + godot_variant resVariant; + var self = (godot_array)_underlyingArray.NativeValue; + NativeFuncs.godotsharp_array_min(ref self, out resVariant); + return VariantUtils.ConvertTo(resVariant); + } + + /// + /// Returns a random value from the target array. + /// + /// + /// + /// var array = new Godot.Collections.Array<int> { 1, 2, 3, 4 }; + /// GD.Print(array.PickRandom()); // Prints either of the four numbers. + /// + /// + /// A random element from the array. + public T PickRandom() + { + godot_variant resVariant; + var self = (godot_array)_underlyingArray.NativeValue; + NativeFuncs.godotsharp_array_pick_random(ref self, out resVariant); + return VariantUtils.ConvertTo(resVariant); + } + + /// + /// Compares this against the + /// recursively. Returns if the + /// sizes and contents of the arrays are equal, + /// otherwise. + /// + /// The other array to compare against. + /// + /// if the sizes and contents of the arrays are equal, + /// otherwise. + /// + public bool RecursiveEqual(Array other) + { + return _underlyingArray.RecursiveEqual(other._underlyingArray); + } + /// /// Resizes this to the given size. /// @@ -671,7 +1204,22 @@ namespace Godot.Collections } /// - /// Shuffles the contents of this into a random order. + /// Reverses the order of the elements in the array. + /// + /// + /// The array is read-only. + /// + public void Reverse() + { + _underlyingArray.Reverse(); + } + + /// + /// Shuffles the array such that the items will have a random order. + /// This method uses the global random number generator common to methods + /// such as . Call to + /// ensure that a new seed will be used each time if you want + /// non-reproducible shuffling. /// /// /// The array is read-only. @@ -682,7 +1230,89 @@ namespace Godot.Collections } /// - /// Concatenates these two s. + /// Creates a shallow copy of a range of elements in the source . + /// + /// + /// is less than 0 or greater than the array's size. + /// + /// The zero-based index at which the range starts. + /// A new array that contains the elements inside the slice range. + public Array Slice(int start) + { + return GetSliceRange(start, Count, step: 1, deep: false); + } + + /// + /// Creates a shallow copy of a range of elements in the source . + /// + /// + /// is less than 0 or greater than the array's size. + /// -or- + /// is less than 0 or greater than the array's size. + /// + /// The zero-based index at which the range starts. + /// The length of the range. + /// A new array that contains the elements inside the slice range. + // The Slice method must have this signature to get implicit Range support. + public Array Slice(int start, int length) + { + return GetSliceRange(start, start + length, step: 1, deep: false); + } + + /// + /// Returns the slice of the , from + /// (inclusive) to (exclusive), as a new . + /// The absolute value of and + /// will be clamped to the array size. + /// If either or are negative, they + /// will be relative to the end of the array (i.e. arr.GetSliceRange(0, -2) + /// is a shorthand for arr.GetSliceRange(0, arr.Count - 2)). + /// If specified, is the relative index between source + /// elements. It can be negative, then must be higher than + /// . For example, [0, 1, 2, 3, 4, 5].GetSliceRange(5, 1, -2) + /// returns [5, 3]. + /// If is true, each element will be copied by value + /// rather than by reference. + /// + /// The zero-based index at which the range starts. + /// The zero-based index at which the range ends. + /// The relative index between source elements to take. + /// If , performs a deep copy. + /// A new array that contains the elements inside the slice range. + public Array GetSliceRange(int start, int end, int step = 1, bool deep = false) + { + return new Array(_underlyingArray.GetSliceRange(start, end, step, deep)); + } + + /// + /// Sorts the array. + /// Note: The sorting algorithm used is not stable. This means that values + /// considered equal may have their order changed when using . + /// Note: Strings are sorted in alphabetical order (as opposed to natural order). + /// This may lead to unexpected behavior when sorting an array of strings ending + /// with a sequence of numbers. + /// To sort with a custom predicate use + /// . + /// + /// + /// + /// var strings = new Godot.Collections.Array<string> { "string1", "string2", "string10", "string11" }; + /// strings.Sort(); + /// GD.Print(strings); // Prints [string1, string10, string11, string2] + /// + /// + /// + /// The array is read-only. + /// + public void Sort() + { + _underlyingArray.Sort(); + } + + /// + /// Concatenates two s together, with the + /// being added to the end of the specified in . + /// For example, [1, 2] + [3, 4] results in [1, 2, 3, 4]. /// /// The first array. /// The second array. @@ -706,12 +1336,15 @@ namespace Godot.Collections // IList /// - /// Returns the value at the given . + /// Returns the item at the given . /// /// /// The property is assigned and the array is read-only. /// - /// The value at the given . + /// + /// is less than 0 or greater than the array's size. + /// + /// The item at the given . public unsafe T this[int index] { get @@ -735,29 +1368,106 @@ namespace Godot.Collections } /// - /// Searches this for an item - /// and returns its index or -1 if not found. + /// Searches the array for a value and returns its index or -1 if not found. /// - /// The item to search for. + /// The item to search for. /// The index of the item, or -1 if not found. public int IndexOf(T item) { + if (Count == 0) + { + // Special case for empty array to avoid an interop call. + return -1; + } + using var variantValue = VariantUtils.CreateFrom(item); var self = (godot_array)_underlyingArray.NativeValue; return NativeFuncs.godotsharp_array_index_of(ref self, variantValue); } /// - /// Inserts a new item at a given position in the . - /// The position must be a valid position of an existing item, - /// or the position at the end of the array. + /// Searches the array for a value and returns its index or -1 if not found. + /// + /// + /// is less than 0 or greater than the array's size. + /// + /// The item to search for. + /// The initial search index to start from. + /// The index of the item, or -1 if not found. + public int IndexOf(T item, int index) + { + if (index < 0 || index > Count) + throw new ArgumentOutOfRangeException(nameof(index)); + + if (Count == 0) + { + // Special case for empty array to avoid an interop call. + return -1; + } + + godot_variant variantValue = VariantUtils.CreateFrom(item); + var self = (godot_array)_underlyingArray.NativeValue; + return NativeFuncs.godotsharp_array_index_of(ref self, variantValue, index); + } + + /// + /// Searches the array for a value in reverse order and returns its index + /// or -1 if not found. + /// + /// The item to search for. + /// The index of the item, or -1 if not found. + public int LastIndexOf(Variant item) + { + if (Count == 0) + { + // Special case for empty array to avoid an interop call. + return -1; + } + + godot_variant variantValue = VariantUtils.CreateFrom(item); + var self = (godot_array)_underlyingArray.NativeValue; + return NativeFuncs.godotsharp_array_last_index_of(ref self, variantValue, Count - 1); + } + + /// + /// Searches the array for a value in reverse order and returns its index + /// or -1 if not found. + /// + /// + /// is less than 0 or greater than the array's size. + /// + /// The item to search for. + /// The initial search index to start from. + /// The index of the item, or -1 if not found. + public int LastIndexOf(Variant item, int index) + { + if (index < 0 || index >= Count) + throw new ArgumentOutOfRangeException(nameof(index)); + + if (Count == 0) + { + // Special case for empty array to avoid an interop call. + return -1; + } + + godot_variant variantValue = VariantUtils.CreateFrom(item); + var self = (godot_array)_underlyingArray.NativeValue; + return NativeFuncs.godotsharp_array_last_index_of(ref self, variantValue, index); + } + + /// + /// Inserts a new element at a given position in the array. The position + /// must be valid, or at the end of the array (pos == Count - 1). /// Existing items will be moved to the right. /// /// /// The array is read-only. /// + /// + /// is less than 0 or greater than the array's size. + /// /// The index to insert at. - /// The item to insert. + /// The item to insert. public void Insert(int index, T item) { ThrowIfReadOnly(); @@ -771,11 +1481,16 @@ namespace Godot.Collections } /// - /// Removes an element from this by index. + /// Removes an element from the array by index. + /// To remove an element by searching for its value, use + /// instead. /// /// /// The array is read-only. /// + /// + /// is less than 0 or greater than the array's size. + /// /// The index of the element to remove. public void RemoveAt(int index) { @@ -814,8 +1529,7 @@ namespace Godot.Collections /// /// The array is read-only. /// - /// The item to add. - /// The new size after adding the item. + /// The item to add. public void Add(T item) { ThrowIfReadOnly(); @@ -826,7 +1540,130 @@ namespace Godot.Collections } /// - /// Erases all items from this . + /// Adds the elements of the specified collection to the end of this . + /// + /// + /// The array is read-only. + /// + /// + /// The is . + /// + /// Collection of items to add. + public void AddRange(IEnumerable collection) + { + ThrowIfReadOnly(); + + if (collection == null) + throw new ArgumentNullException(nameof(collection), "Value cannot be null."); + + // If the collection is another Godot Array, we can add the items + // with a single interop call. + if (collection is Array array) + { + var self = (godot_array)_underlyingArray.NativeValue; + var collectionNative = (godot_array)array.NativeValue; + _ = NativeFuncs.godotsharp_array_add_range(ref self, collectionNative); + return; + } + if (collection is Array typedArray) + { + var self = (godot_array)_underlyingArray.NativeValue; + var collectionNative = (godot_array)typedArray._underlyingArray.NativeValue; + _ = NativeFuncs.godotsharp_array_add_range(ref self, collectionNative); + return; + } + + // If we can retrieve the count of the collection without enumerating it + // (e.g.: the collections is a List), use it to resize the array once + // instead of growing it as we add items. + if (collection.TryGetNonEnumeratedCount(out int count)) + { + Resize(Count + count); + + using var enumerator = collection.GetEnumerator(); + + for (int i = 0; i < count; i++) + { + enumerator.MoveNext(); + this[count + i] = enumerator.Current; + } + + return; + } + + foreach (var item in collection) + { + Add(item); + } + } + + /// + /// Finds the index of an existing value using binary search. + /// If the value is not present in the array, it returns the bitwise + /// complement of the insertion index that maintains sorting order. + /// Note: Calling on an unsorted + /// array results in unexpected behavior. + /// + /// + /// is less than 0. + /// -or- + /// is less than 0. + /// + /// + /// and do not denote + /// a valid range in the . + /// + /// The starting index of the range to search. + /// The length of the range to search. + /// The object to locate. + /// + /// The index of the item in the array, if is found; + /// otherwise, a negative number that is the bitwise complement of the index + /// of the next element that is larger than or, if + /// there is no larger element, the bitwise complement of . + /// + public int BinarySearch(int index, int count, T item) + { + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index), "index cannot be negative."); + if (count < 0) + throw new ArgumentOutOfRangeException(nameof(count), "count cannot be negative."); + if (Count - index < count) + throw new ArgumentException("length is out of bounds or count is greater than the number of elements."); + + if (Count == 0) + { + // Special case for empty array to avoid an interop call. + return -1; + } + + using var variantValue = VariantUtils.CreateFrom(item); + var self = (godot_array)_underlyingArray.NativeValue; + return NativeFuncs.godotsharp_array_binary_search(ref self, index, count, variantValue); + } + + /// + /// Finds the index of an existing value using binary search. + /// If the value is not present in the array, it returns the bitwise + /// complement of the insertion index that maintains sorting order. + /// Note: Calling on an unsorted + /// array results in unexpected behavior. + /// + /// The object to locate. + /// + /// The index of the item in the array, if is found; + /// otherwise, a negative number that is the bitwise complement of the index + /// of the next element that is larger than or, if + /// there is no larger element, the bitwise complement of . + /// + public int BinarySearch(T item) + { + return BinarySearch(0, Count, item); + } + + /// + /// Clears the array. This is the equivalent to using + /// with a size of 0 /// /// /// The array is read-only. @@ -837,8 +1674,17 @@ namespace Godot.Collections } /// - /// Checks if this contains the given item. + /// Returns if the array contains the given value. /// + /// + /// + /// var arr = new Godot.Collections.Array<string> { "inside", "7" }; + /// GD.Print(arr.Contains("inside")); // True + /// GD.Print(arr.Contains("outside")); // False + /// GD.Print(arr.Contains(7)); // False + /// GD.Print(arr.Contains("7")); // True + /// + /// /// The item to look for. /// Whether or not this array contains the given item. public bool Contains(T item) => IndexOf(item) != -1; @@ -847,6 +1693,9 @@ namespace Godot.Collections /// Copies the elements of this to the given /// C# array, starting at the given index. /// + /// + /// is less than 0 or greater than the array's size. + /// /// The C# array to copy to. /// The index to start at. public void CopyTo(T[] array, int arrayIndex) @@ -876,7 +1725,7 @@ namespace Godot.Collections } /// - /// Removes the first occurrence of the specified value + /// Removes the first occurrence of the specified /// from this . /// /// diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.cs index 1e23689c954..ac1d8d34656 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.cs @@ -365,21 +365,44 @@ namespace Godot.NativeInterop public static partial int godotsharp_array_add(ref godot_array p_self, in godot_variant p_item); + public static partial int godotsharp_array_add_range(ref godot_array p_self, in godot_array p_collection); + + public static partial int godotsharp_array_binary_search(ref godot_array p_self, int p_index, int p_count, in godot_variant p_value); + public static partial void godotsharp_array_duplicate(ref godot_array p_self, godot_bool p_deep, out godot_array r_dest); - public static partial int godotsharp_array_index_of(ref godot_array p_self, in godot_variant p_item); + public static partial void godotsharp_array_fill(ref godot_array p_self, in godot_variant p_value); + + public static partial int godotsharp_array_index_of(ref godot_array p_self, in godot_variant p_item, int p_index = 0); public static partial void godotsharp_array_insert(ref godot_array p_self, int p_index, in godot_variant p_item); + public static partial int godotsharp_array_last_index_of(ref godot_array p_self, in godot_variant p_item, int p_index); + + public static partial void godotsharp_array_make_read_only(ref godot_array p_self); + + public static partial void godotsharp_array_max(ref godot_array p_self, out godot_variant r_value); + + public static partial void godotsharp_array_min(ref godot_array p_self, out godot_variant r_value); + + public static partial void godotsharp_array_pick_random(ref godot_array p_self, out godot_variant r_value); + + public static partial godot_bool godotsharp_array_recursive_equal(ref godot_array p_self, in godot_array p_other); + public static partial void godotsharp_array_remove_at(ref godot_array p_self, int p_index); public static partial Error godotsharp_array_resize(ref godot_array p_self, int p_new_size); - public static partial void godotsharp_array_make_read_only(ref godot_array p_self); + public static partial void godotsharp_array_reverse(ref godot_array p_self); public static partial void godotsharp_array_shuffle(ref godot_array p_self); + public static partial void godotsharp_array_slice(ref godot_array p_self, int p_start, int p_end, + int p_step, godot_bool p_deep, out godot_array r_dest); + + public static partial void godotsharp_array_sort(ref godot_array p_self); + public static partial void godotsharp_array_to_string(ref godot_array p_self, out godot_string r_str); // Dictionary diff --git a/modules/mono/glue/runtime_interop.cpp b/modules/mono/glue/runtime_interop.cpp index d17fe3e75ff..c46503df953 100644 --- a/modules/mono/glue/runtime_interop.cpp +++ b/modules/mono/glue/runtime_interop.cpp @@ -992,18 +992,78 @@ int32_t godotsharp_array_add(Array *p_self, const Variant *p_item) { return p_self->size(); } +int32_t godotsharp_array_add_range(Array *p_self, const Array *p_collection) { + p_self->append_array(*p_collection); + return p_self->size(); +} + +int32_t godotsharp_array_binary_search(const Array *p_self, int32_t p_index, int32_t p_length, const Variant *p_value) { + ERR_FAIL_COND_V(p_index < 0, -1); + ERR_FAIL_COND_V(p_length < 0, -1); + ERR_FAIL_COND_V(p_self->size() - p_index < p_length, -1); + + const Variant &value = *p_value; + const Array &array = *p_self; + + int lo = p_index; + int hi = p_index + p_length - 1; + while (lo <= hi) { + int mid = lo + ((hi - lo) >> 1); + const Variant &mid_item = array[mid]; + + if (mid_item == value) { + return mid; + } + if (mid_item < value) { + lo = mid + 1; + } else { + hi = mid - 1; + } + } + + return ~lo; +} + void godotsharp_array_duplicate(const Array *p_self, bool p_deep, Array *r_dest) { memnew_placement(r_dest, Array(p_self->duplicate(p_deep))); } -int32_t godotsharp_array_index_of(const Array *p_self, const Variant *p_item) { - return p_self->find(*p_item); +void godotsharp_array_fill(Array *p_self, const Variant *p_value) { + p_self->fill(*p_value); +} + +int32_t godotsharp_array_index_of(const Array *p_self, const Variant *p_item, int32_t p_index = 0) { + return p_self->find(*p_item, p_index); } void godotsharp_array_insert(Array *p_self, int32_t p_index, const Variant *p_item) { p_self->insert(p_index, *p_item); } +int32_t godotsharp_array_last_index_of(const Array *p_self, const Variant *p_item, int32_t p_index) { + return p_self->rfind(*p_item, p_index); +} + +void godotsharp_array_make_read_only(Array *p_self) { + p_self->make_read_only(); +} + +void godotsharp_array_max(const Array *p_self, Variant *r_value) { + *r_value = p_self->max(); +} + +void godotsharp_array_min(const Array *p_self, Variant *r_value) { + *r_value = p_self->min(); +} + +void godotsharp_array_pick_random(const Array *p_self, Variant *r_value) { + *r_value = p_self->pick_random(); +} + +bool godotsharp_array_recursive_equal(const Array *p_self, const Array *p_other) { + return p_self->recursive_equal(*p_other, 0); +} + void godotsharp_array_remove_at(Array *p_self, int32_t p_index) { p_self->remove_at(p_index); } @@ -1012,14 +1072,22 @@ int32_t godotsharp_array_resize(Array *p_self, int32_t p_new_size) { return (int32_t)p_self->resize(p_new_size); } -void godotsharp_array_make_read_only(Array *p_self) { - p_self->make_read_only(); +void godotsharp_array_reverse(Array *p_self) { + p_self->reverse(); } void godotsharp_array_shuffle(Array *p_self) { p_self->shuffle(); } +void godotsharp_array_slice(Array *p_self, int32_t p_start, int32_t p_end, int32_t p_step, bool p_deep, Array *r_dest) { + memnew_placement(r_dest, Array(p_self->slice(p_start, p_end, p_step, p_deep))); +} + +void godotsharp_array_sort(Array *p_self) { + p_self->sort(); +} + void godotsharp_array_to_string(const Array *p_self, String *r_str) { *r_str = Variant(*p_self).operator String(); } @@ -1442,13 +1510,24 @@ static const void *unmanaged_callbacks[]{ (void *)godotsharp_array_destroy, (void *)godotsharp_dictionary_destroy, (void *)godotsharp_array_add, + (void *)godotsharp_array_add_range, + (void *)godotsharp_array_binary_search, (void *)godotsharp_array_duplicate, + (void *)godotsharp_array_fill, (void *)godotsharp_array_index_of, (void *)godotsharp_array_insert, + (void *)godotsharp_array_last_index_of, + (void *)godotsharp_array_make_read_only, + (void *)godotsharp_array_max, + (void *)godotsharp_array_min, + (void *)godotsharp_array_pick_random, + (void *)godotsharp_array_recursive_equal, (void *)godotsharp_array_remove_at, (void *)godotsharp_array_resize, - (void *)godotsharp_array_make_read_only, + (void *)godotsharp_array_reverse, (void *)godotsharp_array_shuffle, + (void *)godotsharp_array_slice, + (void *)godotsharp_array_sort, (void *)godotsharp_array_to_string, (void *)godotsharp_dictionary_try_get_value, (void *)godotsharp_dictionary_set_value,