Tanoda
ReadonlySlice.cs
Go to the documentation of this file.
1/******************************************************************************
2 * Copyright (C) Ultraleap, Inc. 2011-2020. *
3 * *
4 * Use subject to the terms of the Apache License 2.0 available at *
5 * http://www.apache.org/licenses/LICENSE-2.0, or another agreement *
6 * between Ultraleap and you, your company or other organization. *
7 ******************************************************************************/
8
9using Leap.Unity.Query;
10using System;
11using System.Collections;
12using System.Collections.Generic;
13using UnityEngine;
14
15namespace Leap.Unity {
16
17 public static class ReadonlySliceExtensions {
18
32 public static ReadonlySlice<T> ReadonlySlice<T>(this ReadonlyList<T> list, int beginIdx = -1, int endIdx = -1) {
33 if (beginIdx == -1 && endIdx == -1) {
34 return new ReadonlySlice<T>(list, 0, list.Count);
35 }
36 else if (beginIdx == -1 && endIdx != -1) {
37 return new ReadonlySlice<T>(list, 0, endIdx);
38 }
39 else if (endIdx == -1 && beginIdx != -1) {
40 return new ReadonlySlice<T>(list, beginIdx, list.Count);
41 }
42 else {
43 return new ReadonlySlice<T>(list, beginIdx, endIdx);
44 }
45 }
46
47 public static ReadonlySlice<T> FromIndex<T>(this ReadonlyList<T> list, int fromIdx) {
48 return ReadonlySlice(list, fromIdx);
49 }
50
51 }
52
53 public struct ReadonlySlice<T> : IIndexableStruct<T, ReadonlySlice<T>> {
54
55 private ReadonlyList<T> _list;
56
57 private int _beginIdx;
58 private int _endIdx;
59
60 private int _direction;
61
69 public ReadonlySlice(ReadonlyList<T> list, int beginIdx, int endIdx) {
70 _list = list;
71 _beginIdx = beginIdx;
72 _endIdx = endIdx;
73 _direction = beginIdx <= endIdx ? 1 : -1;
74 }
75
76 public T this[int index] {
77 get {
78 if (index < 0 || index > Count - 1) { throw new IndexOutOfRangeException(); }
79 return _list[_beginIdx + index * _direction];
80 }
81 }
82
83 public int Count {
84 get {
85 return (_endIdx - _beginIdx) * _direction;
86 }
87 }
88
89 #region foreach and Query()
90
93 }
94
95 public Query<T> Query() {
96 T[] array = ArrayPool<T>.Spawn(Count);
97 for (int i = 0; i < Count; i++) {
98 array[i] = this[i];
99 }
100 return new Query<T>(array, Count);
101 }
102
103 #endregion
104
105 }
106
107}
This is a definition-friendly interface that new "indexable" struct definitions can implement to make...
A two-generic-argument variant of an enumerator that allows an IIndexableStruct to quickly define an ...
A Query object is a type of immutable ordered collection of elements that can be used to perform usef...
Definition: Query.cs:90
A simple wrapper around List to provide readonly access. Useful when you want to return a list to som...
Definition: ReadonlyList.cs:20
ReadonlySlice(ReadonlyList< T > list, int beginIdx, int endIdx)
Creates a readonlySlice into the ReadonlyList with an inclusive beginIdx and an exclusive endIdx....
IndexableStructEnumerator< T, ReadonlySlice< T > > GetEnumerator()