nuta / kerla

A new operating system kernel with Linux binary compatibility written in Rust.
Other
3.33k stars 89 forks source link

Implement ext2 reader/writer library #70

Open dust1 opened 2 years ago

dust1 commented 2 years ago

Summary

https://github.com/nuta/kerla/issues/48#issuecomment-962287339

dust1 commented 2 years ago

@nuta hello, I try to implement it, does it mean I need to read and write to the disk directly?

nuta commented 2 years ago

The first step will be an ext2 reader. You should use a trait to access disks to make it portable and testable as a simple Rust application.

For example , if I were to implement it, I would:

#![cfg_attr(not(test), no_std)]

trait Disk {
    fn read_block(&mut self, lba: usize, buf: &mut [u8]) -> Result<usize /* # of bytes actually read */, DiskError>;
    fn write_block(&mut self, lba: usize, buf: &[u8]) -> Result<usize /* # of bytes actually written */, DiskError>;
}

struct Ext2Fs<D: Disk> {
    disk: D,
}

impl<D: Disk> Ext2Fs<D> {
  pub fn new(disk: D) {
    Ext2Fs {
      disk,
    }
  }
}

#[cfg(test)]
mod tests {
    struct PseudoDisk;
    impl Disk for PseudoDIsk {
        fn read_block(...) {
            let f = std::fs::File::open("testdata/ext2-test.img");
            ...
        }
    }

    #[test]
    fn test() {
        let mut fs = Ext2Fs(PseudoDisk);
    }
}
dust1 commented 2 years ago

that means i should implement the way to reader disk in no std, not just defined trait?

nuta commented 2 years ago

You don't need to provide the implementation of a trait in no_std until you port the library into Kerla. In the library development, as shown in the code above, you can use std features to emulate disks.

nuta commented 2 years ago

IIRC, #![cfg_attr(not(test), no_std)] does not enableno_std mode in testing (cargo test).

dust1 commented 2 years ago

i get it now. thank you