| ... | @@ -98,6 +98,10 @@ pub const IncrementingAllocator = struct { | ... | @@ -98,6 +98,10 @@ pub const IncrementingAllocator = struct { |
| 98 | self.end_index = 0; | 98 | self.end_index = 0; |
| 99 | } | 99 | } |
| 100 | | 100 | |
| | 101 | fn bytesLeft(self: &const IncrementingAllocator) -> usize { |
| | 102 | return self.bytes.len - self.end_index; |
| | 103 | } |
| | 104 | |
| 101 | fn alloc(allocator: &Allocator, n: usize, alignment: usize) -> %[]u8 { | 105 | fn alloc(allocator: &Allocator, n: usize, alignment: usize) -> %[]u8 { |
| 102 | const self = @fieldParentPtr(IncrementingAllocator, "allocator", allocator); | 106 | const self = @fieldParentPtr(IncrementingAllocator, "allocator", allocator); |
| 103 | const addr = @ptrToInt(&self.bytes[self.end_index]); | 107 | const addr = @ptrToInt(&self.bytes[self.end_index]); |
| ... | @@ -124,6 +128,26 @@ pub const IncrementingAllocator = struct { | ... | @@ -124,6 +128,26 @@ pub const IncrementingAllocator = struct { |
| 124 | } | 128 | } |
| 125 | }; | 129 | }; |
| 126 | | 130 | |
| | 131 | test "mem.IncrementingAllocator" { |
| | 132 | const total_bytes = 100 * 1024 * 1024; |
| | 133 | var inc_allocator = %%IncrementingAllocator.init(total_bytes); |
| | 134 | defer inc_allocator.deinit(); |
| | 135 | |
| | 136 | const allocator = &inc_allocator.allocator; |
| | 137 | const slice = %%allocator.alloc(&i32, 100); |
| | 138 | |
| | 139 | for (slice) |*item, i| { |
| | 140 | *item = %%allocator.create(i32); |
| | 141 | **item = i32(i); |
| | 142 | } |
| | 143 | |
| | 144 | assert(inc_allocator.bytesLeft() == total_bytes - @sizeOf(i32) * 100 - @sizeOf(usize) * 100); |
| | 145 | |
| | 146 | inc_allocator.reset(); |
| | 147 | |
| | 148 | assert(inc_allocator.bytesLeft() == total_bytes); |
| | 149 | } |
| | 150 | |
| 127 | /// Copy all of source into dest at position 0. | 151 | /// Copy all of source into dest at position 0. |
| 128 | /// dest.len must be >= source.len. | 152 | /// dest.len must be >= source.len. |
| 129 | pub fn copy(comptime T: type, dest: []T, source: []const T) { | 153 | pub fn copy(comptime T: type, dest: []T, source: []const T) { |