1
\$\begingroup\$

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, returns Ok(Some("steve"))
  • CWD = /home, returns Some(Ok("home"))
  • CWD = /, returns None
Src

Playground Link

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?

asked Oct 25, 2022 at 10:11
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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.

answered Oct 25, 2022 at 16:01
\$\endgroup\$
3
  • \$\begingroup\$ Yes, since most functions within Composer::next() return io::Result<T>, changing the signature to Result<Option<OsString>> plus the use of ? would be neat. Would you like to elaborate on Instead, you should at least use increasing chains of ".." to ask for parent directories? Thanks! \$\endgroup\$ Commented Oct 25, 2022 at 23:57
  • \$\begingroup\$ @SteveLau, instead of changing the directory call metadata("."), metadata(".."), metadata("../.."), metadata("../../..") etc. \$\endgroup\$ Commented Oct 26, 2022 at 0:22
  • \$\begingroup\$ Thanks for your help:) \$\endgroup\$ Commented Oct 26, 2022 at 1:33

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.