1+ #if NET461_OR_GREATER || NETSTANDARD2_0
2+ //https://github.com/Grax32/ArrayExtensions/blob/master/docs/index.md
3+
4+ using System ;
5+ namespace Grax32 . Extensions
6+ {
7+ public static class ArrayExtensions
8+ {
9+ public static void Fill < T > ( this T [ ] destinationArray , T value )
10+ {
11+ if ( destinationArray == null )
12+ {
13+ throw new ArgumentNullException ( nameof ( destinationArray ) ) ;
14+ }
15+
16+ destinationArray [ 0 ] = value ;
17+ FillInternal ( destinationArray , 1 ) ;
18+ }
19+
20+ public static void Fill < T > ( this T [ ] destinationArray , T [ ] values )
21+ {
22+ if ( destinationArray == null )
23+ {
24+ throw new ArgumentNullException ( nameof ( destinationArray ) ) ;
25+ }
26+
27+ var copyLength = values . Length ;
28+ var destinationArrayLength = destinationArray . Length ;
29+
30+ if ( copyLength == 0 )
31+ {
32+ throw new ArgumentException ( "Parameter must contain at least one value." , nameof ( values ) ) ;
33+ }
34+
35+ if ( copyLength > destinationArrayLength )
36+ {
37+ // value to copy is longer than destination,
38+ // so fill destination with first part of value
39+ Array . Copy ( values , destinationArray , destinationArrayLength ) ;
40+ return ;
41+ }
42+
43+ Array . Copy ( values , destinationArray , copyLength ) ;
44+
45+ FillInternal ( destinationArray , copyLength ) ;
46+ }
47+
48+ private static void FillInternal < T > ( this T [ ] destinationArray , int copyLength )
49+ {
50+ var destinationArrayLength = destinationArray . Length ;
51+ var destinationArrayHalfLength = destinationArrayLength / 2 ;
52+
53+ // looping copy from beginning of array to current position
54+ // doubling copy length with each pass
55+ for ( ; copyLength < destinationArrayHalfLength ; copyLength *= 2 )
56+ {
57+ Array . Copy (
58+ sourceArray : destinationArray ,
59+ sourceIndex : 0 ,
60+ destinationArray : destinationArray ,
61+ destinationIndex : copyLength ,
62+ length : copyLength ) ;
63+ }
64+
65+ // we're past halfway, meaning only a single copy remains
66+ // exactly fill remainder of array
67+ Array . Copy (
68+ sourceArray : destinationArray ,
69+ sourceIndex : 0 ,
70+ destinationArray : destinationArray ,
71+ destinationIndex : copyLength ,
72+ length : destinationArrayLength - copyLength ) ;
73+ }
74+ }
75+ }
76+ #endif
0 commit comments