window

source of std::vector

1// The growable array.2//3// A Vector owns a heap buffer and a count of the elements in use; the4// slots past them hold moved-from values. Growing allocates a buffer of5// moved-from values, zero bytes that nothing copies, and moves the6// elements into it with one range move, which frees the old buffer7// without visiting its slots (section 5.2). The buffer grows by half on8// exhaustion, so pushes are amortized constant. An empty vector has no9// buffer. A vector of disposable elements is disposable itself and10// disposes them in order (section 5.2).1112import std::option;13import std::iterable;14import std::dispose;15import std::equal;16import std::string;17import std::format;1819exp type Vector<T> : Iterable<T, VectorCursor<T>> + Disposable if (20    T: Disposable21) + Equal + Format if (T: Format) = struct {22    storage: Option<*var [T]>,23    count: u64,24};2526// Writes the elements as `[a, b, c]` (std::format).27exp fn format<T: Format>(self vector: &Vector<T>, out: &var String) {28    out.write_all(&vector.view());29}3031// A vector with no elements and no allocation.32exp fn Vector::empty() -> Vector<T> {33    return Vector { .storage = ::None, .count = 0 };34}3536// An empty vector with room for `capacity` elements, so that many pushes37// allocate nothing more.38exp fn Vector::with_capacity(capacity: u64) -> Vector<T> {39    if (capacity == 0) {40        return Vector<T>::empty();41    }42    return Vector { .storage = ::Some(new [T.moved() : capacity]), .count = 0 };43}4445// A vector holding copies of the items, allocated to fit them; disposable46// items cannot be copied, so their vectors are filled by push.47exp fn Vector::from(items: &[T]) -> Vector<T> {48    if (items.length() == 0) {49        return Vector<T>::empty();50    }51    var buffer: *var [T] = new [T.moved() : items.length()];52    for ([..items.length()]) |k| {53        buffer[k] = copy items[k];54    }55    return Vector { .storage = ::Some(move buffer), .count = items.length() };56}5758// A vector of `count` copies of the item, allocated to fit them.59exp fn Vector::filled(item: T, count: u64) -> Vector<T> {60    if (count == 0) {61        return Vector<T>::empty();62    }63    return Vector { .storage = ::Some(new [copy item : count]), .count = count };64}6566// Disposes the elements in order and empties the vector, freeing its67// buffer; the elements past the count are moved-from fillers.68exp fn dispose<T: Disposable>(self vector: &var Vector<T>) {69    if (vector.storage is ::Some |move buffer|) {70        for (move buffer[..vector.count]) |&var item| {71            item.dispose();72        }73    }74    vector.count = 0;75}7677// What `==` compares: the elements in use, in order, whatever the78// capacities.79exp fn equals<T>(self vector: &Vector<T>, other: &Vector<T>) -> bool {80    return vector.view() == other.view();81}8283// The number of elements in use.84exp fn length<T>(self vector: &Vector<T>) -> u64 {85    return vector.count;86}8788// Appends one element, growing the buffer when it is full. The elements89// move (section 5.2), so an owning element keeps its allocation.90exp fn push<T>(self vector: &var Vector<T>, item: T) {91    const in_use = vector.count;92    if (in_use == vector.capacity()) {93        vector.grow(in_use + 1);94    }95    if (vector.storage is ::Some |&var buffer|) {96        buffer[in_use] = move item;97    }98    vector.count = in_use + 1;99}100101// Makes room for `additional` more elements, so that many pushes do not102// grow the buffer again.103exp fn reserve<T>(self vector: &var Vector<T>, additional: u64) {104    if (vector.count + additional > vector.capacity()) {105        vector.grow(vector.count + additional);106    }107}108109// Moves the elements into a buffer of at least `needed` slots, half again110// as many as they fill.111fn grow<T>(self vector: &var Vector<T>, needed: u64) {112    const in_use = vector.count;113    var capacity = in_use + in_use / 2 + 1;114    if (in_use == 0) {115        capacity = 4;116    }117    if (capacity < needed) {118        capacity = needed;119    }120    vector.resize_buffer(capacity);121}122123// Moves the elements into a buffer of exactly `capacity` slots.124fn resize_buffer<T>(self vector: &var Vector<T>, capacity: u64) {125    var grown: *var [T] = new [T.moved() : capacity];126    if (vector.storage is ::Some |move buffer|) {127        grown[..vector.count] = move buffer[..vector.count];128    }129    vector.storage = ::Some(move grown);130}131132// Appends copies of the items, growing the buffer at most once: as many133// pushes, without a check each. Disposable items cannot be copied; push134// them instead.135exp fn append<T>(self vector: &var Vector<T>, items: &[T]) {136    if (items.length() == 0) {137        return;138    }139    const in_use = vector.count;140    const needed = in_use + items.length();141    if (needed > vector.capacity()) {142        vector.grow(needed);143    }144    if (vector.storage is ::Some |&var buffer|) {145        for ([..items.length()]) |k| {146            buffer[in_use + k] = copy items[k];147        }148    }149    vector.count = needed;150}151152// The element at the index, in place; a fault past the end. Like any153// reference, it is invalidated when a later push grows the buffer.154exp fn get<T>(self vector: &Vector<T>, index: u64) -> &T {155    return &vector.view()[index];156}157158// The element at the index, in place for writing; a fault past the end.159exp fn get_var<T>(self vector: &var Vector<T>, index: u64) -> &var T {160    return &var vector.items()[index];161}162163// The element at the index in place, or `None` past the end.164exp fn try_get<T>(self vector: &Vector<T>, index: u64) -> Option<&T> {165    if (index >= vector.count) {166        return ::None;167    }168    if (vector.storage is ::Some |&buffer|) {169        return ::Some(&buffer[index]);170    }171    return ::None;172}173174// Borrows the elements in use as a `&[T]` slice, in place. The view is175// invalidated by the next mutation (growth may reallocate), like any176// Alloy reference.177exp fn view<T>(self vector: &Vector<T>) -> &[T] {178    if (vector.storage is ::Some |&buffer|) {179        return &buffer[..vector.count];180    }181    return &[];182}183184// Overwrites the element at the index, moving the item in; past the end185// the item is dropped instead. A disposable element replaced, or item186// dropped, is disposed first, as C++'s assignment releases what it187// replaces (section 5.2).188exp fn set<T>(self vector: &var Vector<T>, index: u64, item: T) {189    if (index < vector.count && vector.storage is ::Some |&var buffer|) {190        if (T: Disposable) {191            buffer[index].dispose();192        }193        buffer[index] = move item;194        return;195    }196    if (T: Disposable) {197        var unused = move item;198        unused.dispose();199    }200}201202// Removes and returns the last element, or `None` when empty. The203// element moves out (section 5.2), and the buffer is kept for future204// pushes.205exp fn pop<T>(self vector: &var Vector<T>) -> Option<T> {206    if (vector.count == 0) {207        return ::None;208    }209    vector.count -= 1;210    if (vector.storage is ::Some |&var buffer|) {211        return ::Some(move buffer[vector.count]);212    }213    return ::None;214}215216// Drops every element past the length, last first, keeping the buffer; a217// disposable element is disposed first, as C++'s resize destroys what it218// removes.219exp fn truncate<T>(self vector: &var Vector<T>, length: u64) {220    while (vector.count > length) {221        vector.count -= 1;222        if (vector.storage is ::Some |&var buffer|) {223            var removed = move buffer[vector.count];224            if (T: Disposable) {225                removed.dispose();226            }227        }228    }229}230231// Drops every element, disposing a disposable one first, and keeps the232// buffer for future pushes.233exp fn clear<T>(self vector: &var Vector<T>) {234    vector.truncate(0);235}236237// The last element in place; a fault when the vector is empty.238exp fn last<T>(self vector: &Vector<T>) -> &T {239    if (vector.count == 0) {240        panic "the vector is empty";241    }242    return &vector.get(vector.count - 1);243}244245// The last element in place, or `None` when empty.246exp fn try_last<T>(self vector: &Vector<T>) -> Option<&T> {247    if (vector.count == 0) {248        return ::None;249    }250    return ::Some(&vector.get(vector.count - 1));251}252253// Gives back the room past the elements in use, moving them into a254// buffer that holds just them: for a vector done growing and kept.255exp fn shrink<T>(self vector: &var Vector<T>) {256    const in_use = vector.count;257    if (in_use == vector.capacity()) {258        return;259    }260    if (in_use == 0) {261        vector.storage = ::None;262        return;263    }264    vector.resize_buffer(in_use);265}266267// Borrows the elements in use mutably, in place, for writing or sorting268// them; invalidated by the next push like any reference into the vector.269exp fn items<T>(self vector: &var Vector<T>) -> &var [T] {270    if (vector.storage is ::Some |&var buffer|) {271        return &var buffer[..vector.count];272    }273    var nothing: [T : 0] = [];274    return &var nothing[..];275}276277// Puts the item at the index and returns the element it replaces; a fault278// past the end.279exp fn replace<T>(self vector: &var Vector<T>, index: u64, item: T) -> T {280    const buffer = &var vector.items();281    var old = move buffer[index];282    buffer[index] = move item;283    return move old;284}285286// Puts the item at the index and returns the element it replaces, or287// `None` past the end, where the item is dropped.288exp fn try_replace<T>(self vector: &var Vector<T>, index: u64, item: T) -> Option<T> {289    if (index >= vector.count) {290        return ::None;291    }292    return ::Some(vector.replace(index, move item));293}294295// Removes and returns the element at the index, the later elements moving296// down one place, keeping their order; a fault past the end.297exp fn remove<T>(self vector: &var Vector<T>, index: u64) -> T {298    const buffer = &var vector.items();299    var removed = move buffer[index];300    buffer[index..vector.count - 1] = move buffer[index + 1..vector.count];301    vector.count -= 1;302    return move removed;303}304305// Removes and returns the element at the index, or `None` past the end;306// the later elements move down one place, keeping their order.307exp fn try_remove<T>(self vector: &var Vector<T>, index: u64) -> Option<T> {308    if (index >= vector.count) {309        return ::None;310    }311    return ::Some(vector.remove(index));312}313314// Removes and returns the element at the index in constant time, the last315// element taking its place; a fault past the end.316exp fn swap_remove<T>(self vector: &var Vector<T>, index: u64) -> T {317    const buffer = &var vector.items();318    var removed = move buffer[index];319    vector.count -= 1;320    if (index != vector.count) {321        buffer[index] = move buffer[vector.count];322    }323    return move removed;324}325326// Removes and returns the element at the index, or `None` past the end,327// in constant time: the last element takes its place.328exp fn try_swap_remove<T>(self vector: &var Vector<T>, index: u64) -> Option<T> {329    if (index >= vector.count) {330        return ::None;331    }332    return ::Some(vector.swap_remove(index));333}334335// Puts the item at the index, the later elements moving up one place; an336// index past the end appends it.337exp fn insert<T>(self vector: &var Vector<T>, index: u64, item: T) {338    const at = vector.count;339    if (index >= at) {340        vector.push(move item);341        return;342    }343    if (at == vector.capacity()) {344        vector.grow(at + 1);345    }346    if (vector.storage is ::Some |&var buffer|) {347        buffer[index + 1..at + 1] = move buffer[index..at];348        buffer[index] = move item;349    }350    vector.count = at + 1;351}352353// The slots the buffer has, in use or not.354exp fn capacity<T>(self vector: &Vector<T>) -> u64 {355    if (vector.storage is ::Some |&buffer|) {356        return buffer.length();357    }358    return 0;359}360361// The cursor behind `for (vector) |element|` (section 5.3): it borrows362// the vector and hands out references to the elements in place.363exp type VectorCursor<T> : Iterator<T> = struct {364    subject: &Vector<T>,365    index: u64,366};367368exp fn iterator<T>(self vector: &Vector<T>) -> VectorCursor<T> {369    return VectorCursor { .subject = &vector, .index = 0 };370}371372exp fn next<T>(self cursor: &var VectorCursor<T>) -> Option<&T> {373    const result = cursor.subject.try_get(cursor.index);374    if (result is ::Some) {375        cursor.index += 1;376    }377    return result;378}