Treat /dev/sdN as a &mut [u8]

Let /dev/sdN be a partition on a ssd disk.

Is there a simple way to treat /dev/sdN as a &mut [u8] in Rust?

In particular, I would like to be able to read/write to [start, end) in O(end - start) + O(1) time? The O(1) for seek, and the O(end - start) for the actual data read/write.

You can mmap it I think.

2 Likes

I've had a good experience with the memmap2 crate. But note that UB occurs if the file is modified while being mapped, since the compiler expects to have exclusive access to an &mut [u8].

2 Likes

Isn't this insta-UB because the kernel essentially has a "mutable reference" to the partition already?

3 Likes

Ah, I've just found a feature of memmap2 that might be useful for this case: MmapRaw, which lets you access a file as a *mut u8 (convertible to a *mut [u8]). To access it safely, you can use read_volatile and write_volatile, although data races can still occur if another thread or program writes to the same location.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.