From d943ce5dc79d2438ac82bb8e32baa33d3105306d Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Wed, 21 Feb 2024 00:14:48 -0700 Subject: [PATCH] std.io.Reader: add discard function Reads the stream until the end, ignoring all the data. Returns the number of bytes discarded. --- lib/std/io/Reader.zig | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/lib/std/io/Reader.zig b/lib/std/io/Reader.zig index 0d96629e7a..9569d8d565 100644 --- a/lib/std/io/Reader.zig +++ b/lib/std/io/Reader.zig @@ -360,6 +360,18 @@ pub fn readEnum(self: Self, comptime Enum: type, endian: std.builtin.Endian) any return E.InvalidValue; } +/// Reads the stream until the end, ignoring all the data. +/// Returns the number of bytes discarded. +pub fn discard(self: Self) anyerror!u64 { + var trash: [4096]u8 = undefined; + var index: u64 = 0; + while (true) { + const n = try self.read(&trash); + if (n == 0) return index; + index += n; + } +} + const std = @import("../std.zig"); const Self = @This(); const math = std.math;