sysinfo/common/disk.rs
1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::ffi::OsStr;
4use std::fmt;
5use std::path::Path;
6
7use crate::common::impl_get_set::impl_get_set;
8use crate::{DiskUsage, Error};
9
10/// Struct containing a disk information.
11///
12/// ```no_run
13/// use sysinfo::Disks;
14///
15/// if let Ok(disks) = Disks::new_with_refreshed_list() {
16/// for disk in &disks {
17/// println!("{:?}: {:?}", disk.name(), disk.kind());
18/// }
19/// }
20/// ```
21pub struct Disk {
22 pub(crate) inner: crate::DiskInner,
23}
24
25impl Disk {
26 /// Returns the kind of disk.
27 ///
28 /// ```no_run
29 /// use sysinfo::Disks;
30 ///
31 /// if let Ok(disks) = Disks::new_with_refreshed_list() {
32 /// for disk in &disks {
33 /// println!("[{:?}] {:?}", disk.name(), disk.kind());
34 /// }
35 /// }
36 /// ```
37 pub fn kind(&self) -> DiskKind {
38 self.inner.kind()
39 }
40
41 /// On Unix, returns the Unix device ID.
42 ///
43 /// On Windows, returns the Volume Serial Number.
44 ///
45 /// Returns `None` if the device ID or the Volume Serial Number cannot be retrieved.
46 ///
47 /// ```no_run
48 /// use sysinfo::Disks;
49 ///
50 /// if let Ok(disks) = Disks::new_with_refreshed_list() {
51 /// for disk in &disks {
52 /// println!("[{:?}] {:?}", disk.name(), disk.id());
53 /// }
54 /// }
55 /// ```
56 pub fn id(&self) -> Option<u64> {
57 self.inner.id()
58 }
59
60 /// Returns the disk name.
61 ///
62 /// ```no_run
63 /// use sysinfo::Disks;
64 ///
65 /// if let Ok(disks) = Disks::new_with_refreshed_list() {
66 /// for disk in &disks {
67 /// println!("{:?}", disk.name());
68 /// }
69 /// }
70 /// ```
71 pub fn name(&self) -> &OsStr {
72 self.inner.name()
73 }
74
75 /// Returns the file system used on this disk (so for example: `EXT4`, `NTFS`, etc...).
76 ///
77 /// ```no_run
78 /// use sysinfo::Disks;
79 ///
80 /// if let Ok(disks) = Disks::new_with_refreshed_list() {
81 /// for disk in &disks {
82 /// println!("[{:?}] {:?}", disk.name(), disk.file_system());
83 /// }
84 /// }
85 /// ```
86 pub fn file_system(&self) -> &OsStr {
87 self.inner.file_system()
88 }
89
90 /// Returns the mount point of the disk (`/` for example).
91 ///
92 /// ```no_run
93 /// use sysinfo::Disks;
94 ///
95 /// if let Ok(disks) = Disks::new_with_refreshed_list() {
96 /// for disk in &disks {
97 /// println!("[{:?}] {:?}", disk.name(), disk.mount_point());
98 /// }
99 /// }
100 /// ```
101 pub fn mount_point(&self) -> &Path {
102 self.inner.mount_point()
103 }
104
105 /// Returns the total disk size, in bytes.
106 ///
107 /// ```no_run
108 /// use sysinfo::Disks;
109 ///
110 /// if let Ok(disks) = Disks::new_with_refreshed_list() {
111 /// for disk in &disks {
112 /// println!("[{:?}] {}B", disk.name(), disk.total_space());
113 /// }
114 /// }
115 /// ```
116 pub fn total_space(&self) -> u64 {
117 self.inner.total_space()
118 }
119
120 /// Returns the available disk size, in bytes.
121 ///
122 /// ```no_run
123 /// use sysinfo::Disks;
124 ///
125 /// if let Ok(disks) = Disks::new_with_refreshed_list() {
126 /// for disk in &disks {
127 /// println!("[{:?}] {}B", disk.name(), disk.available_space());
128 /// }
129 /// }
130 /// ```
131 pub fn available_space(&self) -> u64 {
132 self.inner.available_space()
133 }
134
135 /// Returns `true` if the disk is removable.
136 ///
137 /// ```no_run
138 /// use sysinfo::Disks;
139 ///
140 /// if let Ok(disks) = Disks::new_with_refreshed_list() {
141 /// for disk in &disks {
142 /// println!("[{:?}] {}", disk.name(), disk.is_removable());
143 /// }
144 /// }
145 /// ```
146 pub fn is_removable(&self) -> bool {
147 self.inner.is_removable()
148 }
149
150 /// Returns `true` if the disk is read-only.
151 ///
152 /// ```no_run
153 /// use sysinfo::Disks;
154 ///
155 /// if let Ok(disks) = Disks::new_with_refreshed_list() {
156 /// for disk in &disks {
157 /// println!("[{:?}] is read-only: {}", disk.name(), disk.is_read_only());
158 /// }
159 /// }
160 /// ```
161 pub fn is_read_only(&self) -> bool {
162 self.inner.is_read_only()
163 }
164
165 /// Updates the disk' information with everything loaded.
166 ///
167 /// Equivalent to <code>[Disk::refresh_specifics]\([DiskRefreshKind::everything]\())</code>.
168 ///
169 /// ```no_run
170 /// use sysinfo::Disks;
171 ///
172 /// if let Ok(mut disks) = Disks::new_with_refreshed_list() {
173 /// for disk in &mut disks {
174 /// disk.refresh();
175 /// }
176 /// }
177 /// ```
178 pub fn refresh(&mut self) -> bool {
179 self.refresh_specifics(DiskRefreshKind::everything())
180 }
181
182 /// Updates the disk's information corresponding to the given [`DiskRefreshKind`].
183 ///
184 /// ```no_run
185 /// use sysinfo::{Disks, DiskRefreshKind};
186 ///
187 /// if let Ok(mut disks) = Disks::new_with_refreshed_list() {
188 /// for disk in &mut disks {
189 /// disk.refresh_specifics(DiskRefreshKind::nothing());
190 /// }
191 /// }
192 /// ```
193 pub fn refresh_specifics(&mut self, refreshes: DiskRefreshKind) -> bool {
194 self.inner.refresh_specifics(refreshes)
195 }
196
197 /// Returns number of bytes read and written by the disk
198 ///
199 /// ```no_run
200 /// use sysinfo::Disks;
201 ///
202 /// if let Ok(disks) = Disks::new_with_refreshed_list() {
203 /// for disk in &disks {
204 /// println!("[{:?}] disk usage: {:?}", disk.name(), disk.usage());
205 /// }
206 /// }
207 /// ```
208 pub fn usage(&self) -> DiskUsage {
209 self.inner.usage()
210 }
211}
212
213/// Disks interface.
214///
215/// ```no_run
216/// use sysinfo::Disks;
217///
218/// if let Ok(disks) = Disks::new_with_refreshed_list() {
219/// for disk in &disks {
220/// println!("{disk:?}");
221/// }
222/// }
223/// ```
224///
225/// ⚠️ Note that tmpfs mounts are excluded by default under Linux.
226/// To display tmpfs mount points, the `linux-tmpfs` feature must be enabled.
227///
228/// ⚠️ Note that network devices are excluded by default under Linux.
229/// To display mount points using the CIFS and NFS protocols, the `linux-netdevs`
230/// feature must be enabled. Note, however, that sysinfo may hang under certain
231/// circumstances. For example, if a CIFS or NFS share has been mounted with
232/// the _hard_ option, but the connection has an error, such as the share server has stopped.
233pub struct Disks {
234 inner: crate::DisksInner,
235}
236
237impl<'a> IntoIterator for &'a Disks {
238 type Item = &'a Disk;
239 type IntoIter = std::slice::Iter<'a, Disk>;
240
241 fn into_iter(self) -> Self::IntoIter {
242 self.inner.list().iter()
243 }
244}
245
246impl<'a> IntoIterator for &'a mut Disks {
247 type Item = &'a mut Disk;
248 type IntoIter = std::slice::IterMut<'a, Disk>;
249
250 fn into_iter(self) -> Self::IntoIter {
251 self.inner.list_mut().iter_mut()
252 }
253}
254
255impl Disks {
256 /// Creates a new empty [`Disks`][crate::Disks] type.
257 ///
258 /// If you want it to be filled directly, take a look at [`Disks::new_with_refreshed_list`].
259 ///
260 /// ```no_run
261 /// use sysinfo::Disks;
262 ///
263 /// if let Ok(mut disks) = Disks::new() {
264 /// disks.refresh(false);
265 /// for disk in &disks {
266 /// println!("{disk:?}");
267 /// }
268 /// }
269 /// ```
270 pub fn new() -> Result<Self, Error> {
271 Ok(Self {
272 inner: crate::DisksInner::new()?,
273 })
274 }
275
276 /// Creates a new [`Disks`][crate::Disks] type with the disk list loaded.
277 ///
278 /// Equivalent to <code>[Disks::new_with_refreshed_list_specifics]\([DiskRefreshKind::everything]\())</code>.
279 ///
280 /// ```no_run
281 /// use sysinfo::Disks;
282 ///
283 /// if let Ok(mut disks) = Disks::new_with_refreshed_list() {
284 /// for disk in &disks {
285 /// println!("{disk:?}");
286 /// }
287 /// }
288 /// ```
289 pub fn new_with_refreshed_list() -> Result<Self, Error> {
290 Self::new_with_refreshed_list_specifics(DiskRefreshKind::everything())
291 }
292
293 /// Creates a new [`Disks`][crate::Disks] type with the disk list loaded
294 /// and refreshed according to the given [`DiskRefreshKind`].
295 ///
296 /// ```no_run
297 /// use sysinfo::{Disks, DiskRefreshKind};
298 ///
299 /// if let Ok(mut disks) = Disks::new_with_refreshed_list_specifics(DiskRefreshKind::nothing()) {
300 /// for disk in &disks {
301 /// println!("{disk:?}");
302 /// }
303 /// }
304 /// ```
305 pub fn new_with_refreshed_list_specifics(refreshes: DiskRefreshKind) -> Result<Self, Error> {
306 let mut disks = Self::new()?;
307 disks.refresh_specifics(false, refreshes);
308 Ok(disks)
309 }
310
311 /// Refreshes the listed disks' information.
312 ///
313 /// Equivalent to <code>[Disks::refresh_specifics]\([DiskRefreshKind::everything]\())</code>.
314 pub fn refresh(&mut self, remove_not_listed_disks: bool) {
315 self.inner
316 .refresh_specifics(remove_not_listed_disks, DiskRefreshKind::everything());
317 }
318
319 /// Refreshes the disks' information according to the given [`DiskRefreshKind`].
320 ///
321 /// ```no_run
322 /// use sysinfo::Disks;
323 ///
324 /// if let Ok(mut disks) = Disks::new_with_refreshed_list() {
325 /// // We wait some time...?
326 /// disks.refresh(true);
327 /// }
328 /// ```
329 pub fn refresh_specifics(&mut self, remove_not_listed_disks: bool, refreshes: DiskRefreshKind) {
330 self.inner
331 .refresh_specifics(remove_not_listed_disks, refreshes);
332 }
333}
334
335impl std::ops::Deref for Disks {
336 type Target = [Disk];
337
338 fn deref(&self) -> &Self::Target {
339 self.inner.list()
340 }
341}
342
343impl std::ops::DerefMut for Disks {
344 fn deref_mut(&mut self) -> &mut Self::Target {
345 self.inner.list_mut()
346 }
347}
348
349impl From<Disks> for Vec<Disk> {
350 fn from(disks: Disks) -> Self {
351 disks.inner.into_vec()
352 }
353}
354
355/// Enum containing the different supported kinds of disks.
356///
357/// This type is returned by [`Disk::kind`](`crate::Disk::kind`).
358///
359/// ```no_run
360/// use sysinfo::Disks;
361///
362/// if let Ok(disks) = Disks::new_with_refreshed_list() {
363/// for disk in &disks {
364/// println!("{:?}: {:?}", disk.name(), disk.kind());
365/// }
366/// }
367/// ```
368#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
369#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
370pub enum DiskKind {
371 /// HDD type.
372 HDD,
373 /// SSD type.
374 SSD,
375 /// Unknown type.
376 Unknown(isize),
377}
378
379impl fmt::Display for DiskKind {
380 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
381 f.write_str(match *self {
382 DiskKind::HDD => "HDD",
383 DiskKind::SSD => "SSD",
384 _ => "Unknown",
385 })
386 }
387}
388
389/// Used to determine what you want to refresh specifically on the [`Disk`] type.
390///
391/// * `kind` is about refreshing the [`Disk::kind`] information.
392/// * `storage` is about refreshing the [`Disk::available_space`] and [`Disk::total_space`] information.
393/// * `io_usage` is about refreshing the [`Disk::usage`] information.
394///
395/// ```no_run
396/// use sysinfo::{Disks, DiskRefreshKind};
397///
398/// if let Ok(disks) = Disks::new_with_refreshed_list_specifics(DiskRefreshKind::everything()) {
399/// for disk in &disks {
400/// assert!(disk.total_space() != 0);
401/// }
402/// }
403/// ```
404#[derive(Clone, Copy, Debug, Default)]
405pub struct DiskRefreshKind {
406 kind: bool,
407 storage: bool,
408 io_usage: bool,
409}
410
411impl DiskRefreshKind {
412 /// Creates a new `DiskRefreshKind` with every refresh set to false.
413 ///
414 /// ```
415 /// use sysinfo::DiskRefreshKind;
416 ///
417 /// let r = DiskRefreshKind::nothing();
418 ///
419 /// assert_eq!(r.kind(), false);
420 /// assert_eq!(r.storage(), false);
421 /// assert_eq!(r.io_usage(), false);
422 /// ```
423 pub fn nothing() -> Self {
424 Self::default()
425 }
426
427 /// Creates a new `DiskRefreshKind` with every refresh set to true.
428 ///
429 /// ```
430 /// use sysinfo::DiskRefreshKind;
431 ///
432 /// let r = DiskRefreshKind::everything();
433 ///
434 /// assert_eq!(r.kind(), true);
435 /// assert_eq!(r.storage(), true);
436 /// assert_eq!(r.io_usage(), true);
437 /// ```
438 pub fn everything() -> Self {
439 Self {
440 kind: true,
441 storage: true,
442 io_usage: true,
443 }
444 }
445
446 impl_get_set!(DiskRefreshKind, kind, with_kind, without_kind);
447 impl_get_set!(DiskRefreshKind, storage, with_storage, without_storage);
448 impl_get_set!(DiskRefreshKind, io_usage, with_io_usage, without_io_usage);
449}
450
451#[cfg(test)]
452mod tests {
453 /// This first doctest ensure that we can create a new `Disks`.
454 ///
455 /// ```
456 /// let x = sysinfo::Disks::new();
457 /// ```
458 ///
459 /// This second doctest ensures that `Disks` doesn't implement `Clone`.
460 ///
461 /// ```compile_fail
462 /// let x = sysinfo::Disks::new();
463 /// x.clone();
464 /// ```
465 #[test]
466 fn check_if_disks_is_send() {
467 fn is_send<T: Send>(_: &T) {}
468
469 let disks = crate::Disks::new();
470 is_send(&disks);
471 }
472}