| ... | ... | @@ -239,6 +239,24 @@ pub fn BoundedArray(comptime T: type, comptime capacity: usize) type { |
| 239 | 239 | assert(self.len <= capacity); |
| 240 | 240 | mem.set(T, self.slice()[old_len..self.len], value); |
| 241 | 241 | } |
| 242 | |
| 243 | pub const Writer = if (T != u8) |
| 244 | @compileError("The Writer interface is only defined for BoundedArray(u8, ...) " ++ |
| 245 | "but the given type is BoundedArray(" ++ @typeName(T) ++ ", ...)") |
| 246 | else |
| 247 | std.io.Writer(*Self, error{Overflow}, appendWrite); |
| 248 | |
| 249 | /// Initializes a writer which will write into the array. |
| 250 | pub fn writer(self: *Self) Writer { |
| 251 | return .{ .context = self }; |
| 252 | } |
| 253 | |
| 254 | /// Same as `appendSlice` except it returns the number of bytes written, which is always the same |
| 255 | /// as `m.len`. The purpose of this function existing is to match `std.io.Writer` API. |
| 256 | fn appendWrite(self: *Self, m: []const u8) error{Overflow}!usize { |
| 257 | try self.appendSlice(m); |
| 258 | return m.len; |
| 259 | } |
| 242 | 260 | }; |
| 243 | 261 | } |
| 244 | 262 | |
| ... | ... | @@ -336,4 +354,10 @@ test "BoundedArray" { |
| 336 | 354 | const swapped = a.swapRemove(0); |
| 337 | 355 | try testing.expectEqual(swapped, 0xdd); |
| 338 | 356 | try testing.expectEqual(a.get(0), 0xee); |
| 357 | |
| 358 | while (a.popOrNull()) |_| {} |
| 359 | const w = a.writer(); |
| 360 | const s = "hello, this is a test string"; |
| 361 | try w.writeAll(s); |
| 362 | try testing.expectEqualStrings(s, a.constSlice()); |
| 339 | 363 | } |