From c583d140135fe5a57d055d9c0b8bdf59698f29e1 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Tue, 28 Feb 2023 16:49:44 -0700 Subject: [PATCH] std.fifo: add toOwnedSlice method --- lib/std/fifo.zig | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/lib/std/fifo.zig b/lib/std/fifo.zig index b7c8f761d3..ad929cde8a 100644 --- a/lib/std/fifo.zig +++ b/lib/std/fifo.zig @@ -383,6 +383,21 @@ pub fn LinearFifo( self.discard(try dest_writer.write(self.readableSlice(0))); } } + + pub fn toOwnedSlice(self: *Self) Allocator.Error![]T { + assert(self.head == 0); + assert(self.count <= self.buf.len); + const allocator = self.allocator; + if (allocator.resize(self.buf, self.count)) { + const result = self.buf[0..self.count]; + self.* = Self.init(allocator); + return result; + } + const new_memory = try allocator.dupe(T, self.buf[0..self.count]); + allocator.free(self.buf); + self.* = Self.init(allocator); + return new_memory; + } }; }