zig/src/list.hpp

96 lines
2.0 KiB
C++
Raw Normal View History

2015-08-06 07:22:21 +08:00
/*
* Copyright (c) 2015 Andrew Kelley
*
* This file is part of zig, which is MIT licensed.
* See http://opensource.org/licenses/MIT
*/
2015-08-06 08:44:05 +08:00
#ifndef ZIG_LIST_HPP
#define ZIG_LIST_HPP
2015-08-06 07:22:21 +08:00
#include "util.hpp"
template<typename T>
2015-08-06 08:44:05 +08:00
struct ZigList {
2015-08-06 07:22:21 +08:00
void deinit() {
deallocate(items, capacity);
2015-08-06 07:22:21 +08:00
}
2019-09-19 17:35:40 +08:00
void append(const T& item) {
2015-08-06 08:44:05 +08:00
ensure_capacity(length + 1);
2015-08-06 07:22:21 +08:00
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);
2015-08-06 07:22:21 +08:00
assert(index < length);
return items[index];
}
T & at(size_t index) {
assert(index != SIZE_MAX);
2015-08-06 07:22:21 +08:00
assert(index < length);
return items[index];
}
T pop() {
assert(length >= 1);
return items[--length];
}
2016-11-24 15:44:03 +08:00
T *add_one() {
resize(length + 1);
return &last();
2015-08-06 07:22:21 +08:00
}
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);
2015-08-06 08:44:05 +08:00
ensure_capacity(new_length);
2015-08-06 07:22:21 +08:00
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 {
2017-04-11 08:02:39 +08:00
better_capacity = better_capacity * 5 / 2 + 8;
} while (better_capacity < new_capacity);
items = reallocate_nonzero(items, capacity, better_capacity);
capacity = better_capacity;
2015-08-06 07:22:21 +08:00
}
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;
2015-08-06 07:22:21 +08:00
};
#endif