1 module soundio.list; 2 3 @nogc nothrow: 4 extern(C): __gshared: 5 6 7 import soundio.util; 8 import soundio.api; 9 import core.stdc.stdlib; 10 11 package: 12 13 struct SOUNDIO_LIST(Type) { 14 Type *items; 15 int length; 16 int capacity; 17 18 void deinit() { 19 free(this.items); 20 } 21 22 int ensure_capacity(int new_capacity) { 23 int better_capacity = soundio_int_max(this.capacity, 16); 24 while (better_capacity < new_capacity) 25 better_capacity = better_capacity * 2; 26 if (better_capacity != this.capacity) { 27 Type *new_items = REALLOCATE_NONZERO!Type(this.items, better_capacity); 28 if (!new_items) 29 return SoundIoError.NoMem; 30 this.items = new_items; 31 this.capacity = better_capacity; 32 } 33 return 0; 34 } 35 36 int append(Type item) { 37 int err = ensure_capacity(this.length + 1); 38 if (err) 39 return err; 40 this.items[this.length] = item; 41 this.length += 1; 42 return 0; 43 } 44 45 Type val_at(int index) { 46 assert(index >= 0); 47 assert(index < this.length); 48 return this.items[index]; 49 } 50 51 /* remember that the pointer to this item is invalid after you 52 * modify the length of the list 53 */ 54 Type* ptr_at(int index) { 55 assert(index >= 0); 56 assert(index < this.length); 57 return &this.items[index]; 58 } 59 60 Type pop() { 61 assert(this.length >= 1); 62 this.length -= 1; 63 return this.items[this.length]; 64 } 65 66 int resize(int new_length) { 67 assert(new_length >= 0); 68 int err = ensure_capacity(new_length); 69 if (err) 70 return err; 71 this.length = new_length; 72 return 0; 73 } 74 75 int add_one() { 76 return resize(this.length + 1); 77 } 78 79 Type last_val() { 80 assert(this.length >= 1); 81 return this.items[this.length - 1]; 82 } 83 84 Type* last_ptr() { 85 assert(this.length >= 1); 86 return &this.items[this.length - 1]; 87 } 88 89 void clear() { 90 this.length = 0; 91 } 92 93 Type swap_remove(int index) { 94 assert(index >= 0); 95 assert(index < this.length); 96 Type last = pop(); 97 if (index == this.length) 98 return last; 99 Type item = this.items[index]; 100 this.items[index] = last; 101 return item; 102 } 103 }