Repository navigation
Implement FileReader/FileWriter with position tracking - #151
Conversation
- Remove position tracking from File struct (now stateless) - All File read/write methods now require explicit offset parameter - Add FileReader and FileWriter types that track position internally - FileReader/FileWriter implement std.Io.Reader/Writer interfaces - Remove unused StreamReader/StreamWriter generic types - Update all tests to use positioned File API - Rename File.initFd() to File.fromFd() for consistency
|
Warning Rate limit exceeded@lalinsky has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 13 minutes and 43 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (3)
WalkthroughReplaced per-file cursor I/O with explicit offset-based file operations, added Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
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: 0
🧹 Nitpick comments (2)
src/fs/file.zig (2)
22-22: Consider usingu64for offset type instead ofusize.On 32-bit systems,
usizeis 32 bits, which limits file offsets to ~4GB. If you want to support large files on 32-bit platforms,u64would be the safer choice. Most POSIX APIs useoff_twhich is typically 64-bit on modern systems.If 32-bit large file support isn't a concern, this is fine as-is.
Also applies to: 37-37, 54-54, 76-76
266-269: Simplify redundant error handling.Both error branches return the same error. This can be condensed:
- const n = w.file.writeVec(w.runtime, vecs[0..len], w.position) catch |err| { - if (err == error.Canceled) return error.WriteFailed; - return error.WriteFailed; - }; + const n = w.file.writeVec(w.runtime, vecs[0..len], w.position) catch return error.WriteFailed;
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/fs.zig(1 hunks)src/fs/dir.zig(2 hunks)src/fs/file.zig(11 hunks)src/stream.zig(0 hunks)
💤 Files with no reviewable changes (1)
- src/stream.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 (8)
src/fs/dir.zig (1)
28-28: LGTM!Constructor rename from
initFdtofromFdis applied consistently in bothopenFileandcreateFile. The new naming follows a common pattern wherefrom*indicates construction from an existing resource.Also applies to: 43-43
src/fs.zig (1)
29-29: LGTM!Test correctly updated to use explicit offset parameters. Using
0for both write and read makes sense here since you're writing to a fresh file and then reading from the beginning.Also applies to: 35-35
src/fs/file.zig (6)
111-132: LGTM!FileReader cleanly wraps a stateless File with position tracking. The vtable setup is correct and the default position of 0 makes sense for new readers.
134-190: LGTM!The stream, discard, and readVec implementations correctly handle position tracking and integrate with std.Io.Reader's buffering. The max_vecs = 17 in readVec accounts for the extra buffer slice needed by writableVector.
242-261: Verify multi-char splat behavior is intentional.When
splat > 1andpattern.len > 1, this only writes the pattern once rather than repeating itsplattimes. For single-char patterns, you correctly writesplatcopies via memset. But for "ab" with splat=3, you'd get "ab" instead of "ababab".If this is intentional (perhaps std.Io.Writer handles multi-char splat differently), ignore this. Otherwise, you might need a loop or buffer pre-fill for the multi-char case.
275-297: LGTM!The flush implementation correctly handles partial writes by shifting remaining data forward and retrying. The zero-byte write check at line 286 prevents infinite loops if the underlying write can't make progress.
344-378: Nice test coverage for positional I/O.The positional read/write test does a good job validating the new offset-based API: writes at non-contiguous offsets (0 and 10), reads them back, and even checks the gap region. This is exactly the kind of test that catches offset handling bugs.
406-453: LGTM!Test correctly demonstrates the new FileWriter/FileReader API. The round-trip test with writeSplatAll and readSliceShort validates that the std.Io interface integration works end-to-end.
- FileReader and FileWriter now store File by value instead of pointer - Added File.reader() and File.writer() convenience methods - Updated test to use the convenience methods
- File.read/write/readVec/writeVec now take u64 offset parameter - FileReader and FileWriter position field is now u64 - This matches standard file offset semantics and supports large files
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (3)
src/fs/file.zig (3)
118-202: FileReader implementation correctly tracks position and implements std.Io.Reader interface.The vtable-based interface implementation follows Zig patterns, position tracking is consistent, and error handling appropriately distinguishes
Cancelederrors.One minor note: The pattern
var file = r.file(lines 147, 165, 189) creates a mutable copy to work around const restrictions. While this works fine sinceFileis small, it's a bit indirect.
226-285: FileWriter.drain implements vectored writes correctly.The function properly assembles buffered and new data into a vector, handles splat patterns efficiently, and tracks position. The logic is dense but correct.
The error handling at lines 279-280 can be simplified since both paths return
WriteFailed:- const n = file.writeVec(w.runtime, vecs[0..len], w.position) catch |err| { - if (err == error.Canceled) return error.WriteFailed; - return error.WriteFailed; - }; + const n = file.writeVec(w.runtime, vecs[0..len], w.position) catch return error.WriteFailed;
287-310: FileWriter.flush handles partial writes correctly.The function properly loops until the buffer is drained and handles partial writes by shifting remaining data. The zero-write check (line 299) prevents infinite loops.
Similar to
drain, the error handling at lines 294-296 can be simplified:- const n = file.writeVec(w.runtime, &slices, w.position) catch |err| { - if (err == error.Canceled) return error.WriteFailed; - return error.WriteFailed; - }; + const n = file.writeVec(w.runtime, &slices, w.position) catch return error.WriteFailed;
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/fs/file.zig(9 hunks)
⏰ 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 (7)
src/fs/file.zig (7)
18-20: Clean constructor following Zig conventions.The rename from
initFdtofromFdaligns with standard Zig patterns for constructors that wrap existing resources.
22-35: Stateless read implementation looks correct.The explicit offset parameter properly eliminates internal position tracking, and the aio operation is correctly configured.
37-50: Stateless write implementation matches read pattern.Correctly uses explicit offset throughout.
54-72: Vectored read correctly adapted to offset-based API.The error handling properly converts OS errors to std.Io.Reader-compatible errors and correctly treats zero-byte reads as EOF.
76-89: Vectored write correctly adapted to offset-based API.The error mapping to
WriteFailedis appropriate given thatstd.Io.Writer.Errorprovides limited error granularity.
109-116: Factory methods follow expected pattern.Taking
Fileby value is appropriate since it's a lightweight wrapper around a file descriptor handle.
313-466: Tests properly validate the refactored API.The test suite covers:
- Basic read/write with explicit offsets
- Positional I/O at multiple offsets
- Close semantics
- FileReader/FileWriter interface methods
All tests correctly use the new offset-based signatures and demonstrate both stateless positional operations and sequential operations via FileReader/FileWriter.
- Add File.readBuf() and File.writeBuf() for direct iovec I/O - Use platform-specific writableVectorPosix/Wsa in FileReader.readVec - Use iovec directly in FileWriter drain/flush instead of slice copies - Optimize FileReader.discard to seek forward and verify with 2-byte read - Add logicalPos() methods to FileReader and FileWriter - Simplify FileReader.stream and FileWriter.flush to use single-buffer methods
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
src/fs/file.zig (2)
244-268: Optionally allow seeding reader/writer from a non‑zero starting offsetBoth
FileReaderandFileWriterembedposition: u64 = 0andinitnever takes an initial offset. For append‑style or partial reads (e.g. resuming at a checkpoint), having aninitAt(file, runtime, buffer, start_pos)variant (or an optionalstart_posargument) would make the wrappers more generally useful without forcing callers to fake it with manual offset math.
270-332: Defensive check fordata.len == 0inFileWriter.drain
drainassumesdata.len > 0(it slicesdata[0 .. data.len - 1]and indexesdata[data.len - 1]). That matches howstd.Io.Writercurrently drives the vtable, but an explicit guard or assert would make this safer against future misuse:fn drain(io_writer: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize { - const w: *FileWriter = @fieldParentPtr("interface", io_writer); + const w: *FileWriter = @fieldParentPtr("interface", io_writer); + std.debug.assert(data.len > 0);Cheap in debug builds and documents the expectation clearly.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/fs/file.zig(8 hunks)
⏰ 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 (1)
src/fs/file.zig (1)
18-23: StatelessFileAPI and offset-using tests look coherentThe switch to explicit
offseton allFileread/write variants (read,write,readVec,writeVec,readBuf,writeBuf) plus the trivialfromFdconstructor andreader/writerhelpers is consistent and keeps the async flow simple. The tests exercise the basic and positional cases, as well as the reader/writer interfaces, and match the new calling convention cleanly.Also applies to: 25-115, 117-141, 358-436, 438-462
writableVectorWsa needs space for both user data and the reader's internal buffer, so max_vecs must be at least 2 on Windows (1 + 1 for internal buffer).
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
src/fs/file.zig (1)
189-209: Fix underflow and position corruption without reading discard data.Two bugs here that can be fixed with minimal overhead:
Underflow: If
to_discardis 0 (orpositionis 0),r.position - 1wraps tou64::MAX. Add an early return.EOF position corruption: When discarding past EOF,
positionadvances to (say) 110 even though the file is only 100 bytes. The error is returned, butpositionis left corrupted. If the caller catchesEndOfStreamand continues using theFileReader,logicalPos()reports the wrong value. Roll backpositionwhen verification fails.Since you want to avoid reading the discard data for performance, here's a fix that only adds bounds checks:
fn discard(io_reader: *std.Io.Reader, limit: std.Io.Limit) std.Io.Reader.Error!usize { const r: *FileReader = @fieldParentPtr("interface", io_reader); const to_discard = @intFromEnum(limit); + if (to_discard == 0) return 0; // For physical files, we can just seek forward + const old_position = r.position; r.position += to_discard; // Verify we didn't seek past EOF by reading 2 bytes: // - 1 byte at position-1 (last byte we claim to have discarded) // - 1 byte at position (to verify there's more data or we're exactly at EOF) var buf: [2]u8 = undefined; const n = r.file.read(r.runtime, &buf, r.position - 1) catch |err| { r.err = err; + r.position = old_position; // restore position on read error return error.ReadFailed; }; // If we couldn't read even 1 byte, we went past EOF - if (n == 0) return error.EndOfStream; + if (n == 0) { + r.position = old_position; // restore position, caller should not use FileReader after EOF + return error.EndOfStream; + } return to_discard; }This keeps your seek-ahead optimization while ensuring
positionis always valid.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/fs/file.zig(8 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-16T14:33:19.718Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 48
File: src/core/ConcurrentAwaitableList.zig:254-269
Timestamp: 2025-10-16T14:33:19.718Z
Learning: In the zio repository's `src/core/ConcurrentAwaitableList.zig` and `src/core/Awaitable.zig`, the `in_list` field should remain debug-only (conditional compilation with `builtin.mode == .Debug`). Double-removal detection in `ConcurrentAwaitableList.remove()` uses pointer-based checks (comparing `prev`/`next` against `head`/`tail`) rather than relying on a regular `in_list` field.
Applied to files:
src/fs/file.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 (9)
src/fs/file.zig (9)
21-53: LGTM: Clean stateless API with explicit offsets.The refactoring to require explicit offsets makes the API more predictable and safer for concurrent access. The
fromFd()rename aligns with Zig conventions.
55-85: LGTM: Vectored I/O implementation.The 16-iovec storage is a practical choice that covers most use cases without heap allocation. Both
readVec()andwriteVec()correctly delegate to the underlying aio operations with explicit offsets.
87-133: LGTM: Direct buffer access and close implementation.The
readBuf()/writeBuf()methods provide necessary low-level access for advanced use cases. Theclose()method correctly uses the shield pattern to ensure completion and ignores errors following standard Zig conventions.
145-171: LGTM: FileReader structure and position tracking.The
logicalPos()calculation correctly accounts for internal buffering state. The interface vtable setup properly exposes the required std.Io.Reader methods.
173-187: LGTM: Stream implementation.The
stream()method correctly implements the std.Io.Reader streaming interface, properly advancing both file position and Writer state.
211-240: LGTM: Vectored read implementation.The platform-specific vector limits (1 for Windows, 16 for POSIX) and buffer overflow handling are correct. The logic properly accounts for reads that fill both the caller's buffers and the internal buffer.
244-268: LGTM: FileWriter structure.The
logicalPos()calculation correctly accounts for buffered data. The structure mirrorsFileReaderfor consistency.
334-355: LGTM: Flush implementation handles partial writes correctly.The loop properly handles partial writes by sliding remaining buffered data forward. The zero-progress check prevents hanging.
358-511: LGTM: Comprehensive test coverage.Tests properly exercise the new explicit-offset API, positional I/O, and the FileReader/FileWriter interfaces. The test cleanup with
deleteFile()is appropriate.
Return early if to_discard == 0 to avoid underflow when computing position - 1 for the verification read.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
src/fs/file.zig (1)
318-321: Multi-byte splat still only writes pattern once.When
splat > 1andpattern.len > 1, the code adds the pattern to the iovec array only once. CallingwriteSplatAll(&[_][]const u8{"ab"}, 3)should write "ababab" (6 bytes) but will only write "ab" (2 bytes).The previous review comment on this issue remains unresolved. You need to loop
splattimes and add the pattern slice to the iovec array repeatedly (respecting the array size limit).Apply this fix:
- else => { - iovec_storage[len] = aio.system.iovecConstFromSlice(pattern); - len += 1; - }, + else => { + var i: usize = 0; + while (i < splat and len < iovec_storage.len) : (i += 1) { + iovec_storage[len] = aio.system.iovecConstFromSlice(pattern); + len += 1; + } + },
🧹 Nitpick comments (1)
src/fs/file.zig (1)
485-488: Add test coverage for multi-byte splat patterns.The current test only exercises single-character patterns (
"x"). Add a test case for multi-byte patterns like&[_][]const u8{"ab"}withsplat = 3to verify "ababab" is written correctly.// After line 488, add: // Test writeSplatAll with multi-byte pattern var multi_data = [_][]const u8{"xy"}; try writer.interface.writeSplatAll(&multi_data, 3); try writer.interface.flush();
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/fs/file.zig(8 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-16T14:33:19.718Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 48
File: src/core/ConcurrentAwaitableList.zig:254-269
Timestamp: 2025-10-16T14:33:19.718Z
Learning: In the zio repository's `src/core/ConcurrentAwaitableList.zig` and `src/core/Awaitable.zig`, the `in_list` field should remain debug-only (conditional compilation with `builtin.mode == .Debug`). Double-removal detection in `ConcurrentAwaitableList.remove()` uses pointer-based checks (comparing `prev`/`next` against `head`/`tail`) rather than relying on a regular `in_list` field.
Applied to files:
src/fs/file.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 (2)
src/fs/file.zig (2)
15-142: Stateless File API looks solid.The refactoring to explicit offsets is clean. All read/write operations correctly take an
offsetparameter, and the struct no longer tracks internal position. ThefromFdrename aligns with Zig conventions, and the newreadBuf/writeBufmethods provide direct iovec access.
189-212: Discard implementation addresses underflow concern.The zero check at line 194 prevents the underflow issue raised in the previous review. The seek-and-verify approach avoids reading all discarded data while ensuring the position stays within bounds.
FileWriter.drain was incorrectly handling multi-byte patterns, writing them only once instead of repeating splat times. Extracted the correct fillBuf logic from net.zig into io.zig as a shared utility, fixing the bug and eliminating code duplication between FileWriter and Stream.Writer.
Summary
This PR refactors the File API to be stateless and introduces FileReader/FileWriter types that track position and implement std.Io.Reader/Writer interfaces.
Changes
File API (Breaking Changes)
offsetparameter:read(rt, buffer, offset)write(rt, data, offset)readVec(rt, slices, offset)writeVec(rt, slices, offset)initFd()tofromFd()for consistency with Zig naming conventionsseek(),pread(),pwrite()methods - all operations are now positionalNew Types
*Filewith position tracking, implementsstd.Io.Readerinterface*Filewith position tracking, implementsstd.Io.WriterinterfaceBoth provide familiar std.Io APIs like
writeAll(),readSliceShort(),flush(), etc.Cleanup
src/stream.zig- generic StreamReader/StreamWriter no longer neededUsage
Testing
All 157 tests pass ✅