Add a Dir::empty() constructor that returns a Dir representing no
directory. Operations on this directory (creating files, subdirectories)
become no-ops, but the data is still stored.
This is useful as a fallback when a directory lookup fails but you still
need a Dir value to pass to APIs like Dir::scope(). For example:
let dir = Dir::lookup(c_str!("parent"), None)
.unwrap_or_else(Dir::empty);
When CONFIG_DEBUG_FS is enabled, returns Dir(None). When disabled,
returns the empty tuple struct Dir().
Signed-off-by: Timur Tabi <[email protected]>
---
rust/kernel/debugfs.rs | 24 ++++++++++++++++++++++++
1 file changed, 24 insertions(+)
diff --git a/rust/kernel/debugfs.rs b/rust/kernel/debugfs.rs
index eee799f64f79..b0cfe22982d6 100644
--- a/rust/kernel/debugfs.rs
+++ b/rust/kernel/debugfs.rs
@@ -110,6 +110,30 @@ pub fn new(name: &CStr) -> Self {
Dir::create(name, None)
}
+ /// Creates an empty [`Dir`] that represents no directory.
+ ///
+ /// Operations on this directory (such as creating files or
subdirectories) will be no-ops.
+ /// This is useful as a fallback when a directory lookup fails but you
still need a [`Dir`]
+ /// value.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use kernel::c_str;
+ /// # use kernel::debugfs::Dir;
+ /// let dir = Dir::lookup(c_str!("maybe_exists"), None)
+ /// .unwrap_or_else(Dir::empty);
+ /// // If lookup failed, file creation becomes a no-op
+ /// ```
+ pub fn empty() -> Self {
+ #[cfg(CONFIG_DEBUG_FS)]
+ {
+ Self(None)
+ }
+ #[cfg(not(CONFIG_DEBUG_FS))]
+ Self()
+ }
+
/// Looks up an existing directory in DebugFS.
///
/// If `parent` is [`None`], the lookup is performed from the root of the
debugfs filesystem.
--
2.52.0