Skip to main content

libblkid_rs/
devno.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5use std::ffi::CStr;
6
7use crate::err::Result;
8
9/// Device number
10pub struct BlkidDevno(libc::dev_t);
11
12#[cfg(target_os = "linux")]
13pub mod ty {
14    /// Type alias for device major number
15    #[allow(non_camel_case_types)]
16    pub type maj_t = libc::c_uint;
17
18    /// Type alias for device minor number
19    #[allow(non_camel_case_types)]
20    pub type min_t = libc::c_uint;
21}
22
23#[cfg(all(unix, not(target_os = "linux"), not(target_os = "android")))]
24pub mod ty {
25    /// Type alias for device major number
26    #[allow(non_camel_case_types)]
27    pub type maj_t = i32;
28
29    /// Type alias for device minor number
30    #[allow(non_camel_case_types)]
31    pub type min_t = i32;
32}
33
34pub use ty::*;
35
36impl BlkidDevno {
37    pub(crate) fn new(devno: libc::dev_t) -> Self {
38        BlkidDevno(devno)
39    }
40
41    pub(crate) fn as_dev_t(&self) -> libc::dev_t {
42        self.0
43    }
44
45    /// Create a `BlkidDevno` from major and minor numbers.
46    pub fn from_device_numbers(major: maj_t, minor: min_t) -> Self {
47        #[allow(unused_unsafe, reason = "No longer unsafe in libc 0.2.133")]
48        BlkidDevno(unsafe { libc::makedev(major, minor) })
49    }
50
51    /// Get the major number.
52    pub fn major(&self) -> maj_t {
53        #[allow(unused_unsafe, reason = "No longer unsafe in libc 0.2.171")]
54        unsafe {
55            libc::major(self.0)
56        }
57    }
58
59    /// Get the minor number.
60    pub fn minor(&self) -> min_t {
61        #[allow(unused_unsafe, reason = "No longer unsafe in libc 0.2.171")]
62        unsafe {
63            libc::minor(self.0)
64        }
65    }
66
67    /// Get device name from device number
68    pub fn to_devname(&self) -> Result<String> {
69        let ret = errno_ptr!(unsafe { libblkid_rs_sys::blkid_devno_to_devname(self.0) })?;
70        let string_ret = unsafe { CStr::from_ptr(ret) }.to_str()?.to_string();
71        unsafe { libc::free(ret as *mut libc::c_void) };
72        Ok(string_ret)
73    }
74
75    /// Get the device number and name of the whole disk associated with this device
76    /// number
77    pub fn to_wholedisk(&self) -> Result<(String, BlkidDevno)> {
78        let buf = &mut [0u8; 4096];
79        let mut wholedisk_devno: libc::dev_t = 0;
80        errno!(unsafe {
81            libblkid_rs_sys::blkid_devno_to_wholedisk(
82                self.0,
83                buf.as_mut_ptr() as *mut libc::c_char,
84                buf.len(),
85                &mut wholedisk_devno as *mut _,
86            )
87        })?;
88        let name = std::str::from_utf8(buf)?.to_string();
89        Ok((name, BlkidDevno(wholedisk_devno)))
90    }
91}