Remove DirentBytes

pull/20/head
Yifan Wu 4 years ago
parent 3e47a0dbee
commit a589179adc

@ -407,10 +407,13 @@ pub struct DirEntry {
pub const DIRENT_SZ: usize = 32;
//pub type DirentBlock = [DirEntry; BLOCK_SZ / DIRENT_SZ];
pub type DirentBytes = [u8; DIRENT_SZ];
impl DirEntry {
pub fn empty() -> Self {
Self {
name: [0u8; NAME_LENGTH_LIMIT + 1],
inode_number: 0,
}
}
pub fn new(name: &str, inode_number: u32) -> Self {
let mut bytes = [0u8; NAME_LENGTH_LIMIT + 1];
&mut bytes[..name.len()].copy_from_slice(name.as_bytes());
@ -419,18 +422,20 @@ impl DirEntry {
inode_number,
}
}
pub fn into_bytes(&self) -> &DirentBytes {
pub fn as_bytes(&self) -> &[u8] {
unsafe {
&*(self as *const Self as usize as *const DirentBytes)
core::slice::from_raw_parts(
self as *const _ as usize as *const u8,
DIRENT_SZ,
)
}
}
pub fn from_bytes(bytes: &DirentBytes) -> &Self {
unsafe { &*(bytes.as_ptr() as usize as *const Self) }
}
#[allow(unused)]
pub fn from_bytes_mut(bytes: &mut DirentBytes) -> &mut Self {
pub fn as_bytes_mut(&mut self) -> &mut [u8] {
unsafe {
&mut *(bytes.as_mut_ptr() as usize as *mut Self)
core::slice::from_raw_parts_mut(
self as *mut _ as usize as *mut u8,
DIRENT_SZ,
)
}
}
pub fn name(&self) -> &str {

@ -3,7 +3,6 @@ use super::{
DiskInode,
DiskInodeType,
DirEntry,
DirentBytes,
EasyFileSystem,
DIRENT_SZ,
get_block_cache,
@ -63,17 +62,16 @@ impl Inode {
// assert it is a directory
assert!(disk_inode.is_dir());
let file_count = (disk_inode.size as usize) / DIRENT_SZ;
let mut dirent_space: DirentBytes = Default::default();
let mut dirent = DirEntry::empty();
for i in 0..file_count {
assert_eq!(
disk_inode.read_at(
DIRENT_SZ * i,
&mut dirent_space,
dirent.as_bytes_mut(),
&self.block_device,
),
DIRENT_SZ,
);
let dirent = DirEntry::from_bytes(&dirent_space);
if dirent.name() == name {
return Some(dirent.inode_number() as u32);
}
@ -144,7 +142,7 @@ impl Inode {
let dirent = DirEntry::new(name, new_inode_id);
root_inode.write_at(
file_count * DIRENT_SZ,
dirent.into_bytes(),
dirent.as_bytes(),
&self.block_device,
);
});
@ -164,16 +162,16 @@ impl Inode {
let file_count = (disk_inode.size as usize) / DIRENT_SZ;
let mut v: Vec<String> = Vec::new();
for i in 0..file_count {
let mut dirent_bytes: DirentBytes = Default::default();
let mut dirent = DirEntry::empty();
assert_eq!(
disk_inode.read_at(
i * DIRENT_SZ,
&mut dirent_bytes,
dirent.as_bytes_mut(),
&self.block_device,
),
DIRENT_SZ,
);
v.push(String::from(DirEntry::from_bytes(&dirent_bytes).name()));
v.push(String::from(dirent.name()));
}
v
})

Loading…
Cancel
Save