Skip to content

Commit

Permalink
Extract Components from System
Browse files Browse the repository at this point in the history
  • Loading branch information
GuillaumeGomez committed Sep 17, 2023
1 parent 80460e2 commit 8a2720d
Show file tree
Hide file tree
Showing 30 changed files with 438 additions and 313 deletions.
19 changes: 11 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ Otherwise, here is a little code sample:

```rust
use sysinfo::{
Disks, DisksExt, NetworkExt, Networks, NetworksExt, ProcessExt, System,
SystemExt,
Components, ComponentsExt, Disks, DisksExt, NetworkExt, Networks,
NetworksExt, ProcessExt, System, SystemExt,
};

// Please note that we use "new_all" to ensure that all list of
Expand Down Expand Up @@ -65,16 +65,16 @@ println!("NB CPUs: {}", sys.cpus().len());

// Display processes ID, name na disk usage:
for (pid, process) in sys.processes() {
println!("[{}] {} {:?}", pid, process.name(), process.disk_usage());
println!("[{pid}] {} {:?}", process.name(), process.disk_usage());
}

// We display all disks' information:
println!("=> disks:");
let mut disks = Disks::new();
// We refresh the disk list.
disks.refresh_list();
for disk in disks.disks() {
println!("{:?}", disk);
for disk in disks.iter() {
println!("{disk:?}");
}

// Network interfaces name, data received and data transmitted:
Expand All @@ -83,13 +83,16 @@ let mut networks = Networks::new();
networks.refresh_list();
println!("=> networks:");
for (interface_name, data) in &networks {
println!("{}: {}/{} B", interface_name, data.received(), data.transmitted());
println!("{interface_name}: {}/{} B", data.received(), data.transmitted());
}

// Components temperature:
let mut components = Components::new();
// We refresh the component list.
components.refresh_list();
println!("=> components:");
for component in sys.components() {
println!("{:?}", component);
for component in components.iter() {
println!("{component:?}");
}
```

Expand Down
12 changes: 7 additions & 5 deletions benches/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
extern crate test;

use sysinfo::get_current_pid;
use sysinfo::{DiskExt, DisksExt, NetworksExt, SystemExt};
use sysinfo::{ComponentsExt, DiskExt, DisksExt, NetworksExt, SystemExt};

#[bench]
fn bench_new(b: &mut test::Bencher) {
Expand Down Expand Up @@ -140,19 +140,21 @@ fn bench_refresh_cpu(b: &mut test::Bencher) {

#[bench]
fn bench_refresh_components(b: &mut test::Bencher) {
let mut s = sysinfo::System::new_all();
let mut c = sysinfo::Components::new();
c.refresh_list();

b.iter(move || {
s.refresh_components();
c.refresh();
});
}

#[bench]
fn bench_refresh_components_list(b: &mut test::Bencher) {
let mut s = sysinfo::System::new_all();
let mut c = sysinfo::Components::new();
c.refresh_list();

b.iter(move || {
s.refresh_components_list();
c.refresh_list();
});
}

Expand Down
11 changes: 8 additions & 3 deletions examples/simple.c
Original file line number Diff line number Diff line change
Expand Up @@ -58,15 +58,19 @@ bool process_loop(pid_t pid, CProcess process, void *data) {

int main() {
CSystem system = sysinfo_init();
CNetworks networks = sysinfo_networks_init();

sysinfo_refresh_all(system);
sysinfo_networks_refresh_list(networks);

printf("total memory: %ld\n", sysinfo_total_memory(system));
printf("free memory: %ld\n", sysinfo_free_memory(system));
printf("used memory: %ld\n", sysinfo_used_memory(system));
printf("total swap: %ld\n", sysinfo_total_swap(system));
printf("free swap: %ld\n", sysinfo_free_swap(system));
printf("used swap: %ld\n", sysinfo_used_swap(system));
printf("networks received: %ld\n", sysinfo_networks_received(system));
printf("networks transmitted: %ld\n", sysinfo_networks_transmitted(system));
printf("networks received: %ld\n", sysinfo_networks_received(networks));
printf("networks transmitted: %ld\n", sysinfo_networks_transmitted(networks));
unsigned int len = 0, i = 0;
float *procs = NULL;
sysinfo_cpus_usage(system, &len, &procs);
Expand All @@ -80,7 +84,8 @@ int main() {
i = 0;
printf("For a total of %ld processes.\n", sysinfo_processes(system, process_loop, &i));
check_tasks(system);
// we can now free the CSystem object.
// we can now free the CSystem and the CNetworks objects.
sysinfo_destroy(system);
sysinfo_networks_destroy(networks);
return 0;
}
27 changes: 18 additions & 9 deletions examples/simple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ use std::io::{self, BufRead, Write};
use std::str::FromStr;
use sysinfo::Signal::*;
use sysinfo::{
CpuExt, Disks, DisksExt, NetworkExt, Networks, NetworksExt, Pid, ProcessExt, Signal, System,
SystemExt, UserExt,
Components, ComponentsExt, CpuExt, Disks, DisksExt, NetworkExt, Networks, NetworksExt, Pid,
ProcessExt, Signal, System, SystemExt, UserExt,
};

const signals: &[Signal] = &[
Expand Down Expand Up @@ -147,6 +147,7 @@ fn interpret_input(
sys: &mut System,
networks: &mut Networks,
disks: &mut Disks,
components: &mut Components,
) -> bool {
match input.trim() {
"help" => print_help(),
Expand Down Expand Up @@ -277,7 +278,7 @@ fn interpret_input(
}
}
"temperature" => {
for component in sys.components() {
for component in components.iter() {
writeln!(&mut io::stdout(), "{component:?}");
}
}
Expand Down Expand Up @@ -438,11 +439,13 @@ fn interpret_input(

fn main() {
println!("Getting system information...");
let mut t = System::new_all();
let mut n = Networks::new();
let mut d = Disks::new();
n.refresh_list();
d.refresh_list();
let mut system = System::new_all();
let mut networks = Networks::new();
let mut disks = Disks::new();
let mut components = Components::new();
networks.refresh_list();
disks.refresh_list();
components.refresh_list();
println!("Done.");
let t_stin = io::stdin();
let mut stin = t_stin.lock();
Expand All @@ -464,6 +467,12 @@ fn main() {
if (&input as &str).ends_with('\n') {
input.pop();
}
done = interpret_input(input.as_ref(), &mut t, &mut n, &mut d);
done = interpret_input(
input.as_ref(),
&mut system,
&mut networks,
&mut disks,
&mut components,
);
}
}
11 changes: 11 additions & 0 deletions md_doc/components.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Component interfaces.

```no_run
use sysinfo::{Components, ComponentsExt};
let mut components = Components::new();
components.refresh_list();
for component in components.components() {
println!("{component:?}");
}
```
14 changes: 0 additions & 14 deletions src/c_interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,20 +79,6 @@ pub extern "C" fn sysinfo_refresh_cpu(system: CSystem) {
}
}

/// Equivalent of [`System::refresh_components()`][crate::System#method.refresh_temperatures].
#[no_mangle]
pub extern "C" fn sysinfo_refresh_components(system: CSystem) {
assert!(!system.is_null());
unsafe {
let mut system: Box<System> = Box::from_raw(system as *mut System);
{
let system: &mut System = system.borrow_mut();
system.refresh_components();
}
Box::into_raw(system);
}
}

/// Equivalent of [`System::refresh_all()`][crate::System#method.refresh_all].
#[no_mangle]
pub extern "C" fn sysinfo_refresh_all(system: CSystem) {
Expand Down
37 changes: 19 additions & 18 deletions src/common.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Take a look at the license at the top of the repository in the LICENSE file.

use crate::{Disk, GroupExt, NetworkData, NetworksExt, User, UserExt};
use crate::{
Component, Components, ComponentsExt, Disk, GroupExt, NetworkData, NetworksExt, User, UserExt,
};

use std::cmp::Ordering;
use std::collections::HashMap;
Expand Down Expand Up @@ -367,8 +369,6 @@ pub struct RefreshKind {
processes: Option<ProcessRefreshKind>,
memory: bool,
cpu: Option<CpuRefreshKind>,
components: bool,
components_list: bool,
users_list: bool,
}

Expand All @@ -383,8 +383,6 @@ impl RefreshKind {
/// assert_eq!(r.processes().is_some(), false);
/// assert_eq!(r.memory(), false);
/// assert_eq!(r.cpu().is_some(), false);
/// assert_eq!(r.components(), false);
/// assert_eq!(r.components_list(), false);
/// assert_eq!(r.users_list(), false);
/// ```
pub fn new() -> Self {
Expand All @@ -401,17 +399,13 @@ impl RefreshKind {
/// assert_eq!(r.processes().is_some(), true);
/// assert_eq!(r.memory(), true);
/// assert_eq!(r.cpu().is_some(), true);
/// assert_eq!(r.components(), true);
/// assert_eq!(r.components_list(), true);
/// assert_eq!(r.users_list(), true);
/// ```
pub fn everything() -> Self {
Self {
processes: Some(ProcessRefreshKind::everything()),
memory: true,
cpu: Some(CpuRefreshKind::everything()),
components: true,
components_list: true,
users_list: true,
}
}
Expand All @@ -425,13 +419,6 @@ impl RefreshKind {
);
impl_get_set!(RefreshKind, memory, with_memory, without_memory);
impl_get_set!(RefreshKind, cpu, with_cpu, without_cpu, CpuRefreshKind);
impl_get_set!(RefreshKind, components, with_components, without_components);
impl_get_set!(
RefreshKind,
components_list,
with_components_list,
without_components_list
);
impl_get_set!(RefreshKind, users_list, with_users_list, without_users_list);
}

Expand Down Expand Up @@ -490,15 +477,15 @@ impl<'a> Iterator for NetworksIter<'a> {
}
}

/// Disks interfaces.
/// Disk interfaces.
///
/// ```no_run
/// use sysinfo::{Disks, DisksExt};
///
/// let mut disks = Disks::new();
/// disks.refresh_list();
/// for disk in disks.disks() {
/// println!("{:?}", disk);
/// println!("{disk:?}");
/// }
/// ```
pub struct Disks {
Expand Down Expand Up @@ -542,6 +529,20 @@ pub enum DiskKind {
Unknown(isize),
}

impl std::ops::Deref for Components {
type Target = [Component];

fn deref(&self) -> &Self::Target {
self.components()
}
}

impl std::ops::DerefMut for Components {
fn deref_mut(&mut self) -> &mut Self::Target {
self.components_mut()
}
}

/// An enum representing signals on UNIX-like systems.
///
/// On non-unix systems, this enum is mostly useless and is only there to keep coherency between
Expand Down
18 changes: 15 additions & 3 deletions src/debug.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// Take a look at the license at the top of the repository in the LICENSE file.

use crate::{
Component, ComponentExt, Cpu, CpuExt, Disk, DiskExt, Disks, NetworkData, NetworkExt, Networks,
NetworksExt, Process, ProcessExt, System, SystemExt, User, UserExt,
Component, ComponentExt, Components, Cpu, CpuExt, Disk, DiskExt, Disks, NetworkData,
NetworkExt, Networks, NetworksExt, Process, ProcessExt, System, SystemExt, User, UserExt,
};

use std::fmt;
Expand Down Expand Up @@ -30,7 +30,6 @@ impl fmt::Debug for System {
.field("free swap", &self.free_swap())
.field("nb CPUs", &self.cpus().len())
.field("nb processes", &self.processes().len())
.field("nb components", &self.components().len())
.finish()
}
}
Expand Down Expand Up @@ -76,6 +75,19 @@ impl fmt::Debug for Process {
}
}

impl fmt::Debug for Components {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"Components {{ {} }}",
self.iter()
.map(|x| format!("{x:?}"))
.collect::<Vec<_>>()
.join(", ")
)
}
}

impl fmt::Debug for Component {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(critical) = self.critical() {
Expand Down
6 changes: 3 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,10 @@ pub use common::{
Networks, NetworksIter, Pid, PidExt, ProcessRefreshKind, ProcessStatus, RefreshKind, Signal,
Uid,
};
pub use sys::{Component, Cpu, Disk, NetworkData, Process, System, User};
pub use sys::{Component, Components, Cpu, Disk, NetworkData, Process, System, User};
pub use traits::{
ComponentExt, CpuExt, DiskExt, DisksExt, GroupExt, NetworkExt, NetworksExt, ProcessExt,
SystemExt, UserExt,
ComponentExt, ComponentsExt, CpuExt, DiskExt, DisksExt, GroupExt, NetworkExt, NetworksExt,
ProcessExt, SystemExt, UserExt,
};

#[cfg(feature = "c-interface")]
Expand Down
10 changes: 9 additions & 1 deletion src/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,6 @@ impl serde::Serialize for crate::System {
state.serialize_field("free_swap", &self.free_swap())?;
state.serialize_field("used_swap", &self.used_swap())?;

state.serialize_field("components", &self.components())?;
state.serialize_field("users", &self.users())?;

state.serialize_field("uptime", &self.uptime())?;
Expand Down Expand Up @@ -146,6 +145,15 @@ impl Serialize for crate::Disks {
}
}

impl Serialize for crate::Components {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.collect_seq(self.iter())
}
}

impl Serialize for Signal {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
Expand Down
1 change: 0 additions & 1 deletion src/sysinfo.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ void sysinfo_networks_destroy(CNetworks networks);
void sysinfo_refresh_system(CSystem system);
void sysinfo_refresh_memory(CSystem system);
void sysinfo_refresh_cpu(CSystem system);
void sysinfo_refresh_components(CSystem system);
void sysinfo_refresh_all(CSystem system);
void sysinfo_refresh_processes(CSystem system);
#ifdef __linux__
Expand Down
Loading

0 comments on commit 8a2720d

Please sign in to comment.