Skip to content

Add safe translation for open/read/write/close#277

Merged
nunoplopes merged 6 commits into
Cpp2Rust:masterfrom
lucic71:safe-stdio
Jul 21, 2026
Merged

Add safe translation for open/read/write/close#277
nunoplopes merged 6 commits into
Cpp2Rust:masterfrom
lucic71:safe-stdio

Conversation

@lucic71

@lucic71 lucic71 commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

This PR adds the building blocks of safe file descriptor IO translation. In Rust, C file descriptors (int), are usually translated as OwnedFd/BorroweFd. nix also uses OwnedFd/BorrowedFd inside the IO APIs, for example open is defined as: pub fn open<P: ?Sized + NixPath>(path: &P, oflag: OFlag, mode: Mode, ) -> Result<OwnedFd>

However, we cannot directly translate integers to OwnedFd/BorrowedFd. An integer can be used as both integer and OwnedFd at the same time, which Rust does not allow. For example:

int fd = -1; // plain integer
fd = open(...) // file descriptor semantics
if (fd > 0) // plain integer
  write(fd, ...) // file descriptor semantics

To overcome this limitation, allow integers to be translated as i32, and keep a global FdRegistry which contains mappings of type i32 -> OwnedFd:

pub struct FdRegistry {
    fds: Vec<Option<OwnedFd>>,
}

impl FdRegistry {
  // Creates a new i32 -> OwnedFd entry
  pub fn register(fd: OwnedFd) -> i32

  // Applies function f over the BorrowedFd: f(FdRegistry[fd])
  pub fn with_fd<R>(fd: i32, f: impl FnOnce(BorrowedFd<'_>) -> R) -> R

  // Removes the i32 -> OwnedFd entry
  pub fn close(fd: i32) -> i32
}

This way, integer operations on file descriptors continue to work, for example int fd = -1 or if (fd > 0) and functions that use file descriptor access the OwnedFd/BorrowedFd through the FdRegistry, for example:

let fd: i32 = -1;
fd = FdRegistry::register(nix::fcntl::open(...));
if (fd > 0)
  FdRegistry::with_fd(fd, |bfd: BorrowedFd| nix::unistd::write(bfd, ...))

In the following PRs I will add the remaining safe IO rules.

@nunoplopes
nunoplopes merged commit a30d60b into Cpp2Rust:master Jul 21, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants