Skip to content

Commit

Permalink
Merge pull request #984 from GuillaumeGomez/disks
Browse files Browse the repository at this point in the history
[cleanup] Move disk content into Disks type
  • Loading branch information
GuillaumeGomez committed Jun 2, 2023
2 parents a89da0e + b30e3d6 commit c0b0f7c
Show file tree
Hide file tree
Showing 28 changed files with 356 additions and 232 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ sys.refresh_all();

// We display all disks' information:
println!("=> disks:");
for disk in sys.disks() {
for disk in sys.disks().iter() {
println!("{:?}", disk);
}

Expand Down
2 changes: 1 addition & 1 deletion examples/simple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ fn interpret_input(input: &str, sys: &mut System) -> bool {
}
}
"disks" => {
for disk in sys.disks() {
for disk in sys.disks().iter() {
writeln!(&mut io::stdout(), "{disk:?}");
}
}
Expand Down
8 changes: 0 additions & 8 deletions md_doc/networks.md

This file was deleted.

35 changes: 26 additions & 9 deletions src/apple/disk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::sys::{
ffi,
utils::{self, CFReleaser},
};
use crate::{DiskExt, DiskKind};
use crate::{DiskExt, DiskKind, Disks, DisksExt};

use core_foundation_sys::array::CFArrayCreate;
use core_foundation_sys::base::kCFAllocatorDefault;
Expand Down Expand Up @@ -81,18 +81,36 @@ impl DiskExt for Disk {
}
}

pub(super) unsafe fn get_disks() -> Vec<Disk> {
impl DisksExt for Disks {
fn refresh_list(&mut self) {
unsafe {
get_disks(&mut self.disks);
}
}

fn disks(&self) -> &[Disk] {
&self.disks
}

fn disks_mut(&mut self) -> &mut [Disk] {
&mut self.disks
}
}

unsafe fn get_disks(container: &mut Vec<Disk>) {
container.clear();

let raw_disks = {
let count = libc::getfsstat(ptr::null_mut(), 0, libc::MNT_NOWAIT);
if count < 1 {
return Vec::new();
return;
}
let bufsize = count * std::mem::size_of::<libc::statfs>() as libc::c_int;
let mut disks = Vec::with_capacity(count as _);
let count = libc::getfsstat(disks.as_mut_ptr(), bufsize, libc::MNT_NOWAIT);

if count < 1 {
return Vec::new();
return;
}

disks.set_len(count as usize);
Expand All @@ -115,11 +133,10 @@ pub(super) unsafe fn get_disks() -> Vec<Disk> {
Some(properties) => properties,
None => {
sysinfo_debug!("failed to create volume key list");
return Vec::new();
return;
}
};

let mut disks = Vec::with_capacity(raw_disks.len());
for c_disk in raw_disks {
let volume_url = match CFReleaser::new(
core_foundation_sys::url::CFURLCreateFromFileSystemRepresentation(
Expand Down Expand Up @@ -178,10 +195,10 @@ pub(super) unsafe fn get_disks() -> Vec<Disk> {
CStr::from_ptr(c_disk.f_mntonname.as_ptr()).to_bytes(),
));

disks.extend(new_disk(mount_point, volume_url, c_disk, &prop_dict))
if let Some(disk) = new_disk(mount_point, volume_url, c_disk, &prop_dict) {
container.push(disk);
}
}

disks
}

type RetainedCFArray = CFReleaser<core_foundation_sys::array::__CFArray>;
Expand Down
2 changes: 1 addition & 1 deletion src/apple/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,6 @@ mod utils;
pub use self::component::Component;
pub use self::cpu::Cpu;
pub use self::disk::Disk;
pub use self::network::{NetworkData, Networks};
pub use self::network::NetworkData;
pub use self::process::Process;
pub use self::system::System;
15 changes: 2 additions & 13 deletions src/apple/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

use libc::{self, c_char, if_msghdr2, CTL_NET, NET_RT_IFLIST2, PF_ROUTE, RTM_IFINFO2};

use std::collections::{hash_map, HashMap};
use std::collections::hash_map;
use std::ptr::null_mut;

use crate::common::MacAddr;
use crate::network::refresh_networks_addresses;
use crate::{NetworkExt, NetworksExt, NetworksIter};
use crate::{NetworkExt, Networks, NetworksExt, NetworksIter};

macro_rules! old_and_new {
($ty_:expr, $name:ident, $old:ident, $new_val:expr) => {{
Expand All @@ -16,18 +16,7 @@ macro_rules! old_and_new {
}};
}

#[doc = include_str!("../../md_doc/networks.md")]
pub struct Networks {
interfaces: HashMap<String, NetworkData>,
}

impl Networks {
pub(crate) fn new() -> Self {
Networks {
interfaces: HashMap::new(),
}
}

#[allow(unknown_lints)]
#[allow(clippy::cast_ptr_alignment)]
#[allow(clippy::uninit_vec)]
Expand Down
24 changes: 6 additions & 18 deletions src/apple/system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@

use crate::sys::component::Component;
use crate::sys::cpu::*;
use crate::sys::disk::*;
use crate::sys::network::Networks;
use crate::sys::process::*;

use crate::{
CpuExt, CpuRefreshKind, LoadAvg, Pid, ProcessRefreshKind, RefreshKind, SystemExt, User,
CpuExt, CpuRefreshKind, Disks, LoadAvg, Networks, Pid, ProcessRefreshKind, RefreshKind,
SystemExt, User,
};

#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
Expand Down Expand Up @@ -90,7 +89,7 @@ pub struct System {
page_size_kb: u64,
#[cfg(not(any(target_os = "ios", feature = "apple-sandbox")))]
components: Components,
disks: Vec<Disk>,
disks: Disks,
networks: Networks,
port: mach_port_t,
users: Vec<User>,
Expand Down Expand Up @@ -166,7 +165,7 @@ impl SystemExt for System {
page_size_kb: sysconf(_SC_PAGESIZE) as _,
#[cfg(not(any(target_os = "ios", feature = "apple-sandbox")))]
components: Components::new(),
disks: Vec::with_capacity(1),
disks: Disks::new(),
networks: Networks::new(),
port,
users: Vec::new(),
Expand Down Expand Up @@ -364,10 +363,6 @@ impl SystemExt for System {
}
}

fn refresh_disks_list(&mut self) {
self.disks = unsafe { get_disks() };
}

fn refresh_users_list(&mut self) {
self.users = crate::apple::users::get_users_list();
}
Expand Down Expand Up @@ -465,21 +460,14 @@ impl SystemExt for System {
&mut []
}

fn disks(&self) -> &[Disk] {
fn disks(&self) -> &Disks {
&self.disks
}

fn disks_mut(&mut self) -> &mut [Disk] {
fn disks_mut(&mut self) -> &mut Disks {
&mut self.disks
}

fn sort_disks_by<F>(&mut self, compare: F)
where
F: FnMut(&Disk, &Disk) -> std::cmp::Ordering,
{
self.disks.sort_unstable_by(compare);
}

fn uptime(&self) -> u64 {
unsafe {
let csec = libc::time(::std::ptr::null_mut());
Expand Down
73 changes: 66 additions & 7 deletions src/common.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
// Take a look at the license at the top of the repository in the LICENSE file.

use crate::{NetworkData, Networks, NetworksExt, UserExt};
use crate::{Disk, NetworkData, NetworksExt, UserExt};

use std::collections::HashMap;
use std::convert::{From, TryFrom};
use std::fmt;
use std::str::FromStr;
Expand Down Expand Up @@ -460,6 +461,37 @@ impl RefreshKind {
impl_get_set!(RefreshKind, users_list, with_users_list, without_users_list);
}

/// Networks interfaces.
///
/// ```no_run
/// use sysinfo::{NetworksExt, System, SystemExt};
///
/// let s = System::new_all();
/// for network in s.networks().iter() {
/// println!("{:?}", network);
/// }
/// ```
pub struct Networks {
pub(crate) interfaces: HashMap<String, NetworkData>,
}

impl Networks {
pub(crate) fn new() -> Networks {
Networks {
interfaces: HashMap::new(),
}
}
}

impl<'a> IntoIterator for &'a Networks {
type Item = (&'a String, &'a NetworkData);
type IntoIter = NetworksIter<'a>;

fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}

/// Iterator over network interfaces.
///
/// It is returned by [`Networks::iter`][crate::Networks#method.iter].
Expand Down Expand Up @@ -488,12 +520,39 @@ impl<'a> Iterator for NetworksIter<'a> {
}
}

impl<'a> IntoIterator for &'a Networks {
type Item = (&'a String, &'a NetworkData);
type IntoIter = NetworksIter<'a>;
/// Disks interfaces.
///
/// ```no_run
/// use sysinfo::{DiskExt, System, SystemExt};
///
/// let s = System::new_all();
/// for disk in s.disks().iter() {
/// println!("{:?}", disk);
/// }
/// ```
pub struct Disks {
pub(crate) disks: Vec<Disk>,
}

fn into_iter(self) -> Self::IntoIter {
self.iter()
impl Disks {
pub(crate) fn new() -> Self {
Self {
disks: Vec::with_capacity(2),
}
}
}

impl std::ops::Deref for Disks {
type Target = [Disk];

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

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

Expand All @@ -505,7 +564,7 @@ impl<'a> IntoIterator for &'a Networks {
/// use sysinfo::{System, SystemExt, DiskExt};
///
/// let system = System::new_all();
/// for disk in system.disks() {
/// for disk in system.disks().iter() {
/// println!("{:?}: {:?}", disk.name(), disk.kind());
/// }
/// ```
Expand Down
15 changes: 14 additions & 1 deletion src/debug.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Take a look at the license at the top of the repository in the LICENSE file.

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

Expand Down Expand Up @@ -130,3 +130,16 @@ impl fmt::Debug for NetworkData {
.finish()
}
}

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

0 comments on commit c0b0f7c

Please sign in to comment.