While loop that always executes at least once (do-while loop)?

I previously discussed the usage implemented with blocks, and @Sze provided a solution based on inline functions that makes fuller use of zls hints:

pub inline fn do(work: void, @"while": bool) bool {
    _ = work;
    return @"while";
}

pub fn readMailboxInTimeout(
    port: *Port,
    io: std.Io,
    station_address: u16,
    recv_timeout: std.Io.Duration,
    mbx_in: HalfConfiguration,
    mailbox_timeout: std.Io.Duration,
) ReadMailboxInTimeoutError!InContent {
    assert(mbx_in.isValid());

    const deadline = (try std.Io.Clock.Timestamp.now(io, .boot)).addDuration(.{ .clock = .boot, .raw = mailbox_timeout });
    while (do({
        if (try readMailboxIn(
            port,
            io,
            station_address,
            recv_timeout,
            mbx_in,
        )) |in_content| {
            return in_content;
        }
    }, (try std.Io.Clock.Timestamp.now(io, .boot)).compare(.lt, deadline))) {}
    return error.MailboxTimeout;
}
4 Likes