mirror of
https://github.com/ziglang/zig.git
synced 2026-01-03 20:13:21 +00:00
- split util_base.hpp from util.hpp - new namespaces: `mem` and `heap` - new `mem::Allocator` interface - new `heap::CAllocator` impl with global `heap::c_allocator` - new `heap::ArenaAllocator` impl - new `mem::TypeInfo` extracts names without RTTI - name extraction is enabled w/ ZIG_ENABLE_MEM_PROFILE=1 - new `mem::List` takes explicit `Allocator&` parameter - new `mem::HashMap` takes explicit `Allocator&` parameter - add Codegen.pass1_arena and use for all `ZigValue` allocs - deinit Codegen.pass1_arena early in `zig_llvm_emit_output()`
94 lines
2.0 KiB
C++
94 lines
2.0 KiB
C++
/*
|
|
* Copyright (c) 2015 Andrew Kelley
|
|
*
|
|
* This file is part of zig, which is MIT licensed.
|
|
* See http://opensource.org/licenses/MIT
|
|
*/
|
|
|
|
#ifndef ZIG_LIST_HPP
|
|
#define ZIG_LIST_HPP
|
|
|
|
#include "util.hpp"
|
|
|
|
template<typename T>
|
|
struct ZigList {
|
|
void deinit() {
|
|
heap::c_allocator.deallocate(items, capacity);
|
|
}
|
|
void append(const T& item) {
|
|
ensure_capacity(length + 1);
|
|
items[length++] = item;
|
|
}
|
|
// remember that the pointer to this item is invalid after you
|
|
// modify the length of the list
|
|
const T & at(size_t index) const {
|
|
assert(index != SIZE_MAX);
|
|
assert(index < length);
|
|
return items[index];
|
|
}
|
|
T & at(size_t index) {
|
|
assert(index != SIZE_MAX);
|
|
assert(index < length);
|
|
return items[index];
|
|
}
|
|
T pop() {
|
|
assert(length >= 1);
|
|
return items[--length];
|
|
}
|
|
|
|
T *add_one() {
|
|
resize(length + 1);
|
|
return &last();
|
|
}
|
|
|
|
const T & last() const {
|
|
assert(length >= 1);
|
|
return items[length - 1];
|
|
}
|
|
|
|
T & last() {
|
|
assert(length >= 1);
|
|
return items[length - 1];
|
|
}
|
|
|
|
void resize(size_t new_length) {
|
|
assert(new_length != SIZE_MAX);
|
|
ensure_capacity(new_length);
|
|
length = new_length;
|
|
}
|
|
|
|
void clear() {
|
|
length = 0;
|
|
}
|
|
|
|
void ensure_capacity(size_t new_capacity) {
|
|
if (capacity >= new_capacity)
|
|
return;
|
|
|
|
size_t better_capacity = capacity;
|
|
do {
|
|
better_capacity = better_capacity * 5 / 2 + 8;
|
|
} while (better_capacity < new_capacity);
|
|
|
|
items = heap::c_allocator.reallocate_nonzero(items, capacity, better_capacity);
|
|
capacity = better_capacity;
|
|
}
|
|
|
|
T swap_remove(size_t index) {
|
|
if (length - 1 == index) return pop();
|
|
|
|
assert(index != SIZE_MAX);
|
|
assert(index < length);
|
|
|
|
T old_item = items[index];
|
|
items[index] = pop();
|
|
return old_item;
|
|
}
|
|
|
|
T *items;
|
|
size_t length;
|
|
size_t capacity;
|
|
};
|
|
|
|
#endif
|