Branch data Line data Source code
1 : : /* 2 : : * Copyright (c) 2015 Andrew Kelley 3 : : * 4 : : * This file is part of zig, which is MIT licensed. 5 : : * See http://opensource.org/licenses/MIT 6 : : */ 7 : : 8 : : #ifndef ZIG_LIST_HPP 9 : : #define ZIG_LIST_HPP 10 : : 11 : : #include "util.hpp" 12 : : 13 : : template<typename T> 14 : : struct ZigList { 15 : 14001 : void deinit() { 16 : 14001 : free(items); 17 : 14001 : } 18 : 18892226 : void append(T item) { 19 : 18892226 : ensure_capacity(length + 1); 20 : 18892226 : items[length++] = item; 21 : 18892226 : } 22 : : // remember that the pointer to this item is invalid after you 23 : : // modify the length of the list 24 : 22046 : const T & at(size_t index) const { 25 : 22046 : assert(index != SIZE_MAX); 26 : 22046 : assert(index < length); 27 : 22046 : return items[index]; 28 : : } 29 : 118693256 : T & at(size_t index) { 30 : 118693256 : assert(index != SIZE_MAX); 31 : 118693256 : assert(index < length); 32 : 118693256 : return items[index]; 33 : : } 34 : 164429 : T pop() { 35 : 164429 : assert(length >= 1); 36 : 164429 : return items[--length]; 37 : : } 38 : : 39 : 2894659 : T *add_one() { 40 : 2894659 : resize(length + 1); 41 : 2894659 : return &last(); 42 : : } 43 : : 44 : : const T & last() const { 45 : : assert(length >= 1); 46 : : return items[length - 1]; 47 : : } 48 : : 49 : 5921434 : T & last() { 50 : 5921434 : assert(length >= 1); 51 : 5921434 : return items[length - 1]; 52 : : } 53 : : 54 : 12438095 : void resize(size_t new_length) { 55 : 12438095 : assert(new_length != SIZE_MAX); 56 : 12438095 : ensure_capacity(new_length); 57 : 12438095 : length = new_length; 58 : 12438095 : } 59 : : 60 : 0 : void clear() { 61 : 0 : length = 0; 62 : 0 : } 63 : : 64 : 31330321 : void ensure_capacity(size_t new_capacity) { 65 [ + + ][ + + ]: 31330321 : if (capacity >= new_capacity) [ + + ][ + + ] [ + + ][ + + ] [ + + ][ + + ] [ + + ][ + + ] [ + + ][ + + ] [ + + ][ # # ] [ + + ][ + + ] [ + + ][ + + ] [ + + ][ # # ] 66 : 25653683 : return; 67 : : 68 : 5676638 : size_t better_capacity = capacity; 69 : 247064 : do { 70 : 5923702 : better_capacity = better_capacity * 5 / 2 + 8; 71 [ - + ][ - + ]: 5923702 : } while (better_capacity < new_capacity); [ - + ][ + + ] [ - + ][ - + ] [ - + ][ - + ] [ - + ][ - + ] [ - + ][ - + ] [ + + ][ # # ] [ - + ][ - + ] [ - + ][ - + ] [ - + ][ # # ] 72 : : 73 : 5676638 : items = reallocate_nonzero(items, capacity, better_capacity); 74 : 5676638 : capacity = better_capacity; 75 : : } 76 : : 77 : 584 : T swap_remove(size_t index) { 78 [ + + ]: 584 : if (length - 1 == index) return pop(); 79 : : 80 : 40 : assert(index != SIZE_MAX); 81 : 40 : assert(index < length); 82 : : 83 : 40 : T old_item = items[index]; 84 : 40 : items[index] = pop(); 85 : 40 : return old_item; 86 : : } 87 : : 88 : : T *items; 89 : : size_t length; 90 : : size_t capacity; 91 : : }; 92 : : 93 : : #endif 94 : : 95 : :