Skip to content

Implement FileReader/FileWriter with position tracking - #151

Merged
lalinsky merged 10 commits into
mainfrom
file-reader-writer
Nov 30, 2025
Merged

lalinsky merged 10 commits into
mainfrom
file-reader-writer

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

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)

  • Removed position tracking from File struct - File is now completely stateless
  • All read/write methods now require explicit offset parameter:
    • read(rt, buffer, offset)
    • write(rt, data, offset)
    • readVec(rt, slices, offset)
    • writeVec(rt, slices, offset)
  • Renamed initFd() to fromFd() for consistency with Zig naming conventions
  • Removed seek(), pread(), pwrite() methods - all operations are now positional

New Types

  • FileReader: Wraps *File with position tracking, implements std.Io.Reader interface
  • FileWriter: Wraps *File with position tracking, implements std.Io.Writer interface

Both provide familiar std.Io APIs like writeAll(), readSliceShort(), flush(), etc.

Cleanup

  • Removed src/stream.zig - generic StreamReader/StreamWriter no longer needed
  • Updated all tests to use the new positioned File API

Usage

// Positioned file operations (stateless)
var file = try dir.createFile(rt, "test.txt", .{});
_ = try file.write(rt, "Hello", 0);
_ = try file.write(rt, "World", 6);

// Sequential operations with position tracking
var writer = FileWriter.init(&file, rt, &buffer);
try writer.interface.writeAll("Hello, World!");
try writer.interface.flush();

Testing

All 157 tests pass ✅

- 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
@coderabbitai

coderabbitai Bot commented Nov 30, 2025 •

Copy link
Copy Markdown
Contributor

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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.

📥 Commits

Reviewing files that changed from the base of the PR and between 684edf4 and 01526a2.

📒 Files selected for processing (3)
  • src/fs/file.zig (8 hunks)
  • src/io.zig (1 hunks)
  • src/net.zig (1 hunks)

Walkthrough

Replaced per-file cursor I/O with explicit offset-based file operations, added File.fromFd, introduced concrete FileReader/FileWriter, updated call sites to pass offsets (e.g., 0), switched Dir file wrapping to .fromFd, and removed generic StreamReader/StreamWriter and their tests.

Changes

Cohort / File(s) Summary
File core
src/fs/file.zig
Removed File.position and position-based APIs. Added pub fn fromFd(fd: Handle) File. read/write/readVec/writeVec now accept offset: u64. Added public FileReader and FileWriter types, readBuf/writeBuf and vectored IO surfaces; removed seek, pread/pwrite, and initFd.
Call sites
src/fs.zig
Updated file IO calls to pass explicit offsets: write(rt, data) → write(rt, data, 0) and read(rt, buffer) → read(rt, buffer, 0).
Directory → File
src/fs/dir.zig
Replaced .initFd(fd) with .fromFd(fd) when converting descriptors to File.
Removed stream abstractions & tests
src/stream.zig
Removed generic StreamReader(comptime T) and StreamWriter(comptime T) types, their implementations, mocks, and tests; corresponding public declarations were deleted.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

  • Pay extra attention to:
    • src/fs/file.zig — correctness of offset handling across single and vectored IO, edge cases (EOF, partial transfers).
    • All call sites to ensure offsets are provided consistently and semantics match previous cursor-based behavior.
    • Removal of StreamReader/StreamWriter — check for remaining callers or tests that relied on those generic abstractions.

Possibly related PRs

Poem

A cursor shed, offsets arrive,
Files answer where callers drive.
Descriptors wrapped, old streams adjourn—
Readers, writers take their turn.
Code moves on; small sparks still burn.

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title directly matches the main change: introducing FileReader/FileWriter with position tracking in place of the removed File.position field.
Description check ✅ Passed The description is clearly related to the changeset, detailing the File API refactoring, new FileReader/FileWriter types, and removal of stream.zig.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/fs/file.zig (2)

22-22: Consider using u64 for offset type instead of usize.

On 32-bit systems, usize is 32 bits, which limits file offsets to ~4GB. If you want to support large files on 32-bit platforms, u64 would be the safer choice. Most POSIX APIs use off_t which 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

📥 Commits

Reviewing files that changed from the base of the PR and between cc4d761 and f52cb1a.

📒 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 initFd to fromFd is applied consistently in both openFile and createFile. The new naming follows a common pattern where from* 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 0 for 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 > 1 and pattern.len > 1, this only writes the pattern once rather than repeating it splat times. For single-char patterns, you correctly write splat copies 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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 Canceled errors.

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 since File is 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

📥 Commits

Reviewing files that changed from the base of the PR and between b6bb73b and fd5682c.

📒 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 initFd to fromFd aligns 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 WriteFailed is appropriate given that std.Io.Writer.Error provides limited error granularity.


109-116: Factory methods follow expected pattern.

Taking File by 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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/fs/file.zig (2)

244-268: Optionally allow seeding reader/writer from a non‑zero starting offset

Both FileReader and FileWriter embed position: u64 = 0 and init never takes an initial offset. For append‑style or partial reads (e.g. resuming at a checkpoint), having an initAt(file, runtime, buffer, start_pos) variant (or an optional start_pos argument) would make the wrappers more generally useful without forcing callers to fake it with manual offset math.


270-332: Defensive check for data.len == 0 in FileWriter.drain

drain assumes data.len > 0 (it slices data[0 .. data.len - 1] and indexes data[data.len - 1]). That matches how std.Io.Writer currently 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

📥 Commits

Reviewing files that changed from the base of the PR and between fd5682c and 86a597e.

📒 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: Stateless File API and offset-using tests look coherent

The switch to explicit offset on all File read/write variants (read, write, readVec, writeVec, readBuf, writeBuf) plus the trivial fromFd constructor and reader/writer helpers 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

Comment thread src/fs/file.zig Resolved
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).

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Underflow: If to_discard is 0 (or position is 0), r.position - 1 wraps to u64::MAX. Add an early return.

  2. EOF position corruption: When discarding past EOF, position advances to (say) 110 even though the file is only 100 bytes. The error is returned, but position is left corrupted. If the caller catches EndOfStream and continues using the FileReader, logicalPos() reports the wrong value. Roll back position when 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 position is always valid.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 86a597e and 2c64f2d.

📒 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() and writeVec() 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. The close() 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 mirrors FileReader for 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.

Comment thread src/fs/file.zig Resolved
Return early if to_discard == 0 to avoid underflow when computing
position - 1 for the verification read.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
src/fs/file.zig (1)

318-321: Multi-byte splat still only writes pattern once.

When splat > 1 and pattern.len > 1, the code adds the pattern to the iovec array only once. Calling writeSplatAll(&[_][]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 splat times 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"} with splat = 3 to 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2c64f2d and 684edf4.

📒 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 offset parameter, and the struct no longer tracks internal position. The fromFd rename aligns with Zig conventions, and the new readBuf/writeBuf methods 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.
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.

1 participant