Commit 9ae66b4c67

Andrew Kelley <superjoe30@gmail.com>
2017-09-28 04:04:38
add test for std.mem.IncrementingAllocator
See #501
1 parent 583ca36
Changed files (1)
std/mem.zig
@@ -98,6 +98,10 @@ pub const IncrementingAllocator = struct {
         self.end_index = 0;
     }
 
+    fn bytesLeft(self: &const IncrementingAllocator) -> usize {
+        return self.bytes.len - self.end_index;
+    }
+
     fn alloc(allocator: &Allocator, n: usize, alignment: usize) -> %[]u8 {
         const self = @fieldParentPtr(IncrementingAllocator, "allocator", allocator);
         const addr = @ptrToInt(&self.bytes[self.end_index]);
@@ -124,6 +128,26 @@ pub const IncrementingAllocator = struct {
     }
 };
 
+test "mem.IncrementingAllocator" {
+    const total_bytes = 100 * 1024 * 1024;
+    var inc_allocator = %%IncrementingAllocator.init(total_bytes);
+    defer inc_allocator.deinit();
+
+    const allocator = &inc_allocator.allocator;
+    const slice = %%allocator.alloc(&i32, 100);
+
+    for (slice) |*item, i| {
+        *item = %%allocator.create(i32);
+        **item = i32(i);
+    }
+
+    assert(inc_allocator.bytesLeft() == total_bytes - @sizeOf(i32) * 100 - @sizeOf(usize) * 100);
+
+    inc_allocator.reset();
+
+    assert(inc_allocator.bytesLeft() == total_bytes);
+}
+
 /// Copy all of source into dest at position 0.
 /// dest.len must be >= source.len.
 pub fn copy(comptime T: type, dest: []T, source: []const T) {