| ... | @@ -64,6 +64,8 @@ pub fn Queue(comptime T: type) type { | ... | @@ -64,6 +64,8 @@ pub fn Queue(comptime T: type) type { |
| 64 | return head; | 64 | return head; |
| 65 | } | 65 | } |
| 66 | | 66 | |
| | 67 | /// Prepends `node` to the front of the queue. |
| | 68 | /// The lifetime of `node` must be longer than the lifetime of the queue. |
| 67 | pub fn unget(self: *Self, node: *Node) void { | 69 | pub fn unget(self: *Self, node: *Node) void { |
| 68 | node.prev = null; | 70 | node.prev = null; |
| 69 | | 71 | |
| ... | @@ -72,8 +74,8 @@ pub fn Queue(comptime T: type) type { | ... | @@ -72,8 +74,8 @@ pub fn Queue(comptime T: type) type { |
| 72 | | 74 | |
| 73 | const opt_head = self.head; | 75 | const opt_head = self.head; |
| 74 | self.head = node; | 76 | self.head = node; |
| 75 | if (opt_head) |head| { | 77 | if (opt_head) |old_head| { |
| 76 | head.next = node; | 78 | node.next = old_head; |
| 77 | } else { | 79 | } else { |
| 78 | assert(self.tail == null); | 80 | assert(self.tail == null); |
| 79 | self.tail = node; | 81 | self.tail = node; |
| ... | @@ -330,11 +332,25 @@ test "std.atomic.Queue single-threaded" { | ... | @@ -330,11 +332,25 @@ test "std.atomic.Queue single-threaded" { |
| 330 | node_3.next = null; | 332 | node_3.next = null; |
| 331 | try expect(!queue.isEmpty()); | 333 | try expect(!queue.isEmpty()); |
| 332 | | 334 | |
| | 335 | queue.unget(&node_3); |
| | 336 | try expect(queue.get().?.data == 3); |
| | 337 | try expect(!queue.isEmpty()); |
| | 338 | |
| 333 | try expect(queue.get().?.data == 4); | 339 | try expect(queue.get().?.data == 4); |
| 334 | try expect(queue.isEmpty()); | 340 | try expect(queue.isEmpty()); |
| 335 | | 341 | |
| 336 | try expect(queue.get() == null); | 342 | try expect(queue.get() == null); |
| 337 | try expect(queue.isEmpty()); | 343 | try expect(queue.isEmpty()); |
| | 344 | |
| | 345 | // unget an empty queue |
| | 346 | queue.unget(&node_4); |
| | 347 | try expect(queue.tail == &node_4); |
| | 348 | try expect(queue.head == &node_4); |
| | 349 | |
| | 350 | try expect(queue.get().?.data == 4); |
| | 351 | |
| | 352 | try expect(queue.get() == null); |
| | 353 | try expect(queue.isEmpty()); |
| 338 | } | 354 | } |
| 339 | | 355 | |
| 340 | test "std.atomic.Queue dump" { | 356 | test "std.atomic.Queue dump" { |