1extern crate lazy_static;
2extern crate num_cpus;
3use super::bithacks::round_up_to_power2;
4
5const DEFAULT_CPUS: u32 = 4;
6
7pub struct CpuShard(u32, u32);
25
26impl CpuShard {
27 #[inline]
29 pub fn new(max_shard_limit: Option<u32>) -> Self {
30 let mut cpus = num_cpus::get() as u32;
31 if cpus < DEFAULT_CPUS {
32 cpus = DEFAULT_CPUS;
33 }
34 if let Some(limit) = max_shard_limit {
35 if cpus > limit {
36 cpus = limit;
37 }
38 }
39 let (shard, shift) = round_up_to_power2(cpus);
40 Self(shard, shift)
41 }
42
43 #[inline]
45 pub fn shards(&self) -> u32 {
46 self.0
47 }
48
49 #[inline]
51 pub fn shift(&self) -> u32 {
52 self.1
53 }
54}
55
56#[cfg(test)]
57mod tests {
58 use super::*;
59
60 #[test]
61 fn test_static_shards() {
62 let cpu_shard = CpuShard::new(None);
63 let cpus = num_cpus::get();
64 println!("cpus={}", cpus);
65 if cpus <= 4 {
66 assert_eq!(cpu_shard.shards(), 4);
67 assert_eq!(cpu_shard.shift(), 2);
68 } else if cpus <= 8 {
69 assert_eq!(cpu_shard.shards(), 8);
70 assert_eq!(cpu_shard.shift(), 3);
71 }
72 }
73
74 #[test]
75 fn test_shards_limit() {
76 let cpu_shard = CpuShard::new(Some(2));
77 assert_eq!(cpu_shard.shards(), 2);
78 assert_eq!(cpu_shard.shift(), 1);
79 }
80}