I am trying to implement a getcwd(3)
(or env::current_dir()
in Rust std).
In the implementation, I use a Composer
(an iterator) to yield (call next()
on Composer
) each path entry:
- CWD =
/home/steve
, returnsOk(Some("steve"))
- CWD =
/home
, returnsSome(Ok("home"))
- CWD =
/
, returnsNone
Src
use std::{
collections::VecDeque,
env::set_current_dir,
ffi::OsString,
fs::{metadata, read_dir, File},
io::Result,
os::{linux::fs::MetadataExt, unix::io::AsRawFd},
path::PathBuf,
};
use libc::{fchdir, PATH_MAX};
/// A CWD composer, returns the next path entry
///
/// ##### Example
/// * `/home/steve` -> `Some(Ok("steve"))`
/// * `/home` -> `Some(Ok("home"))`
/// * `/` -> `None`
struct Composer;
impl Composer {
fn new() -> Self {
Composer
}
}
impl Iterator for Composer {
type Item = Result<OsString>;
fn next(&mut self) -> Option<Self::Item> {
let cur_dir_metadata = match metadata(".") {
Ok(m) => m,
Err(e) => return Some(Err(e)),
};
let parent_metadata = match metadata("..") {
Ok(m) => m,
Err(e) => return Some(Err(e)),
};
// reaches root
if cur_dir_metadata.st_dev() == parent_metadata.st_dev()
&& cur_dir_metadata.st_ino() == parent_metadata.st_ino()
{
return None;
}
// cd to parent dir
if let Err(e) = set_current_dir("..") {
return Some(Err(e));
}
let dir = match read_dir(".") {
Ok(dir) => dir,
Err(e) => return Some(Err(e)),
};
for res_entry in dir {
let entry = match res_entry {
Ok(entry) => entry,
Err(e) => return Some(Err(e)),
};
let entry_metadata = match entry.metadata() {
Ok(m) => m,
Err(e) => return Some(Err(e)),
};
if entry_metadata.st_dev() == cur_dir_metadata.st_dev()
&& entry_metadata.st_ino() == cur_dir_metadata.st_ino()
{
return Some(Ok(entry.file_name()));
}
}
unreachable!("This is unreachable unless there is something wrong with your file system");
}
}
pub fn getcwd() -> Result<PathBuf> {
let cwd = File::open(".")?;
let comp = Composer::new();
let mut entries = VecDeque::new();
for item in comp {
entries.push_front(item?);
}
let mut res = OsString::with_capacity(PATH_MAX as usize);
entries.iter().for_each(|entry| {
res.push("/");
res.push(entry);
});
res.shrink_to_fit();
unsafe { fchdir(cwd.as_raw_fd()) };
Ok(PathBuf::from(res))
}
Problem
I am not satisfied with the implementation of Composer::next()
. Within this method, I have used a lot of functions whose return value is std::io::Result<T>
, if the return value is an Err(e)
, I have to match against it and return Some(Err(e))
. I kind of think this is not idiomatic and Rusty. Can I avoid this or change it to a more natural way?
1 Answer 1
For your primary question, my strategy would be something like:
impl Composer {
fn next_component(&self) -> Result<Option<OsStr>> {
// do your main logic here, since it returns a result, you
// use ? and simplify the code nicely.
}
}
impl Iterator for Composer {
fn next(&mut self) -> Self::Item {
self.next_component().invert()
}
}
Manipulating the current working directory as part of the algorithm is asking for trouble. Instead, you should at least use increasing chains of ".." to ask for parent directories. Honestly, though, getting the current working directory is so low level that its hard to meaningfully reimplement it yourself.
-
\$\begingroup\$ Yes, since most functions within
Composer::next()
returnio::Result<T>
, changing the signature toResult<Option<OsString>>
plus the use of?
would be neat. Would you like to elaborate onInstead, you should at least use increasing chains of ".." to ask for parent directories
? Thanks! \$\endgroup\$Steve Lau– Steve Lau2022年10月25日 23:57:56 +00:00Commented Oct 25, 2022 at 23:57 -
\$\begingroup\$ @SteveLau, instead of changing the directory call
metadata("."), metadata(".."), metadata("../.."), metadata("../../..")
etc. \$\endgroup\$Winston Ewert– Winston Ewert2022年10月26日 00:22:06 +00:00Commented Oct 26, 2022 at 0:22 -
\$\begingroup\$ Thanks for your help:) \$\endgroup\$Steve Lau– Steve Lau2022年10月26日 01:33:38 +00:00Commented Oct 26, 2022 at 1:33