syd 3.42.0

rock-solid application kernel
Documentation
//
// Syd: rock-solid application kernel
// src/retry.rs: Utilities to handle restarting syscalls
//
// Copyright (c) 2025 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0

//! Utilities to handle restarting syscalls

// SAFETY: This module has been liberated from unsafe code!
#![forbid(unsafe_code)]

use nix::errno::Errno;

/// Retries a closure on `EAGAIN` and `EINTR` errors.
///
/// This function will call the provided closure, and if the closure
/// returns `EAGAIN` or `EINTR` error, it will retry the operation until it
/// succeeds or fails with a different error.
pub fn retry_on_intr<F, T>(mut f: F) -> Result<T, Errno>
where
    F: FnMut() -> Result<T, Errno>,
{
    loop {
        match f() {
            Err(Errno::EAGAIN | Errno::EINTR) => continue,
            result => return result,
        }
    }
}

/// Retries a closure on `EINTR` errors.
///
/// This function will call the provided closure, and if the closure
/// returns `EINTR` error, it will retry the operation until it
/// succeeds or fails with a different error.
pub fn retry_on_eintr<F, T>(mut f: F) -> Result<T, Errno>
where
    F: FnMut() -> Result<T, Errno>,
{
    loop {
        match f() {
            Err(Errno::EINTR) => continue,
            result => return result,
        }
    }
}

/// Retries a closure on `EAGAIN` errors.
///
/// This function will call the provided closure, and if the closure
/// returns `EAGAIN` error, it will retry the operation until it
/// succeeds or fails with a different error.
pub fn retry_on_eagain<F, T>(mut f: F) -> Result<T, Errno>
where
    F: FnMut() -> Result<T, Errno>,
{
    loop {
        match f() {
            Err(Errno::EAGAIN) => continue,
            result => return result,
        }
    }
}

/// write! which retries on EINTR and EAGAIN.
#[macro_export]
macro_rules! rwrite {
    ($dst:expr, $($arg:tt)*) => {{
        $crate::retry::retry_on_intr(|| {
            $dst.write_fmt(format_args!($($arg)*))
                .map_err(|err| $crate::err::err2no(&err))
        })
    }};
}

/// writeln! which retries on EINTR and EAGAIN.
#[macro_export]
macro_rules! rwriteln {
    ($dst:expr $(, $($arg:tt)*)?) => {{
        $crate::retry::retry_on_intr(|| {
            let () = $dst
                .write_fmt(format_args!($($($arg)*)?))
                .map_err(|err| $crate::err::err2no(&err))?;
            $dst
                .write_all(b"\n")
                .map_err(|err| $crate::err::err2no(&err))
        })
    }};
}