Skip to main content

file_system/fundamentals/
entry.rs

1//! Directory entry representation for file system operations.
2
3//!
4//! This module provides the [`Entry`] structure which represents individual
5//! entries within directories, such as files, subdirectories, and other file system objects.
6
7use alloc::string::String;
8
9use crate::{Kind, Path, PathOwned, Time};
10
11use super::{Inode, Size};
12
13/// Represents a single entry within a directory.
14///
15/// A directory entry contains metadata about a file system object including its
16/// inode number, name, type, size, and last modification time. This structure is
17/// used when reading directory contents to provide information about each item
18/// within the directory.
19#[derive(Clone, Debug, PartialEq, Eq)]
20pub struct Entry {
21    /// The inode number identifying this file system object
22    pub inode: Inode,
23    /// The name of this directory entry
24    pub name: String,
25    /// The type of file system object (file, directory, etc.)
26    pub kind: Kind,
27    /// The size of the file system object in bytes
28    pub size: Size,
29    /// The last modification time, in UTC seconds since the Unix epoch.
30    ///
31    /// `0` means unknown: the time was never set (no UTC clock was available)
32    /// or the object was created without Xila attributes.
33    pub modification: Time,
34}
35
36impl Entry {
37    /// Create a new directory entry with the specified metadata.
38    ///
39    /// # Arguments
40    ///
41    /// * `inode` - Unique inode number for this file system object
42    /// * `name` - Name of the file or directory
43    /// * `type` - Type of the file system object
44    /// * `size` - Size in bytes (for files) or entry count (for directories)
45    /// * `modification` - Last modification time of the file system object
46    ///
47    /// # Examples
48    ///
49    /// ```rust
50    /// # extern crate alloc;
51    /// use file_system::{Entry, Inode, Kind, Size, Time};
52    /// use alloc::string::String;
53    ///
54    /// let entry = Entry::new(
55    ///     123,
56    ///     String::from("example.txt"),
57    ///     Kind::File,
58    ///     2048,
59    ///     Time::new(1_700_000_000),
60    /// );
61    /// ```
62    pub fn new(inode: Inode, name: String, r#type: Kind, size: Size, modification: Time) -> Self {
63        Self {
64            inode,
65            name,
66            kind: r#type,
67            size,
68            modification,
69        }
70    }
71
72    pub fn join_path(&self, base_path: impl AsRef<Path>) -> Option<PathOwned> {
73        base_path.as_ref().join(Path::from_str(&self.name))
74    }
75}
76
77impl AsMut<[u8]> for Entry {
78    fn as_mut(&mut self) -> &mut [u8] {
79        unsafe {
80            core::slice::from_raw_parts_mut(
81                self as *mut Entry as *mut u8,
82                core::mem::size_of::<Entry>(),
83            )
84        }
85    }
86}
87
88impl TryFrom<&mut [u8]> for &mut Entry {
89    type Error = ();
90
91    fn try_from(value: &mut [u8]) -> Result<Self, Self::Error> {
92        if value.len() != core::mem::size_of::<Entry>() {
93            return Err(());
94        }
95        if !(value.as_ptr() as usize).is_multiple_of(core::mem::align_of::<Entry>()) {
96            return Err(());
97        }
98
99        #[allow(clippy::transmute_ptr_to_ref)]
100        Ok(unsafe { core::mem::transmute::<*mut u8, &mut Entry>(value.as_mut_ptr()) })
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107    use alloc::string::String;
108
109    #[test]
110    fn test_entry_as_mut_slice() {
111        let mut entry = Entry::new(42, String::from("test"), Kind::File, 100, Time::new(1234));
112        assert_eq!(entry.modification, Time::new(1234));
113
114        let slice = entry.as_mut();
115        assert_eq!(slice.len(), core::mem::size_of::<Entry>());
116    }
117
118    #[test]
119    fn test_entry_from_slice_invalid_size() {
120        let mut buffer = [0u8; 10]; // Too small
121        let result = <&mut Entry>::try_from(buffer.as_mut_slice());
122        assert!(result.is_err());
123    }
124
125    #[test]
126    fn test_entry_from_slice_valid() {
127        // Create a properly sized and aligned buffer
128        let mut buffer = alloc::vec![0u8; core::mem::size_of::<Entry>()];
129
130        // Ensure proper alignment by using Vec which should be properly aligned for any type
131        let result = <&mut Entry>::try_from(buffer.as_mut_slice());
132
133        // This might fail due to alignment requirements, which is expected behavior
134        // The important thing is that we're testing the code path
135        let _ = result; // We don't assert success since alignment isn't guaranteed
136    }
137
138    #[test]
139    fn test_entry_size() {
140        #[cfg(target_pointer_width = "32")]
141        assert_eq!(core::mem::size_of::<Entry>(), 40);
142        #[cfg(target_pointer_width = "64")]
143        assert_eq!(core::mem::size_of::<Entry>(), 56);
144    }
145}