@@ -77,15 +77,17 @@ pub const File = struct {
7777 return self .f .writer (io (), buffer );
7878 }
7979
80+ // std.Io.File exposes no public seek wrappers (only positional reads and
81+ // writes), so go through the Io vtable, which implements seeking for
82+ // every supported OS.
8083 pub fn seekTo (self : File , offset : u64 ) ! void {
81- const rc = std . os . linux . lseek ( self . f . handle , @intCast ( offset ), std . os . linux . SEEK . SET );
82- if ( std . os . linux . errno ( rc ) != .SUCCESS ) return error . Unseekable ;
84+ const i = io ( );
85+ return i . vtable . fileSeekTo ( i . userdata , self . f , offset ) ;
8386 }
8487
85- pub fn getPos (self : File ) ! u64 {
86- const rc = std .os .linux .lseek (self .f .handle , 0 , std .os .linux .SEEK .CUR );
87- if (std .os .linux .errno (rc ) != .SUCCESS ) return error .Unseekable ;
88- return rc ;
88+ pub fn seekBy (self : File , offset : i64 ) ! void {
89+ const i = io ();
90+ return i .vtable .fileSeekBy (i .userdata , self .f , offset );
8991 }
9092
9193 pub fn readToEndAlloc (self : File , allocator : std.mem.Allocator , max_bytes : usize ) ! []u8 {
@@ -97,6 +99,28 @@ pub const File = struct {
9799 }
98100};
99101
102+ test "File seekTo and seekBy reposition the stream" {
103+ var tmp = std .testing .tmpDir (.{});
104+ defer tmp .cleanup ();
105+
106+ var file = try (Dir { .d = tmp .dir }).createFile ("seek.bin" , .{ .read = true });
107+ defer file .close ();
108+ try file .writeAll ("abcdef" );
109+
110+ try file .seekTo (1 );
111+ var buf : [2 ]u8 = undefined ;
112+ try std .testing .expectEqual (@as (usize , 2 ), try file .readAll (buf [0.. 2]));
113+ try std .testing .expectEqualSlices (u8 , "bc" , buf [0.. 2]);
114+
115+ try file .seekBy (-1 );
116+ try std .testing .expectEqual (@as (usize , 1 ), try file .readAll (buf [0.. 1]));
117+ try std .testing .expectEqual (@as (u8 , 'c' ), buf [0 ]);
118+
119+ try file .seekTo (0 );
120+ try std .testing .expectEqual (@as (usize , 1 ), try file .readAll (buf [0.. 1]));
121+ try std .testing .expectEqual (@as (u8 , 'a' ), buf [0 ]);
122+ }
123+
100124pub fn stdout () File {
101125 return .{ .f = std .Io .File .stdout () };
102126}
0 commit comments