Skip to content

Commit

Permalink
async-await rewrite of heim-cpu
Browse files Browse the repository at this point in the history
  • Loading branch information
svartalf committed Feb 15, 2020
1 parent ede7005 commit 607c461
Show file tree
Hide file tree
Showing 15 changed files with 66 additions and 97 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/tier1.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
- macOS-latest
- windows-latest
toolchain:
- 1.36.0 # MSRV
- 1.39.0 # MSRV
- stable
- nightly

Expand Down
19 changes: 2 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
[![Latest Version](https://docs.rs/heim/badge.svg)](https://docs.rs/heim)
[![dependency status](https://deps.rs/crate/heim/0.0.10/status.svg)](https://deps.rs/crate/heim/0.0.10)
[![Coverage Status](https://github.com/heim-rs/heim/workflows/Continuous%20integration/badge.svg)](https://github.com/heim-rs/heim/actions?workflow=Continuous+integration)
![Minimum rustc version](https://img.shields.io/badge/rustc-1.36+-green.svg)
![Minimum rustc version](https://img.shields.io/badge/rustc-1.39+-green.svg)
![Apache 2.0 OR MIT licensed](https://img.shields.io/badge/license-Apache2.0%2FMIT-blue.svg)
[![Gitter](https://badges.gitter.im/heim-rs/heim.svg)](https://gitter.im/heim-rs/heim)
![Platforms supported](https://img.shields.io/badge/platform-linux%20%7C%20macos%20%7C%20windows-brightgreen)
Expand Down Expand Up @@ -47,22 +47,7 @@ See the [comparison](https://github.com/heim-rs/heim/blob/master/COMPARISON.md)

## Technical notes

`heim` requires stable Rust 1.36+,
but examples, tests and benchmarks use the [`async_await`](https://github.com/rust-lang/rust/issues/50547)
feature and therefore require stable Rust 1.39+.\
Of course, you can use `heim` without the `async` keyword,
just be aware that it is used by the examples.

`heim` is using `std::future::Future` and it is expected that users understand
how futures work, how to use them, and what differences there are
between futures versions `0.1` and `0.3/std::future::Future`.\
It is not a project goal to provide any kind of information about how to
combine `heim` with `actix`, `hyper`, `tide`, or any other Rust crate.

At the moment, `heim` is async runtime agnostic, but in the future it may need to depend on runtime
specific features. Note that if this becomes the case, it is likely that the required runtime(s) will be
compatible with the [runtime](https://crates.io/crates/runtime) crate.
Users may want to consider this fact during development. See [#75](https://github.com/heim-rs/heim/issues/75) for more info.
Currently `master` branch is going under `async/await` rewrite, stay tuned.

## Platform support

Expand Down
10 changes: 5 additions & 5 deletions heim-cpu/src/count.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use heim_common::prelude::{Future, Result};
use heim_common::prelude::Result;

use crate::sys;

/// Returns future which will resolve into a amount of logical CPUs.
pub fn logical_count() -> impl Future<Output = Result<u64>> {
sys::logical_count()
pub async fn logical_count() -> Result<u64> {
sys::logical_count().await
}

/// Returns future which will resolve into a amount of physical CPUs.
///
/// Returned future might resolve into `Ok(None)` if the amount can't be determined.
pub fn physical_count() -> impl Future<Output = Result<Option<u64>>> {
sys::physical_count()
pub async fn physical_count() -> Result<Option<u64>> {
sys::physical_count().await
}
4 changes: 2 additions & 2 deletions heim-cpu/src/freq.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,6 @@ impl fmt::Debug for CpuFrequency {
///
/// [CpuFrequency]: ./struct.CpuFrequency.html
/// [frequencies]: ./os/linux/fn.frequencies.html
pub fn frequency() -> impl Future<Output = Result<CpuFrequency>> {
sys::frequency().map_ok(Into::into)
pub async fn frequency() -> Result<CpuFrequency> {
sys::frequency().await.map(Into::into)
}
1 change: 1 addition & 0 deletions heim-cpu/src/os/linux/times.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ pub trait CpuTimeExt {
fn guest_nice(&self) -> Option<Time>;
}

#[cfg(target_os = "linux")]
impl CpuTimeExt for crate::CpuTime {
fn nice(&self) -> Time {
self.as_ref().nice()
Expand Down
4 changes: 2 additions & 2 deletions heim-cpu/src/stats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,6 @@ impl fmt::Debug for CpuStats {
/// Returns future which will resolve into [CpuStats].
///
/// [CpuStats]: ./struct.CpuStats.html
pub fn stats() -> impl Future<Output = Result<CpuStats>> {
sys::stats().map_ok(Into::into)
pub async fn stats() -> Result<CpuStats> {
sys::stats().await.map(Into::into)
}
8 changes: 4 additions & 4 deletions heim-cpu/src/sys/macos/count.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ fn sysctl(key: &[u8]) -> Result<u64> {
}
}

pub fn logical_count() -> impl Future<Output = Result<u64>> {
future::ready(sysctl(b"hw.logicalcpu\0"))
pub async fn logical_count() -> Result<u64> {
sysctl(b"hw.logicalcpu\0")
}

pub fn physical_count() -> impl Future<Output = Result<Option<u64>>> {
future::ready(sysctl(b"hw.physicalcpu\0").map(Some))
pub async fn physical_count() -> Result<Option<u64>> {
sysctl(b"hw.physicalcpu\0").map(Some)
}
18 changes: 8 additions & 10 deletions heim-cpu/src/sys/macos/freq.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,14 @@ impl CpuFrequency {
}
}

pub fn frequency() -> impl Future<Output = Result<CpuFrequency>> {
future::lazy(|_| {
let current = bindings::cpu_frequency()?;
let min = bindings::cpu_frequency_min()?;
let max = bindings::cpu_frequency_max()?;
pub async fn frequency() -> Result<CpuFrequency> {
let current = bindings::cpu_frequency()?;
let min = bindings::cpu_frequency_min()?;
let max = bindings::cpu_frequency_max()?;

Ok(CpuFrequency {
current: Frequency::new::<frequency::hertz>(current),
min: Frequency::new::<frequency::hertz>(min),
max: Frequency::new::<frequency::hertz>(max),
})
Ok(CpuFrequency {
current: Frequency::new::<frequency::hertz>(current),
min: Frequency::new::<frequency::hertz>(min),
max: Frequency::new::<frequency::hertz>(max),
})
}
8 changes: 3 additions & 5 deletions heim-cpu/src/sys/macos/stats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,8 @@ impl From<bindings::vmmeter> for CpuStats {
}
}

pub fn stats() -> impl Future<Output = Result<CpuStats>> {
future::lazy(|_| {
let vm = unsafe { bindings::vm_meter()? };
pub async fn stats() -> Result<CpuStats> {
let vm = unsafe { bindings::vm_meter()? };

Ok(vm.into())
})
Ok(vm.into())
}
8 changes: 3 additions & 5 deletions heim-cpu/src/sys/macos/times.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,9 @@ impl From<bindings::processor_cpu_load_info> for CpuTime {
}
}

pub fn time() -> impl Future<Output = Result<CpuTime>> {
future::lazy(|_| {
let info = unsafe { bindings::cpu_load_info()? };
Ok(info.into())
})
pub async fn time() -> Result<CpuTime> {
let info = unsafe { bindings::cpu_load_info()? };
Ok(info.into())
}

pub fn times() -> impl Stream<Item = Result<CpuTime>> {
Expand Down
30 changes: 13 additions & 17 deletions heim-cpu/src/sys/windows/count.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,28 @@ use winapi::um::{winbase, winnt};
use super::wrappers::count::LogicalProcessors;
use heim_common::prelude::*;

pub fn logical_count() -> impl Future<Output = Result<u64>> {
pub async fn logical_count() -> Result<u64> {
// Safety: seems to be a very straightforward function.
// https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getactiveprocessorcount
let result = unsafe { winbase::GetActiveProcessorCount(winnt::ALL_PROCESSOR_GROUPS) };

if result > 0 {
future::ok(u64::from(result))
Ok(u64::from(result))
} else {
future::err(Error::last_os_error())
Err(Error::last_os_error())
}
}

pub fn physical_count() -> impl Future<Output = Result<Option<u64>>> {
match LogicalProcessors::get() {
Ok(processors) => {
let count = processors
.iter()
.filter(|p| p.Relationship == winnt::RelationProcessorCore)
.count();
pub async fn physical_count() -> Result<Option<u64>> {
let processors = LogicalProcessors::get()?;
let count = processors
.iter()
.filter(|p| p.Relationship == winnt::RelationProcessorCore)
.count();

if count > 0 {
future::ok(Some(count as u64))
} else {
future::ok(None)
}
}
Err(e) => future::err(e.into()),
if count > 0 {
Ok(Some(count as u64))
} else {
Ok(None)
}
}
19 changes: 7 additions & 12 deletions heim-cpu/src/sys/windows/freq.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,17 +54,12 @@ unsafe fn get_processors() -> Result<Vec<PROCESSOR_POWER_INFORMATION>> {
}
}

pub fn frequency() -> impl Future<Output = Result<CpuFrequency>> {
match unsafe { get_processors() } {
Ok(processors) => {
let freq = processors
.into_iter()
.next()
.map(CpuFrequency)
.ok_or_else(|| Error::incompatible("No processors was found"));
pub async fn frequency() -> Result<CpuFrequency> {
let processors = unsafe { get_processors()? };

future::ready(freq)
}
Err(e) => future::err(e),
}
processors
.into_iter()
.next()
.map(CpuFrequency)
.ok_or_else(|| Error::incompatible("No processors was found"))
}
22 changes: 10 additions & 12 deletions heim-cpu/src/sys/windows/stats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,17 +60,15 @@ fn interrupts() -> Result<u64> {
Ok(count.into())
}

pub fn stats() -> impl Future<Output = Result<CpuStats>> {
future::lazy(|_| {
let (ctx_switches, system_calls) = system_performance_info()?;
let dpc = dpc_count()?;
let interrupts = interrupts()?;

Ok(CpuStats {
ctx_switches,
system_calls,
interrupts,
dpc_count: dpc,
})
pub async fn stats() -> Result<CpuStats> {
let (ctx_switches, system_calls) = system_performance_info()?;
let dpc = dpc_count()?;
let interrupts = interrupts()?;

Ok(CpuStats {
ctx_switches,
system_calls,
interrupts,
dpc_count: dpc,
})
}
6 changes: 3 additions & 3 deletions heim-cpu/src/sys/windows/times.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,23 +28,23 @@ impl CpuTime {
}

// https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-getsystemtimes
pub fn time() -> impl Future<Output = Result<CpuTime>> {
pub async fn time() -> Result<CpuTime> {
let mut user = minwindef::FILETIME::default();
let mut kernel = minwindef::FILETIME::default();
let mut idle = minwindef::FILETIME::default();

let result = unsafe { processthreadsapi::GetSystemTimes(&mut idle, &mut kernel, &mut user) };

if result == 0 {
future::err(Error::last_os_error())
Err(Error::last_os_error())
} else {
let user = user.into_time();
let idle = idle.into_time();
// Same as `psutil` subtracting idle time
// and leaving only busy kernel time
let system = kernel.into_time() - idle;

future::ok(CpuTime { user, system, idle })
Ok(CpuTime { user, system, idle })
}
}

Expand Down
4 changes: 2 additions & 2 deletions heim-cpu/src/times.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ impl fmt::Debug for CpuTime {
/// Returns future which will resolve into cumulative value of all [CPU times].
///
/// [CPU times]: struct.CpuTime.html
pub fn time() -> impl Future<Output = Result<CpuTime>> {
sys::time().map_ok(Into::into)
pub async fn time() -> Result<CpuTime> {
sys::time().await.map(Into::into)
}

/// Returns stream which will yield [CPU time] for each CPU.
Expand Down

0 comments on commit 607c461

Please sign in to comment.