跳转到内容

vector_ext - [mainnet]

此内容尚不支持你的语言。

use 0x1::vector;

Constants

The index into the vector is out of bounds

const EINDEX_OUT_OF_BOUNDS: u64 = 131072;

Functions

range_move

public fun range_move<T>(from: &mut vector<T>, removal_position: u64, length: u64, to: &mut vector<T>, insert_position: u64)
Implementation
public native fun range_move<T>(from: &mut vector<T>, removal_position: u64, length: u64, to: &mut vector<T>, insert_position: u64);

split_off

Splits the collection into two at the given index. Returns a newly allocated vector containing the elements in the range [at, len). After the call, the original vector will be left containing the elements [0, at) with its previous capacity unchanged.

public fun split_off<Element>(self: &mut vector<Element>, at: u64): vector<Element>
Implementation
public fun split_off<Element>(self: &mut vector<Element>, at: u64): vector<Element> {
    let len = vector::length(self);
    assert!(at <= len, EINDEX_OUT_OF_BOUNDS);

    let other = vector::empty();
    range_move(self, at, len - at, &mut other, 0);

    // let other = empty();
    // while (len > at) {
    //     push_back(&mut other, pop_back(self));
    //     len = len - 1;
    // };
    // reverse(&mut other);
    other
}

append

Pushes all of the elements of the other vector into the self vector.

public fun append<Element>(self: &mut vector<Element>, other: vector<Element>)
Implementation
public fun append<Element>(self: &mut vector<Element>, other: vector<Element>) {
    let self_length = self.length();
    let other_length = other.length();
    range_move(&mut other, 0, other_length, self, self_length);
    other.destroy_empty();
    // reverse(&mut other);
    // reverse_append(self, other);
}

insert

public fun insert<Element>(self: &mut vector<Element>, i: u64, e: Element)
Implementation
public fun insert<Element>(self: &mut vector<Element>, i: u64, e: Element) {
    let len = self.length();
    assert!(i <= len, EINDEX_OUT_OF_BOUNDS);

    if (i == len) {
        self.push_back(e);
    } else {
        let other = vector::singleton(e);
        range_move(&mut other, 0, 1, self, i);
        other.destroy_empty();
    }
}

remove

Remove the ith element of the vector self, shifting all subsequent elements. This is O(n) and preserves ordering of elements in the vector. Aborts if i is out of bounds.

public fun remove<Element>(self: &mut vector<Element>, i: u64): Element
Implementation
public fun remove<Element>(self: &mut vector<Element>, i: u64): Element {
    let len = self.length();
    // i out of bounds; abort
    if (i >= len) abort EINDEX_OUT_OF_BOUNDS;

    if (i + 1 == len) {
        self.pop_back()
    } else {
        let other = vector::empty();
        range_move(self, i, 1, &mut other, 0);
        let result = other.pop_back();
        other.destroy_empty();
        result
    }
}