From f28befa00b82d2d154cc947b529520f77db2c5a6 Mon Sep 17 00:00:00 2001 From: Victor Nova Date: Wed, 8 Sep 2021 23:46:55 -0700 Subject: [PATCH] fixed bool[].ToFixedArray() --- src/FixedArray.cs | 16 ++++++++++++++-- tests/FixedArrayTests.cs | 7 +++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/FixedArray.cs b/src/FixedArray.cs index bfc949b..c4669dd 100644 --- a/src/FixedArray.cs +++ b/src/FixedArray.cs @@ -128,8 +128,20 @@ public static unsafe IList ToFixedArray(this ICollection collection) wh int len = collection.Count; var type = FixedArray.GetType(len); - object result = Activator.CreateInstance(type); - var box = GCHandle.Alloc(result, GCHandleType.Pinned); + var result = (IList)Activator.CreateInstance(type); + + GCHandle box; + try { + box = GCHandle.Alloc(result, GCHandleType.Pinned); + } catch (ArgumentException) { + // workaround for bool and char not being pinnable + using IEnumerator 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 { diff --git a/tests/FixedArrayTests.cs b/tests/FixedArrayTests.cs index afb0949..2cf4032 100644 --- a/tests/FixedArrayTests.cs +++ b/tests/FixedArrayTests.cs @@ -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];