1// Copyright 2016 - 2018 Ulrik Sverdrup "bluss"
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
89use core::cmp::min;
1011#[derive(Copy, Clone)]
12pub struct RangeChunk { i: usize, n: usize, chunk: usize }
1314/// Create an iterator that splits `n` in chunks of size `chunk`;
15/// the last item can be an uneven chunk.
16pub fn range_chunk(n: usize, chunk: usize) -> RangeChunk {
17 RangeChunk {
18 i: 0,
19 n: n,
20 chunk: chunk,
21 }
22}
2324impl Iterator for RangeChunk {
25type Item = (usize, usize);
2627#[inline]
28fn next(&mut self) -> Option<Self::Item> {
29if self.n == 0 {
30None
31} else {
32let i = self.i;
33let rem = min(self.n, self.chunk);
34self.i += 1;
35self.n -= rem;
36Some((i, rem))
37 }
38 }
39}
4041#[inline]
42pub fn round_up_to(x: usize, multiple_of: usize) -> usize {
43let (mut d, r) = (x / multiple_of, x % multiple_of);
44if r > 0 { d += 1; }
45 d * multiple_of
46}
4748impl RangeChunk {
49#[cfg(feature="threading")]
50/// Split the iterator in `total` parts and only iterate the `index`th part of it.
51 /// The iterator must not have started when this is called.
52pub(crate) fn part(self, index: usize, total: usize) -> Self {
53debug_assert_eq!(self.i, 0, "range must be uniterated");
54debug_assert_ne!(total, 0);
55let (n, chunk) = (self.n, self.chunk);
5657// round up
58let mut nchunks = n / chunk;
59 nchunks += (n % chunk != 0) as usize;
6061// chunks per thread
62 // round up
63let mut chunks_per = nchunks / total;
64 chunks_per += (nchunks % total != 0) as usize;
6566let i = chunks_per * index;
67let nn = min(n, (i + chunks_per) * chunk).saturating_sub(i * chunk);
6869 RangeChunk { i, n: nn, chunk }
70 }
71}