File size: 27,873 Bytes
18a519f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 | using System;
using System.Collections.Generic;
using System.Linq;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
namespace UnityEngine.InputSystem.Utilities
{
/// <summary>
/// A collection of utility functions for working with arrays.
/// </summary>
/// <remarks>
/// The goal of this collection is to make it easy to use arrays directly rather than resorting to
/// <see cref="List{T}"/>.
/// </remarks>
internal static class ArrayHelpers
{
public static int LengthSafe<TValue>(this TValue[] array)
{
if (array == null)
return 0;
return array.Length;
}
public static void Clear<TValue>(this TValue[] array)
{
if (array == null)
return;
Array.Clear(array, 0, array.Length);
}
public static void Clear<TValue>(this TValue[] array, int count)
{
if (array == null)
return;
Array.Clear(array, 0, count);
}
public static void Clear<TValue>(this TValue[] array, ref int count)
{
if (array == null)
return;
Array.Clear(array, 0, count);
count = 0;
}
public static void EnsureCapacity<TValue>(ref TValue[] array, int count, int capacity, int capacityIncrement = 10)
{
if (capacity == 0)
return;
if (array == null)
{
array = new TValue[Math.Max(capacity, capacityIncrement)];
return;
}
var currentCapacity = array.Length - count;
if (currentCapacity >= capacity)
return;
DuplicateWithCapacity(ref array, count, capacity, capacityIncrement);
}
public static void DuplicateWithCapacity<TValue>(ref TValue[] array, int count, int capacity, int capacityIncrement = 10)
{
if (array == null)
{
array = new TValue[Math.Max(capacity, capacityIncrement)];
return;
}
var newSize = count + Math.Max(capacity, capacityIncrement);
var newArray = new TValue[newSize];
Array.Copy(array, newArray, count);
array = newArray;
}
public static bool Contains<TValue>(TValue[] array, TValue value)
{
if (array == null)
return false;
var comparer = EqualityComparer<TValue>.Default;
for (var i = 0; i < array.Length; ++i)
if (comparer.Equals(array[i], value))
return true;
return false;
}
public static bool ContainsReference<TValue>(this TValue[] array, TValue value)
where TValue : class
{
if (array == null)
return false;
return ContainsReference(array, array.Length, value);
}
public static bool ContainsReference<TFirst, TSecond>(this TFirst[] array, int count, TSecond value)
where TSecond : class
where TFirst : TSecond
{
return IndexOfReference(array, value, count) != -1;
}
public static bool ContainsReference<TFirst, TSecond>(this TFirst[] array, int startIndex, int count, TSecond value)
where TSecond : class
where TFirst : TSecond
{
return IndexOfReference(array, value, startIndex, count) != -1;
}
public static bool HaveDuplicateReferences<TFirst>(this TFirst[] first, int index, int count)
{
for (var i = 0; i < count; ++i)
{
var element = first[i];
for (var n = i + 1; n < count - i; ++n)
{
if (ReferenceEquals(element, first[n]))
return true;
}
}
return false;
}
public static bool HaveEqualElements<TValue>(TValue[] first, TValue[] second, int count = int.MaxValue)
{
if (first == null || second == null)
return second == first;
var lengthFirst = Math.Min(count, first.Length);
var lengthSecond = Math.Min(count, second.Length);
if (lengthFirst != lengthSecond)
return false;
var comparer = EqualityComparer<TValue>.Default;
for (var i = 0; i < lengthFirst; ++i)
if (!comparer.Equals(first[i], second[i]))
return false;
return true;
}
////REVIEW: remove this to get rid of default equality comparer?
public static int IndexOf<TValue>(TValue[] array, TValue value, int startIndex = 0, int count = -1)
{
if (array == null)
return -1;
if (count < 0)
count = array.Length - startIndex;
var comparer = EqualityComparer<TValue>.Default;
for (var i = startIndex; i < startIndex + count; ++i)
if (comparer.Equals(array[i], value))
return i;
return -1;
}
public static int IndexOf<TValue>(this TValue[] array, Predicate<TValue> predicate)
{
if (array == null)
return -1;
var length = array.Length;
for (var i = 0; i < length; ++i)
if (predicate(array[i]))
return i;
return -1;
}
public static int IndexOf<TValue>(this TValue[] array, Predicate<TValue> predicate, int startIndex = 0, int count = -1)
{
if (array == null)
return -1;
var end = startIndex + (count < 0 ? array.Length - startIndex : count);
for (var i = startIndex; i < end; ++i)
{
if (predicate(array[i]))
return i;
}
return -1;
}
public static int IndexOfReference<TFirst, TSecond>(this TFirst[] array, TSecond value, int count = -1)
where TSecond : class
where TFirst : TSecond
{
return IndexOfReference(array, value, 0, count);
}
public static int IndexOfReference<TFirst, TSecond>(this TFirst[] array, TSecond value, int startIndex, int count)
where TSecond : class
where TFirst : TSecond
{
if (array == null)
return -1;
if (count < 0)
count = array.Length - startIndex;
for (var i = startIndex; i < startIndex + count; ++i)
if (ReferenceEquals(array[i], value))
return i;
return -1;
}
public static int IndexOfValue<TValue>(this TValue[] array, TValue value, int startIndex = 0, int count = -1)
where TValue : struct, IEquatable<TValue>
{
if (array == null)
return -1;
if (count < 0)
count = array.Length - startIndex;
for (var i = startIndex; i < startIndex + count; ++i)
if (value.Equals(array[i]))
return i;
return -1;
}
public static unsafe void Resize<TValue>(ref NativeArray<TValue> array, int newSize, Allocator allocator)
where TValue : struct
{
var oldSize = array.Length;
if (oldSize == newSize)
return;
if (newSize == 0)
{
if (array.IsCreated)
array.Dispose();
array = new NativeArray<TValue>();
return;
}
var newArray = new NativeArray<TValue>(newSize, allocator);
if (oldSize != 0)
{
// Copy contents from old array.
UnsafeUtility.MemCpy(newArray.GetUnsafePtr(), array.GetUnsafeReadOnlyPtr(),
UnsafeUtility.SizeOf<TValue>() * (newSize < oldSize ? newSize : oldSize));
array.Dispose();
}
array = newArray;
}
public static int Append<TValue>(ref TValue[] array, TValue value)
{
if (array == null)
{
array = new TValue[1];
array[0] = value;
return 0;
}
var length = array.Length;
Array.Resize(ref array, length + 1);
array[length] = value;
return length;
}
public static int Append<TValue>(ref TValue[] array, IEnumerable<TValue> values)
{
if (array == null)
{
array = values.ToArray();
return 0;
}
var oldLength = array.Length;
var valueCount = values.Count();
Array.Resize(ref array, oldLength + valueCount);
var index = oldLength;
foreach (var value in values)
array[index++] = value;
return oldLength;
}
// Append to an array that is considered immutable. This allows using 'values' as is
// if 'array' is null.
// Returns the index of the first newly added element in the resulting array.
public static int AppendToImmutable<TValue>(ref TValue[] array, TValue[] values)
{
if (array == null)
{
array = values;
return 0;
}
if (values != null && values.Length > 0)
{
var oldCount = array.Length;
var valueCount = values.Length;
Array.Resize(ref array, oldCount + valueCount);
Array.Copy(values, 0, array, oldCount, valueCount);
return oldCount;
}
return array.Length;
}
public static int AppendWithCapacity<TValue>(ref TValue[] array, ref int count, TValue value, int capacityIncrement = 10)
{
if (array == null)
{
array = new TValue[capacityIncrement];
array[0] = value;
++count;
return 0;
}
var capacity = array.Length;
if (capacity == count)
{
capacity += capacityIncrement;
Array.Resize(ref array, capacity);
}
var index = count;
array[index] = value;
++count;
return index;
}
public static int AppendListWithCapacity<TValue, TValues>(ref TValue[] array, ref int length, TValues values, int capacityIncrement = 10)
where TValues : IReadOnlyList<TValue>
{
var numToAdd = values.Count;
if (array == null)
{
var size = Math.Max(numToAdd, capacityIncrement);
array = new TValue[size];
for (var i = 0; i < numToAdd; ++i)
array[i] = values[i];
length += numToAdd;
return 0;
}
var capacity = array.Length;
if (capacity < length + numToAdd)
{
capacity += Math.Max(length + numToAdd, capacityIncrement);
Array.Resize(ref array, capacity);
}
var index = length;
for (var i = 0; i < numToAdd; ++i)
array[index + i] = values[i];
length += numToAdd;
return index;
}
public static int AppendWithCapacity<TValue>(ref NativeArray<TValue> array, ref int count, TValue value,
int capacityIncrement = 10, Allocator allocator = Allocator.Persistent)
where TValue : struct
{
var capacity = array.Length;
if (capacity == count)
GrowBy(ref array, capacityIncrement > 1 ? capacityIncrement : 1, allocator);
var index = count;
array[index] = value;
++count;
return index;
}
public static void InsertAt<TValue>(ref TValue[] array, int index, TValue value)
{
if (array == null)
{
////REVIEW: allow growing array to specific size by inserting at arbitrary index?
if (index != 0)
throw new ArgumentOutOfRangeException(nameof(index));
array = new TValue[1];
array[0] = value;
return;
}
// Reallocate.
var oldLength = array.Length;
Array.Resize(ref array, oldLength + 1);
// Make room for element.
if (index != oldLength)
Array.Copy(array, index, array, index + 1, oldLength - index);
array[index] = value;
}
public static void InsertAtWithCapacity<TValue>(ref TValue[] array, ref int count, int index, TValue value, int capacityIncrement = 10)
{
EnsureCapacity(ref array, count, count + 1, capacityIncrement);
if (index != count)
Array.Copy(array, index, array, index + 1, count - index);
array[index] = value;
++count;
}
public static void PutAtIfNotSet<TValue>(ref TValue[] array, int index, Func<TValue> valueFn)
{
if (array.LengthSafe() < index + 1)
Array.Resize(ref array, index + 1);
if (EqualityComparer<TValue>.Default.Equals(array[index], default(TValue)))
array[index] = valueFn();
}
// Adds 'count' entries to the array. Returns first index of newly added entries.
public static int GrowBy<TValue>(ref TValue[] array, int count)
{
if (array == null)
{
array = new TValue[count];
return 0;
}
var oldLength = array.Length;
Array.Resize(ref array, oldLength + count);
return oldLength;
}
public static unsafe int GrowBy<TValue>(ref NativeArray<TValue> array, int count, Allocator allocator = Allocator.Persistent)
where TValue : struct
{
var length = array.Length;
if (length == 0)
{
array = new NativeArray<TValue>(count, allocator);
return 0;
}
var newArray = new NativeArray<TValue>(length + count, allocator);
// CopyFrom() expects length to match. Copy manually.
UnsafeUtility.MemCpy(newArray.GetUnsafePtr(), array.GetUnsafeReadOnlyPtr(), (long)length * UnsafeUtility.SizeOf<TValue>());
array.Dispose();
array = newArray;
return length;
}
public static int GrowWithCapacity<TValue>(ref TValue[] array, ref int count, int growBy, int capacityIncrement = 10)
{
var length = array != null ? array.Length : 0;
if (length < count + growBy)
{
if (capacityIncrement < growBy)
capacityIncrement = growBy;
GrowBy(ref array, capacityIncrement);
}
var offset = count;
count += growBy;
return offset;
}
public static int GrowWithCapacity<TValue>(ref NativeArray<TValue> array, ref int count, int growBy,
int capacityIncrement = 10, Allocator allocator = Allocator.Persistent)
where TValue : struct
{
var length = array.Length;
if (length < count + growBy)
{
if (capacityIncrement < growBy)
capacityIncrement = growBy;
GrowBy(ref array, capacityIncrement, allocator);
}
var offset = count;
count += growBy;
return offset;
}
public static TValue[] Join<TValue>(TValue value, params TValue[] values)
{
// Determine length.
var length = 0;
if (value != null)
++length;
if (values != null)
length += values.Length;
if (length == 0)
return null;
var array = new TValue[length];
// Populate.
var index = 0;
if (value != null)
array[index++] = value;
if (values != null)
Array.Copy(values, 0, array, index, values.Length);
return array;
}
public static TValue[] Merge<TValue>(TValue[] first, TValue[] second)
where TValue : IEquatable<TValue>
{
if (first == null)
return second;
if (second == null)
return first;
var merged = new List<TValue>();
merged.AddRange(first);
for (var i = 0; i < second.Length; ++i)
{
var secondValue = second[i];
if (!merged.Exists(x => x.Equals(secondValue)))
{
merged.Add(secondValue);
}
}
return merged.ToArray();
}
public static TValue[] Merge<TValue>(TValue[] first, TValue[] second, IEqualityComparer<TValue> comparer)
{
if (first == null)
return second;
if (second == null)
return null;
var merged = new List<TValue>();
merged.AddRange(first);
for (var i = 0; i < second.Length; ++i)
{
var secondValue = second[i];
if (!merged.Exists(x => comparer.Equals(secondValue)))
{
merged.Add(secondValue);
}
}
return merged.ToArray();
}
public static void EraseAt<TValue>(ref TValue[] array, int index)
{
Debug.Assert(array != null);
Debug.Assert(index >= 0 && index < array.Length);
var length = array.Length;
if (index == 0 && length == 1)
{
array = null;
return;
}
if (index < length - 1)
Array.Copy(array, index + 1, array, index, length - index - 1);
Array.Resize(ref array, length - 1);
}
public static void EraseAtWithCapacity<TValue>(this TValue[] array, ref int count, int index)
{
Debug.Assert(array != null);
Debug.Assert(count <= array.Length);
Debug.Assert(index >= 0 && index < count);
// If we're erasing from the beginning or somewhere in the middle, move
// the array contents down from after the index.
if (index < count - 1)
{
Array.Copy(array, index + 1, array, index, count - index - 1);
}
array[count - 1] = default; // Tail has been moved down by one.
--count;
}
public static unsafe void EraseAtWithCapacity<TValue>(NativeArray<TValue> array, ref int count, int index)
where TValue : struct
{
Debug.Assert(array.IsCreated);
Debug.Assert(count <= array.Length);
Debug.Assert(index >= 0 && index < count);
// If we're erasing from the beginning or somewhere in the middle, move
// the array contents down from after the index.
if (index < count - 1)
{
var elementSize = UnsafeUtility.SizeOf<TValue>();
var arrayPtr = (byte*)array.GetUnsafePtr();
UnsafeUtility.MemCpy(arrayPtr + elementSize * index, arrayPtr + elementSize * (index + 1),
(count - index - 1) * elementSize);
}
--count;
}
public static bool Erase<TValue>(ref TValue[] array, TValue value)
{
var index = IndexOf(array, value);
if (index != -1)
{
EraseAt(ref array, index);
return true;
}
return false;
}
/// <summary>
/// Erase an element from the array by moving the tail element into its place.
/// </summary>
/// <param name="array">Array to modify. May be not <c>null</c>.</param>
/// <param name="count">Current number of elements inside of array. May be less than <c>array.Length</c>.</param>
/// <param name="index">Index of element to remove. Tail element will get moved into its place.</param>
/// <typeparam name="TValue"></typeparam>
/// <remarks>
/// This method does not re-allocate the array. Instead <paramref name="count"/> is used
/// to keep track of how many elements there actually are in the array.
/// </remarks>
public static void EraseAtByMovingTail<TValue>(TValue[] array, ref int count, int index)
{
Debug.Assert(array != null);
Debug.Assert(index >= 0 && index < array.Length);
Debug.Assert(count >= 0 && count <= array.Length);
Debug.Assert(index < count);
// Move tail, if necessary.
if (index != count - 1)
array[index] = array[count - 1];
// Destroy current tail.
if (count >= 1)
array[count - 1] = default;
--count;
}
public static TValue[] Copy<TValue>(TValue[] array)
{
if (array == null)
return null;
var length = array.Length;
var result = new TValue[length];
Array.Copy(array, result, length);
return result;
}
public static TValue[] Clone<TValue>(TValue[] array)
where TValue : ICloneable
{
if (array == null)
return null;
var count = array.Length;
var result = new TValue[count];
for (var i = 0; i < count; ++i)
result[i] = (TValue)array[i].Clone();
return result;
}
public static TNew[] Select<TOld, TNew>(TOld[] array, Func<TOld, TNew> converter)
{
if (array == null)
return null;
var length = array.Length;
var result = new TNew[length];
for (var i = 0; i < length; ++i)
result[i] = converter(array[i]);
return result;
}
private static void Swap<TValue>(ref TValue first, ref TValue second)
{
var temp = first;
first = second;
second = temp;
}
/// <summary>
/// Move a slice in the array to a different place without allocating a temporary array.
/// </summary>
/// <param name="array"></param>
/// <param name="sourceIndex"></param>
/// <param name="destinationIndex"></param>
/// <param name="count"></param>
/// <typeparam name="TValue"></typeparam>
/// <remarks>
/// The slice is moved by repeatedly swapping slices until all the slices are where they
/// are supposed to go. This is not super efficient but avoids having to allocate a temporary
/// array on the heap.
/// </remarks>
public static void MoveSlice<TValue>(TValue[] array, int sourceIndex, int destinationIndex, int count)
{
if (count <= 0 || sourceIndex == destinationIndex)
return;
// Determine the number of elements in the window.
int elementCount;
if (destinationIndex > sourceIndex)
elementCount = destinationIndex + count - sourceIndex;
else
elementCount = sourceIndex + count - destinationIndex;
// If the source and target slice are right next to each other, just go
// and swap out the elements in both slices.
if (elementCount == count * 2)
{
for (var i = 0; i < count; ++i)
Swap(ref array[sourceIndex + i], ref array[destinationIndex + i]);
}
else
{
// There's elements in-between the two slices.
//
// The easiest way to picture this operation is as a rotation of the elements within
// the window given by sourceIndex, destination, and count. Within that window, we are
// simply treating it as a wrap-around buffer and then sliding the elements clockwise
// or counter-clockwise (depending on whether we move up or down, respectively) through
// the window.
//
// Unfortunately, we can't just memcopy the slices within that window as we have to
// have a temporary copy in place in order to preserve element values. So instead, we
// go and swap elements one by one, something that doesn't require anything other than
// a single value temporary copy.
// Determine the number of swaps we need to achieve the desired order. Swaps
// operate in pairs so it's one less than the number of elements in the range.
var swapCount = elementCount - 1;
// We simply take sourceIndex as fixed and do all swaps from there until all
// the elements in the window are in the right order. Each swap will put one
// element in its final place.
var dst = destinationIndex;
for (var i = 0; i < swapCount; ++i)
{
// Swap source into its destination place. This puts the current sourceIndex
// element in its final place.
Swap(ref array[dst], ref array[sourceIndex]);
// Find out where the element that we now swapped into sourceIndex should
// actually go.
if (destinationIndex > sourceIndex)
{
// Rotating clockwise.
dst -= count;
if (dst < sourceIndex)
dst = destinationIndex + count - Math.Abs(sourceIndex - dst); // Wrap around.
}
else
{
// Rotating counter-clockwise.
dst += count;
if (dst >= sourceIndex + count)
dst = destinationIndex + (dst - (sourceIndex + count)); // Wrap around.
}
}
}
}
public static void EraseSliceWithCapacity<TValue>(ref TValue[] array, ref int length, int index, int count)
{
// Move elements down.
if (count < length)
Array.Copy(array, index + count, array, index, length - index - count);
// Erase now vacant slots.
for (var i = 0; i < count; ++i)
array[length - i - 1] = default;
length -= count;
}
public static void SwapElements<TValue>(this TValue[] array, int index1, int index2)
{
MemoryHelpers.Swap(ref array[index1], ref array[index2]);
}
public static void SwapElements<TValue>(this NativeArray<TValue> array, int index1, int index2)
where TValue : struct
{
var temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
}
}
|