Skip to content

Commit

Permalink
Add LoopControl::add (#56)
Browse files Browse the repository at this point in the history
* Add LoopControl::add

Add LoopControl::add for adding/creating new loop devices via the
LOOP_CTL_ADD ioctl.

* Fixup the tests for creating new loop devs

It did not work for me as it counted the 'loop-control' file as an extra one so never failed with the file already existing.

Co-authored-by: Michael Daffin <[email protected]>
  • Loading branch information
flxo and mdaffin authored Nov 11, 2022
1 parent 99a3662 commit 64a8ddb
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
30 changes: 28 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@
//! ld.detach().unwrap();
//! ```
use crate::bindings::{
loop_info64, LOOP_CLR_FD, LOOP_CTL_GET_FREE, LOOP_SET_CAPACITY, LOOP_SET_FD, LOOP_SET_STATUS64,
LO_FLAGS_AUTOCLEAR, LO_FLAGS_PARTSCAN, LO_FLAGS_READ_ONLY,
loop_info64, LOOP_CLR_FD, LOOP_CTL_ADD, LOOP_CTL_GET_FREE, LOOP_SET_CAPACITY, LOOP_SET_FD,
LOOP_SET_STATUS64, LO_FLAGS_AUTOCLEAR, LO_FLAGS_PARTSCAN, LO_FLAGS_READ_ONLY,
};
#[cfg(feature = "direct_io")]
use bindings::LOOP_SET_DIRECT_IO;
Expand Down Expand Up @@ -120,6 +120,32 @@ impl LoopControl {
})?;
LoopDevice::open(&format!("{}{}", LOOP_PREFIX, dev_num))
}

/// Add and opens a new loop device.
///
/// # Examples
///
/// ```rust
/// use loopdev::LoopControl;
/// let lc = LoopControl::open().unwrap();
/// let ld = lc.add(1).unwrap();
/// println!("{}", ld.path().unwrap().display());
/// ```
///
/// # Errors
///
/// This funcitons will return an error when a loop device with the passed
/// number exists or opening the newly created device fails.
pub fn add(&self, n: u32) -> io::Result<LoopDevice> {
let dev_num = ioctl_to_error(unsafe {
ioctl(
self.dev_file.as_raw_fd() as c_int,
LOOP_CTL_ADD as IoctlRequest,
n as c_int,
)
})?;
LoopDevice::open(&format!("{}{}", LOOP_PREFIX, dev_num))
}
}

impl AsRawFd for LoopControl {
Expand Down
21 changes: 21 additions & 0 deletions tests/integration_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,3 +211,24 @@ fn attach_a_backing_file_with_part_scan(file_size: i64) {
"there should be only one partition for the device"
);
}

#[test]
fn add_a_loop_device() {
let _lock = setup();
let dev = std::fs::read_dir("/dev").expect("should be able to open /dev");
let device_count = dev
.map(|r| {
r.as_ref()
.expect("readdir failed")
.file_name()
.to_string_lossy()
.to_string()
})
.filter(|r| r != "loop-control")
.filter(|r| r.contains("loop"))
.count();

let lc = LoopControl::open().expect("should be able to open the LoopControl device");
assert!(lc.add(device_count as u32).is_err()); // EEXIST
assert!(lc.add(device_count as u32 + 1).is_ok())
}

0 comments on commit 64a8ddb

Please sign in to comment.