block_file.rs 1020 B

1234567891011121314151617181920212223242526272829303132333435
  1. use another_ext4::{Block, BlockDevice, BLOCK_SIZE};
  2. use std::fs::{File, OpenOptions};
  3. use std::io::{Read, Seek, SeekFrom, Write};
  4. #[derive(Debug)]
  5. pub struct BlockFile(File);
  6. impl BlockFile {
  7. pub fn new(path: &str) -> Self {
  8. let file = OpenOptions::new()
  9. .read(true)
  10. .write(true)
  11. .open(path)
  12. .unwrap();
  13. Self(file)
  14. }
  15. }
  16. impl BlockDevice for BlockFile {
  17. fn read_block(&self, block_id: u64) -> Block {
  18. let mut file = &self.0;
  19. let mut buffer = [0u8; BLOCK_SIZE];
  20. // warn!("read_block {}", block_id);
  21. let _r = file.seek(SeekFrom::Start(block_id * BLOCK_SIZE as u64));
  22. let _r = file.read_exact(&mut buffer);
  23. Block::new(block_id, buffer)
  24. }
  25. fn write_block(&self, block: &Block) {
  26. let mut file = &self.0;
  27. // warn!("write_block {}", block.block_id);
  28. let _r = file.seek(SeekFrom::Start(block.id * BLOCK_SIZE as u64));
  29. let _r = file.write_all(&block.data);
  30. }
  31. }