SparseArrays.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. namespace SharpGLTF.Memory
  7. {
  8. /// <summary>
  9. /// Special accessor to wrap over a base accessor and a sparse accessor
  10. /// </summary>
  11. /// <typeparam name="T"></typeparam>
  12. [System.Diagnostics.DebuggerDisplay("Sparse {typeof(T).Name} Accessor {Count}")]
  13. public struct SparseArray<T> : IEncodedArray<T>
  14. where T : unmanaged
  15. {
  16. #region lifecycle
  17. public SparseArray(IEncodedArray<T> bottom, IEncodedArray<T> top, IntegerArray topMapping)
  18. {
  19. _BottomItems = bottom;
  20. _TopItems = top;
  21. _Mapping = new Dictionary<int, int>();
  22. for (int val = 0; val < topMapping.Count; ++val)
  23. {
  24. var key = (int)topMapping[val];
  25. _Mapping[key] = val;
  26. }
  27. }
  28. #endregion
  29. #region data
  30. [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
  31. private readonly IEncodedArray<T> _BottomItems;
  32. [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
  33. private readonly IEncodedArray<T> _TopItems;
  34. [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
  35. private readonly Dictionary<int, int> _Mapping;
  36. [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.RootHidden)]
  37. private T[] _DebugItems => this.ToArray();
  38. #endregion
  39. #region API
  40. [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
  41. public int Count => _BottomItems.Count;
  42. public T this[int index]
  43. {
  44. get => _Mapping.TryGetValue(index, out int topIndex) ? _TopItems[topIndex] : _BottomItems[index];
  45. set
  46. {
  47. if (_Mapping.TryGetValue(index, out int topIndex)) _TopItems[topIndex] = value;
  48. }
  49. }
  50. public void CopyTo(ArraySegment<T> dst) { EncodedArrayUtils.Copy(this, dst); }
  51. public (T, T) GetBounds()
  52. {
  53. throw new NotImplementedException();
  54. }
  55. public IEnumerator<T> GetEnumerator() { return new EncodedArrayEnumerator<T>(this); }
  56. IEnumerator IEnumerable.GetEnumerator() { return new EncodedArrayEnumerator<T>(this); }
  57. #endregion
  58. }
  59. }