5 // Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
7 // Copyright (c) 2009 Jérémie "Garuma" Laval
9 // Permission is hereby granted, free of charge, to any person obtaining a copy
10 // of this software and associated documentation files (the "Software"), to deal
11 // in the Software without restriction, including without limitation the rights
12 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 // copies of the Software, and to permit persons to whom the Software is
14 // furnished to do so, subject to the following conditions:
16 // The above copyright notice and this permission notice shall be included in
17 // all copies or substantial portions of the Software.
19 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
30 using System.Threading;
31 using System.Collections.Generic;
32 using System.Runtime.InteropServices;
34 namespace System.Collections.Concurrent.Partitioners
36 // Represent a Range partitioner
37 internal class ListPartitioner<T> : OrderablePartitioner<T>
41 public ListPartitioner (IList<T> source) : base (true, true, true)
46 public override IList<IEnumerator<KeyValuePair<long, T>>> GetOrderablePartitions (int partitionCount)
48 if (partitionCount <= 0)
49 throw new ArgumentOutOfRangeException ("partitionCount");
51 IEnumerator<KeyValuePair<long, T>>[] enumerators
52 = new IEnumerator<KeyValuePair<long, T>>[partitionCount];
54 int count = source.Count / partitionCount;
57 if (source.Count < partitionCount) {
60 extra = source.Count % partitionCount;
67 Range[] ranges = new Range[enumerators.Length];
68 for (int i = 0; i < ranges.Length; i++) {
69 ranges[i] = new Range (currentIndex,
70 currentIndex + count);
71 currentIndex += count;
76 for (int i = 0; i < enumerators.Length; i++) {
77 enumerators[i] = GetEnumeratorForRange (ranges, i);
86 public readonly int LastIndex;
88 public Range (int frm, int lastIndex)
91 LastIndex = lastIndex;
95 IEnumerator<KeyValuePair<long, T>> GetEnumeratorForRange (Range[] ranges, int workerIndex)
97 if (ranges[workerIndex].Actual >= source.Count)
100 return GetEnumeratorForRangeInternal (ranges, workerIndex);
103 IEnumerator<KeyValuePair<long, T>> GetEmpty ()
108 IEnumerator<KeyValuePair<long, T>> GetEnumeratorForRangeInternal (Range[] ranges, int workerIndex)
110 Range range = ranges[workerIndex];
111 int lastIndex = range.LastIndex;
112 int index = range.Actual;
114 for (int i = index; i < lastIndex; i = ++range.Actual) {
115 yield return new KeyValuePair<long, T> (i, source[i]);