Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Output NonZeroUsize instead of usize #107

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 10 additions & 8 deletions src/lib.rs
Expand Up @@ -31,6 +31,8 @@
#![doc(html_root_url = "https://docs.rs/num_cpus/1.13.0")]
#![allow(non_snake_case)]

use std::num::NonZeroUsize;

#[cfg(not(windows))]
extern crate libc;

Expand All @@ -50,7 +52,7 @@ use linux::{get_num_cpus, get_num_physical_cpus};
/// # Examples
///
/// ```
/// let cpus = num_cpus::get();
/// let cpus: usize = num_cpus::get().into();
/// if cpus > 1 {
/// println!("We are on a multicore system with {} CPUs", cpus);
/// } else {
Expand All @@ -69,8 +71,8 @@ use linux::{get_num_cpus, get_num_physical_cpus};
/// [sched affinity]: http://www.gnu.org/software/libc/manual/html_node/CPU-Affinity.html
/// [cgroups]: https://www.kernel.org/doc/Documentation/cgroup-v1/cgroups.txt
#[inline]
pub fn get() -> usize {
get_num_cpus()
pub fn get() -> NonZeroUsize {
NonZeroUsize::new(get_num_cpus()).unwrap_or_else(|| NonZeroUsize::new(1).unwrap())
}

/// Returns the number of physical cores of the current system.
Expand All @@ -90,7 +92,7 @@ pub fn get() -> usize {
/// if logical_cpus > physical_cpus {
/// println!("We have simultaneous multithreading with about {:.2} \
/// logical cores to 1 physical core.",
/// (logical_cpus as f64) / (physical_cpus as f64));
/// usize::from(logical_cpus) as f64 / usize::from(physical_cpus) as f64);
/// } else if logical_cpus == physical_cpus {
/// println!("Either we don't have simultaneous multithreading, or our \
/// system doesn't support getting the number of physical CPUs.");
Expand All @@ -102,8 +104,8 @@ pub fn get() -> usize {
///
/// [`get()`]: fn.get.html
#[inline]
pub fn get_physical() -> usize {
get_num_physical_cpus()
pub fn get_physical() -> NonZeroUsize {
NonZeroUsize::new(get_num_physical_cpus()).unwrap_or_else(|| NonZeroUsize::new(1).unwrap())
}


Expand Down Expand Up @@ -434,7 +436,7 @@ mod tests {

#[test]
fn test_get() {
let num = super::get();
let num: usize = super::get().into();
if let Some(n) = env_var("NUM_CPUS_TEST_GET") {
assert_eq!(num, n);
} else {
Expand All @@ -445,7 +447,7 @@ mod tests {

#[test]
fn test_get_physical() {
let num = super::get_physical();
let num: usize = super::get_physical().into();
if let Some(n) = env_var("NUM_CPUS_TEST_GET_PHYSICAL") {
assert_eq!(num, n);
} else {
Expand Down