Skip to content

Commit

Permalink
fixed bool[].ToFixedArray()
Browse files Browse the repository at this point in the history
  • Loading branch information
lostmsu committed Sep 9, 2021
1 parent 876219b commit f28befa
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/FixedArray.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,20 @@ public static unsafe IList<T> ToFixedArray<T>(this ICollection<T> collection) wh

int len = collection.Count;
var type = FixedArray<T>.GetType(len);
object result = Activator.CreateInstance(type);
var box = GCHandle.Alloc(result, GCHandleType.Pinned);
var result = (IList<T>)Activator.CreateInstance(type);

GCHandle box;
try {
box = GCHandle.Alloc(result, GCHandleType.Pinned);
} catch (ArgumentException) {
// workaround for bool and char not being pinnable
using IEnumerator<T> enumerator = collection.GetEnumerator();
for (int i = 0; i < len; i++) {
if (!enumerator.MoveNext()) throw new ArgumentException("Bad collection enumerator");
result[i] = enumerator.Current;
}
return result;
}
var data = (T*)box.AddrOfPinnedObject();

try {
Expand Down
7 changes: 7 additions & 0 deletions tests/FixedArrayTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ public void ToFixedArray() {
Assert.Equal(netArray, array);
}

[Fact]
public void ToFixedBoolArray() {
bool[] netArrray = new[] { false, true, true };
var array = netArrray.ToFixedArray();
Assert.Equal(netArrray, array);
}

[Fact]
public void ToFixedArray_TooLarge() {
int[] netArray = new int[PowersOfTwo.Max + 1];
Expand Down

0 comments on commit f28befa

Please sign in to comment.