MappedSlice.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // RichTextKit
  2. // Copyright © 2019-2020 Topten Software. All Rights Reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. // not use this product except in compliance with the License. You may obtain
  6. // a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. // License for the specific language governing permissions and limitations
  14. // under the License.
  15. using System.Runtime.CompilerServices;
  16. namespace Topten.RichTextKit.Utils
  17. {
  18. /// <summary>
  19. /// Provides a mapped view of an underlying slice array, selecting arbitrary indicies
  20. /// from the source array
  21. /// </summary>
  22. /// <typeparam name="T">The element type of the underlying array</typeparam>
  23. public struct MappedSlice<T>
  24. {
  25. /// <summary>
  26. /// Constructs a new mapped array
  27. /// </summary>
  28. /// <param name="data">The data to be mapped</param>
  29. /// <param name="mapping">The index map</param>
  30. public MappedSlice(Slice<T> data, Slice<int> mapping)
  31. {
  32. _data = data;
  33. _mapping = mapping;
  34. }
  35. Slice<T> _data;
  36. Slice<int> _mapping;
  37. /// <summary>
  38. /// Get the underlying slice for this mapped array
  39. /// </summary>
  40. public Slice<T> Underlying => _data;
  41. /// <summary>
  42. /// Get the index mapping for this mapped array
  43. /// </summary>
  44. public Slice<int> Mapping => _mapping;
  45. /// <summary>
  46. /// Gets the number of elements in this mapping
  47. /// </summary>
  48. public int Length => _mapping.Length;
  49. /// <summary>
  50. /// Gets a reference to a mapped element
  51. /// </summary>
  52. /// <param name="index">The mapped index to be retrieved</param>
  53. /// <returns>A reference to the element</returns>
  54. public ref T this[int index]
  55. {
  56. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  57. get
  58. {
  59. return ref _data[_mapping[index]];
  60. }
  61. }
  62. /// <summary>
  63. /// Get the content of this mapped slice as an array
  64. /// </summary>
  65. /// <returns>The content as an array</returns>
  66. public T[] ToArray()
  67. {
  68. var arr = new T[Length];
  69. for (int i = 0; i < Length; i++)
  70. {
  71. arr[i] = this[i];
  72. }
  73. return arr;
  74. }
  75. }
  76. }