Repository navigation
Add Duration type and simplify sleep - #201
Conversation
📝 WalkthroughWalkthroughThis PR introduces a new Duration type to replace raw u64 nanosecond/millisecond timeout parameters across the runtime and synchronization primitives. Changes include a comprehensive Duration implementation with constructors, conversions, formatting, and parsing, plus updates to sleep and timeout APIs throughout the codebase. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Fix all issues with AI agents
In `@src/common.zig`:
- Around line 23-41: The Duration constructors (fromNanoseconds,
fromMicroseconds, fromMilliseconds, fromSeconds, fromMinutes) currently multiply
inputs by ns constants and can overflow for large u64 values; change them to
detect and handle overflow by using a saturating multiply or mulWithOverflow
check from std.math and clamp the result to Duration.max (or return
Duration.max) instead of letting the value wrap, ensuring each constructor
returns a capped .{ .ns = Duration.max } on overflow.
In `@src/io.zig`:
- Around line 178-184: Remove the explicit call to timer.clear(rt) inside the
executor.yield error handler and rely on the existing defer at the top of the
function (the defer that calls timer.clear(rt)) to perform timer cleanup; keep
the classification via rt.checkTimeout(&timer, err), call cancelIo(rt,
completion) as before, and return the classified_err, so all timer cleanup is
centralized in the defer rather than duplicated in the error path.
🧹 Nitpick comments (1)
src/sync/Futex.zig (1)
114-114: Nit: Inconsistent initialization style.The implementation uses
var timer: Timeout = .{};while tests usevar timeout: Timeout = .init;. Both work, but picking one style across the file would be cleaner. Not a blocker.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (16)
examples/producer_consumer.zigexamples/signal_demo.zigexamples/sleep.zigsrc/common.zigsrc/io.zigsrc/runtime.zigsrc/runtime/group.zigsrc/runtime/timeout.zigsrc/select.zigsrc/signal.zigsrc/sync/Condition.zigsrc/sync/Futex.zigsrc/sync/Notify.zigsrc/sync/ResetEvent.zigsrc/sync/Semaphore.zigsrc/zio.zig
🧰 Additional context used
🧠 Learnings (9)
📚 Learning: 2026-01-07T13:15:48.677Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 179
File: src/os/windows.zig:424-424
Timestamp: 2026-01-07T13:15:48.677Z
Learning: In `src/os/windows.zig`, WSABUF must be re-exported from `std.os.windows.ws2_32.WSABUF` rather than defined locally because it needs to satisfy `std.Io.Reader` compatibility requirements.
Applied to files:
src/zio.zig
📚 Learning: 2025-10-10T05:59:17.087Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 41
File: src/udp.zig:79-82
Timestamp: 2025-10-10T05:59:17.087Z
Learning: In UDP socket operations (src/udp.zig), error.Canceled from result_data.result represents OS/IO-level cancellation (e.g., io_uring), not user-requested cancellation. User cancellation is handled by waitForXevCompletion() via try. OS-level error.Canceled should be mapped to error.Unexpected as it represents an unexpected system event.
Applied to files:
src/zio.zigsrc/io.zigsrc/common.zig
📚 Learning: 2026-01-10T13:55:00.163Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/runtime/blocking_task.zig:117-146
Timestamp: 2026-01-10T13:55:00.163Z
Learning: In Zig files, do not reference libxev for async I/O. The project uses a custom event loop implementation under src/ev/ and a callback-based async I/O loop similar to libuv/libxev. Reviewers should ensure code relies on the src/ev event loop and that there are no libxev usage patterns; prefer the central event loop in src/ev/ for all asynchronous operations.
Applied to files:
src/zio.zigsrc/runtime/group.zigexamples/sleep.zigsrc/select.zigsrc/runtime.zigsrc/sync/Condition.zigexamples/producer_consumer.zigsrc/io.zigsrc/runtime/timeout.zigsrc/sync/Futex.zigsrc/sync/Notify.zigexamples/signal_demo.zigsrc/signal.zigsrc/sync/ResetEvent.zigsrc/sync/Semaphore.zigsrc/common.zig
📚 Learning: 2026-01-10T14:08:37.019Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/stdio.zig:117-129
Timestamp: 2026-01-10T14:08:37.019Z
Learning: In Zig files implementing swap-like semantics (e.g., old = swap(new); defer swap(old)), ensure the return value is an opaque restoration token rather than a direct reflection of internal state. Rely on the contract to perform increment/decrement logic internally (e.g., shield_count) and not expose internal state through the token. This makes behavior predictable, supports refactoring, and avoids leaking internal state across calls. Apply this pattern broadly to Zig code that uses a paired-swap or restoration-token mechanism.
Applied to files:
src/zio.zigsrc/runtime/group.zigexamples/sleep.zigsrc/select.zigsrc/runtime.zigsrc/sync/Condition.zigexamples/producer_consumer.zigsrc/io.zigsrc/runtime/timeout.zigsrc/sync/Futex.zigsrc/sync/Notify.zigexamples/signal_demo.zigsrc/signal.zigsrc/sync/ResetEvent.zigsrc/sync/Semaphore.zigsrc/common.zig
📚 Learning: 2025-11-04T10:29:56.949Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 118
File: src/core/task.zig:33-115
Timestamp: 2025-11-04T10:29:56.949Z
Learning: In zio's task implementation (src/core/task.zig), the Closure struct intentionally caps result_len and context_len at 4096 bytes (using u12 fields) and alignment at 16 bytes (using u4 padding fields). This is a deliberate design decision to avoid bloating task structures. Users needing larger result or context storage should heap-allocate and pass pointers instead. These limits are more generous than std lib's fixed storage (64 bytes for results, 1024 bytes for args).
<!-- [add_learning]
The task storage limits in zio (4 KiB for result/context, 16-byte alignment) are intentional design constraints to prevent task bloat, not correctness issues. The maintainer's position is that larger data should be heap-allocated.
Applied to files:
src/select.zigsrc/sync/Condition.zigsrc/io.zigsrc/runtime/timeout.zigsrc/sync/Futex.zigsrc/sync/ResetEvent.zig
📚 Learning: 2025-10-23T16:17:53.575Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 70
File: src/select.zig:145-153
Timestamp: 2025-10-23T16:17:53.575Z
Learning: In src/select.zig, the select() function is designed to accept futures either as copyable wrappers (e.g., JoinHandle(T)) by value, or as pointers (e.g., &reset_event) for value-owned types. This is intentional, and users are expected to pass the appropriate form based on the future type.
Applied to files:
src/runtime.zig
📚 Learning: 2025-10-03T11:09:46.846Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 18
File: src/net.zig:18-25
Timestamp: 2025-10-03T11:09:46.846Z
Learning: In zio's `Runtime.BlockingTask`, calling `deinit()` on a blocking task only frees the task wrapper (TaskData) itself, not the result returned by the blocking function. The result remains valid and owned by the caller, who is responsible for its cleanup. This is the intended design for async blocking tasks.
Applied to files:
src/runtime.zig
📚 Learning: 2026-01-08T21:08:29.443Z
Learnt from: CR
Repo: lalinsky/zio PR: 0
File: CLAUDE.md:0-0
Timestamp: 2026-01-08T21:08:29.443Z
Learning: Use `zig env` to get the path to the Zig standard library when needed for reference checks
Applied to files:
src/runtime/timeout.zig
📚 Learning: 2025-10-15T19:38:44.659Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 47
File: src/sync/Mutex.zig:237-237
Timestamp: 2025-10-15T19:38:44.659Z
Learning: In the `unlock` method of `src/sync/Mutex.zig`, the `runtime` parameter is intentionally retained (marked with `_ = runtime;`) for API consistency and future-proofing, even though it's not currently used in the implementation.
Applied to files:
src/sync/Futex.zigsrc/signal.zigsrc/sync/ResetEvent.zigsrc/sync/Semaphore.zig
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: test (windows-latest)
🔇 Additional comments (58)
src/common.zig (5)
16-21: Solid foundation for the Duration type.Using
u64nanoseconds gives ~584 years of range which is plenty. Themaxsentinel usingmaxInt(u64)is a good choice for "wait forever" semantics.
43-61: Accessors look correct.Using
@divTruncfor the conversions is the right call - matches Go's integer division semantics for duration conversions.
70-168: Format helpers are well-structured.Filling the buffer from the end and returning the start index is a clean approach. The trailing zero removal in
fmtFracand the separate handling of sub-second vs multi-unit durations matches Go's time.Duration formatting behavior.
242-304: Tests provide good coverage of the happy path.The round-trip cases for format/parse are solid. Consider adding a test for
Duration.maxformatting and perhaps an overflow edge case if you add overflow handling.
63-68: The code is correct.std.Io.Writer(with capital I) is the actual type in Zig 0.15.2's standard library. The README explicitly states this project targets Zig 0.15.2 and references the official documentation forstd.Io.Readerandstd.Io.Writer. This signature is used consistently throughout the codebase in multiple files and compiles without issues.Likely an incorrect or invalid review comment.
src/select.zig (1)
522-527: Sleep calls correctly updated to Duration API.All test sleep calls consistently use
.fromMilliseconds(N)- the anonymous struct literal syntax is clean and the timing values are preserved.src/runtime/timeout.zig (2)
37-58: Duration.max bypass and rounding logic look correct.The early return for
Duration.maxavoids setting a timer when waiting forever - good optimization.The rounding formula
(timeout.ns +| ns_per_ms / 2) / ns_per_msrounds to nearest millisecond with saturating add to prevent overflow. One thing to note: sub-millisecond timeouts (< 500μs) will round to 0ms, causing immediate timeout. If that's not desired, you could use@max(1, ...)to ensure at least 1ms, but this might be intentional behavior.
95-270: Test updates are consistent with the new Duration API.All
timeout.set()andrt.sleep()calls now use.fromMilliseconds(N)with the same numeric values as before. The tests exercise the same timing scenarios.examples/producer_consumer.zig (2)
21-21: Producer sleep updated correctly.
39-39: Consumer sleep updated correctly.examples/signal_demo.zig (1)
26-26: Sleep call updated to Duration API.src/zio.zig (1)
19-19: Clean addition to the public API.Re-exporting
DurationalongsideCancelableandTimeoutablekeeps the public surface consistent. Users can now access the type viazio.Duration.examples/sleep.zig (1)
10-10: Good migration to the Duration API.
.fromSeconds(1)is clearer than the old raw millisecond value. The intent is immediately obvious.src/runtime/group.zig (1)
329-336: Test code correctly migrated to Duration.Both sleep calls preserve the original timing behavior. The explicit
.fromMilliseconds()constructor makes the time units unambiguous.src/signal.zig (4)
10-10: Import added for Duration type.Required for the new timeout signature.
319-341: Timeout handling refactored to use Duration.The implementation follows the standard pattern:
- Stack-allocated
Timeoutwithinitdefer timer.clear(rt)ensures cleanuptimer.set(rt, timeout)configures the durationrt.checkTimeout(&timer, err)classifies cancellation vs timeout errorsThis is consistent with the timeout pattern used elsewhere in the codebase.
350-350: Error classification uses the timer reference.
rt.checkTimeout(&timer, err)correctly passes the timer to determine whether the cancellation was due to timeout expiry or user cancellation.
414-414: Test code migrated to Duration constructors.All sleep and timedWait calls in tests now use
.fromMilliseconds()or.fromSeconds()as appropriate. The test timing semantics are preserved.Also applies to: 460-460, 485-485, 525-530, 577-577, 608-608, 637-637, 665-665
src/io.zig (2)
14-14: Import added for Duration type.Required for the updated function signature.
155-162: Function signature and timeout setup updated for Duration.The pattern matches what's used in
src/signal.zigfortimedWait. Clean migration.src/sync/Condition.zig (5)
56-56: LGTM!Import added for the new Duration type. Consistent with the codebase-wide migration to Duration-based timing APIs.
165-165: LGTM on the API change.Signature update from raw nanoseconds to
Durationis cleaner and type-safe. Callers now express intent more clearly with.fromMilliseconds(10)instead of magic numbers.
177-180: Good rename fromtimeouttotimer.Avoids shadowing/confusion with the
timeout: Durationparameter. The init/set/clear pattern is consistent with other sync primitives in this PR.
200-219: LGTM!All references properly updated to use
timerinstead oftimeout. The assertion at line 219 correctly checkstimer.triggeredto ensure the timer didn't fire if we exited the happy path.
323-323: LGTM!Test updated to use Duration literal. Clean and readable.
src/sync/Notify.zig (6)
54-54: LGTM!Duration import added.
151-162: LGTM!The timedWait signature and timer setup follow the same pattern as Condition.zig. The
defer timer.clear(runtime)ensures cleanup on all exit paths.
185-193: LGTM!Error handling and final assertion properly reference
timer. The flow is: on error, check if our timer triggered (return Timeout) or it was user cancellation (propagate Canceled).
366-366: LGTM!Test updated to Duration literal.
392-392: LGTM!Test updated to Duration literal.
424-424: LGTM!Test updated to Duration literal.
src/runtime.zig (10)
14-14: LGTM!Duration import added.
38-38: LGTM!Import for runIo added to support the simplified sleep implementation.
614-617: Nice simplification!Went from manual timeout handling to a clean 3-liner. The Timer takes milliseconds, so
duration.toMilliseconds()is the right conversion.runIohandles the async wait and cancellation.
973-975: LGTM!Runtime.sleep now forwards the Duration directly to the executor. Clean delegation pattern.
1210-1210: LGTM!Test updated to use Duration literal.
1230-1230: LGTM!Test updated to use Duration literal.
1243-1243: LGTM!Test updated to use Duration literal.
1263-1263: LGTM!Test updated to use Duration literal.
1279-1279: LGTM!Test updated to use Duration literal.
1358-1358: LGTM!Test updated to use Duration literal.
src/sync/Semaphore.zig (4)
47-47: LGTM!Duration import added.
115-129: LGTM!Different approach than Condition/Notify/ResetEvent, but makes sense here. Semaphore needs to loop and recalculate remaining time for each
cond.timedWaitcall. Usingstd.time.Timerfor elapsed tracking and computingDuration.fromNanoseconds(timeout_ns - elapsed)for remaining is the right pattern.
201-201: LGTM!Test updated to Duration literal.
227-227: LGTM!Test updated to Duration literal.
src/sync/ResetEvent.zig (7)
52-52: LGTM!Duration import added.
165-165: LGTM!Signature updated to accept Duration. Consistent with other sync primitives.
191-194: LGTM!Timer setup follows the standard pattern: init, defer clear, set with Duration.
203-211: LGTM!Error handling and final assertion properly reference
timer. Same pattern as Condition and Notify.
310-310: LGTM!Test updated to Duration literal.
397-397: LGTM!Test updated to Duration literal.
414-416: LGTM!Tests updated to Duration literals.
src/sync/Futex.zig (6)
35-35: LGTM!Import added for
Durationfromcommon.zig— consistent with existing imports from the same module.
81-86: LGTM!Using
Duration.maxfor the unbounded wait is the right call. Theunreachableforerror.Timeoutis correct — that path can't fire with a maximum duration.
101-152: LGTM!The refactor from raw
u64nanoseconds toDurationis clean:
- Signature change is straightforward
- Timer lifecycle is handled correctly with
defer timer.clear(runtime)checkTimeoutintegration looks proper- The assertion on line 151 correctly validates invariants when yield succeeds
The API now matches the rest of the codebase's Duration-based timeout handling.
232-234: LGTM!Test updated to use the new
Duration.fromMilliseconds(10)syntax. The timeout setup pattern is consistent.
301-303: LGTM!Timeout setup migrated to
Duration— consistent with other tests in this file.
345-347: LGTM!Duration-based timeout setup is consistent across all tests.
✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.
There was a problem hiding this comment.
Actionable comments posted: 1
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (11)
src/io.zigsrc/runtime.zigsrc/runtime/timeout.zigsrc/signal.zigsrc/sync/Condition.zigsrc/sync/Futex.zigsrc/sync/Notify.zigsrc/sync/ResetEvent.zigsrc/sync/Semaphore.zigsrc/time.zigsrc/zio.zig
🚧 Files skipped from review as they are similar to previous changes (3)
- src/io.zig
- src/sync/Futex.zig
- src/sync/Notify.zig
🧰 Additional context used
🧠 Learnings (8)
📚 Learning: 2026-01-10T13:55:00.163Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/runtime/blocking_task.zig:117-146
Timestamp: 2026-01-10T13:55:00.163Z
Learning: In Zig files, do not reference libxev for async I/O. The project uses a custom event loop implementation under src/ev/ and a callback-based async I/O loop similar to libuv/libxev. Reviewers should ensure code relies on the src/ev event loop and that there are no libxev usage patterns; prefer the central event loop in src/ev/ for all asynchronous operations.
Applied to files:
src/time.zigsrc/runtime/timeout.zigsrc/runtime.zigsrc/sync/Condition.zigsrc/sync/Semaphore.zigsrc/signal.zigsrc/sync/ResetEvent.zigsrc/zio.zig
📚 Learning: 2026-01-10T14:08:37.019Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/stdio.zig:117-129
Timestamp: 2026-01-10T14:08:37.019Z
Learning: In Zig files implementing swap-like semantics (e.g., old = swap(new); defer swap(old)), ensure the return value is an opaque restoration token rather than a direct reflection of internal state. Rely on the contract to perform increment/decrement logic internally (e.g., shield_count) and not expose internal state through the token. This makes behavior predictable, supports refactoring, and avoids leaking internal state across calls. Apply this pattern broadly to Zig code that uses a paired-swap or restoration-token mechanism.
Applied to files:
src/time.zigsrc/runtime/timeout.zigsrc/runtime.zigsrc/sync/Condition.zigsrc/sync/Semaphore.zigsrc/signal.zigsrc/sync/ResetEvent.zigsrc/zio.zig
📚 Learning: 2025-11-04T10:29:56.949Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 118
File: src/core/task.zig:33-115
Timestamp: 2025-11-04T10:29:56.949Z
Learning: In zio's task implementation (src/core/task.zig), the Closure struct intentionally caps result_len and context_len at 4096 bytes (using u12 fields) and alignment at 16 bytes (using u4 padding fields). This is a deliberate design decision to avoid bloating task structures. Users needing larger result or context storage should heap-allocate and pass pointers instead. These limits are more generous than std lib's fixed storage (64 bytes for results, 1024 bytes for args).
<!-- [add_learning]
The task storage limits in zio (4 KiB for result/context, 16-byte alignment) are intentional design constraints to prevent task bloat, not correctness issues. The maintainer's position is that larger data should be heap-allocated.
Applied to files:
src/runtime/timeout.zigsrc/sync/Condition.zigsrc/sync/ResetEvent.zig
📚 Learning: 2026-01-08T21:08:29.443Z
Learnt from: CR
Repo: lalinsky/zio PR: 0
File: CLAUDE.md:0-0
Timestamp: 2026-01-08T21:08:29.443Z
Learning: Use `zig env` to get the path to the Zig standard library when needed for reference checks
Applied to files:
src/runtime/timeout.zig
📚 Learning: 2025-10-23T16:17:53.575Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 70
File: src/select.zig:145-153
Timestamp: 2025-10-23T16:17:53.575Z
Learning: In src/select.zig, the select() function is designed to accept futures either as copyable wrappers (e.g., JoinHandle(T)) by value, or as pointers (e.g., &reset_event) for value-owned types. This is intentional, and users are expected to pass the appropriate form based on the future type.
Applied to files:
src/runtime.zig
📚 Learning: 2025-10-03T11:09:46.846Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 18
File: src/net.zig:18-25
Timestamp: 2025-10-03T11:09:46.846Z
Learning: In zio's `Runtime.BlockingTask`, calling `deinit()` on a blocking task only frees the task wrapper (TaskData) itself, not the result returned by the blocking function. The result remains valid and owned by the caller, who is responsible for its cleanup. This is the intended design for async blocking tasks.
Applied to files:
src/runtime.zig
📚 Learning: 2025-10-15T19:38:44.659Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 47
File: src/sync/Mutex.zig:237-237
Timestamp: 2025-10-15T19:38:44.659Z
Learning: In the `unlock` method of `src/sync/Mutex.zig`, the `runtime` parameter is intentionally retained (marked with `_ = runtime;`) for API consistency and future-proofing, even though it's not currently used in the implementation.
Applied to files:
src/sync/Semaphore.zigsrc/signal.zigsrc/sync/ResetEvent.zig
📚 Learning: 2025-10-10T05:59:17.087Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 41
File: src/udp.zig:79-82
Timestamp: 2025-10-10T05:59:17.087Z
Learning: In UDP socket operations (src/udp.zig), error.Canceled from result_data.result represents OS/IO-level cancellation (e.g., io_uring), not user-requested cancellation. User cancellation is handled by waitForXevCompletion() via try. OS-level error.Canceled should be mapped to error.Unexpected as it represents an unexpected system event.
Applied to files:
src/zio.zig
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: test (windows-latest)
🔇 Additional comments (34)
src/zio.zig (1)
20-21: LGTM!Clean re-export of
Durationfromtime.zig, consistent with how other types are exposed in this module.src/signal.zig (4)
10-10: LGTM!Duration import added correctly.
319-341: LGTM!Good rename from
timeouttotimer— avoids shadowing/confusion with thetimeout: Durationparameter. The setup pattern (Timeout.init,defer timer.clear,timer.set) is consistent with other sync primitives in this PR.
348-351: LGTM!
checkTimeoutcorrectly references the renamedtimervariable.
414-414: LGTM!Test correctly uses
.fromMilliseconds(10)for the sleep duration.src/sync/Condition.zig (4)
56-56: LGTM!Duration import added.
165-180: LGTM!Clean migration to Duration-based API. The
timeout→timerrename keeps things unambiguous.
199-219: LGTM!The early
timer.clear(runtime)before reacquiring the mutex is a sensible choice — prevents the timer from firing spuriously while waiting on the lock. The assertion on line 219 correctly validates that if we reach the success path, the timer shouldn't have triggered.
323-323: LGTM!Test correctly uses Duration constructor.
src/runtime.zig (5)
14-14: LGTM!Duration import added.
38-38: LGTM!runIo import added for the simplified sleep implementation.
973-975: LGTM!Runtime.sleep now delegates with the Duration parameter directly.
1210-1210: LGTM!Test correctly uses
.fromMilliseconds(10).
614-617: Clean simplification of the sleep method.Three lines: init the timer, run async I/O, done. The
Duration.toMilliseconds()call works as expected andrunIohandles the event loop integration.src/runtime/timeout.zig (3)
7-7: LGTM!Duration import added.
37-51: Good stuff.The
Duration.maxearly-exit saves a timer allocation for the "wait forever" case. The saturating add for rounding (+|) handles edge cases wheretimeout.nsis nearu64max without overflow.
95-95: LGTM!Test correctly uses
.fromMilliseconds(100).src/sync/ResetEvent.zig (5)
52-52: LGTM!Import of Duration from the new time module aligns with the API migration.
165-165: Clean API change.Switching from
timeout_ns: u64totimeout: Durationmakes call sites more readable and self-documenting.
203-203: Consistent naming update.References to
timerinstead of the oldtimeoutvariable are correct.Also applies to: 211-211
310-310: Test updates are correct.Using
.fromMilliseconds(...)is the right pattern for the new Duration-based API.Also applies to: 397-397, 414-416
191-194: Timer setup is correct.The
Timeout.setAPI confirms it acceptsDurationas the third parameter. The init pattern and defer cleanup are properly structured.src/sync/Semaphore.zig (3)
47-47: Import added correctly.
201-201: Test updates look correct.Switched to
.fromMilliseconds(...)for the Duration-based API.Also applies to: 227-227
115-129: Correct approach for looping with timeout.Semaphore correctly uses
std.time.Timerfor wall-clock tracking and decrements the remaining timeout across multiple condition waits. Thetimer.read()gives elapsed nanoseconds, and the remaining duration is correctly computed astimeout_ns - elapsedand passed tocond.timedWait.src/time.zig (9)
1-8: Good attribution.Proper licensing and source attribution for the Go-derived formatting code.
13-17: Clean struct definition.
zeroandmaxas compile-time constants are useful. Usingu64for nanoseconds gives a range of ~584 years which is plenty.
19-37: Saturating multiplication is the right call.Using
*|prevents overflow panics and clamps toDuration.maxinstead. This matches the test expectations in lines 329-348.
67-125: formatBuf implementation is solid.Building the string from the end of the buffer and returning the start index is an efficient approach - avoids shifting characters or allocations. The branching logic for sub-second vs multi-unit durations is clear.
129-164: Helper functions are clean.
fmtFrachandles trailing zero suppression elegantly.fmtIntis straightforward.
169-245: Parse implementation has thorough overflow protection.The overflow checks at lines 184, 187, 231, and 240 cover:
- Integer part digit accumulation overflow
- Multiplication by unit overflow
- Accumulation across multiple units overflow
The use of
+|=(saturating add) at line 236 for the fractional part is a nice touch - prevents panic on float-to-int edge cases.
276-327: Parse tests are comprehensive.Good coverage of:
- Valid inputs (various units, combinations, fractional parts)
- Error cases (empty, invalid unit, missing unit)
- Overflow edge cases (integer overflow, multiplication overflow, accumulation overflow)
- Max u64 boundary case
329-348: Overflow saturation tests verify the*|behavior.These confirm that constructors clamp to
Duration.maxon overflow rather than panicking.
59-64: No changes needed —std.Io.Writeris correct for modern Zig.Zig's I/O module was refactored in version 0.15+, and the current standard uses
std.Io(capital I), notstd.io. The codebase is consistent throughout with this modern API. The code will compile correctly.
✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.
Summary
sleepimplementation to userunIodirectly instead of manual timeout handlingDurationtype with Go-style formatting and parsingTimeout.setandtimedWaitForIoto useDurationChanges
Durationstruct withfromNanoseconds,fromMicroseconds,fromMilliseconds,fromSeconds,fromMinutesconstructorsDuration.formatfor Go-style output (e.g., "1h23m45.123456789s", "1.5ms")Duration.parsefor parsing duration stringsDuration.zeroandDuration.maxconstantsExecutor.sleepfrom 17 lines to 3 linesTest plan