Update: A reader ( Michael Hsu ) posted a faster improved version at https://github.com/mykohsu/Extensions/blob/master/ArrayExtensions.cs and I blogged about it.
Looking back at my first blog post, I decided to revisit it.
The function is succinct, blazingly fast, and I am quite proud of it.
Here's what it does. Given an array of any type (byte, int, string), fill the array with a single value or a repeating pattern of values.
Usage is very simple.
Define an array, for example:
byte[] myByteArray = new byte[12345];
Call ArrayFill with the array variable and a value to fill the array with.
ArrayFill(myByteArray, (byte)3);
At this point the array is completely filled with a byte of 3.
Call it with a second array to fill your array with a repeating pattern.
ArrayFill(myByteArray, new byte[] { 3, 4, 1, 9 });
At this point the array is filled with a repeating pattern of bytes. 3,4,1,9,3,4,1,9,3,4,1,9, etc
Code Snippet
- public static void ArrayFill<T>(T[] arrayToFill, T fillValue)
- {
- // if called with a single value, wrap the value in an array and call the main function
- ArrayFill(arrayToFill, new T[] { fillValue });
- }
- public static void ArrayFill<T>(T[] arrayToFill, T[] fillValue)
- {
- if (fillValue.Length >= arrayToFill.Length)
- {
- throw new ArgumentException("fillValue array length must be smaller than length of arrayToFill");
- }
- // set the initial array value
- Array.Copy(fillValue, arrayToFill, fillValue.Length);
- int arrayToFillHalfLength = arrayToFill.Length / 2;
- for (int i = fillValue.Length; i < arrayToFill.Length; i *= 2)
- {
- int copyLength = i;
- if (i > arrayToFillHalfLength)
- {
- copyLength = arrayToFill.Length - i;
- }
- Array.Copy(arrayToFill, 0, arrayToFill, i, copyLength);
- }
- }