table

模块说明

  • Table是一种类似于map的集合
  • 与传统集合不同的是,它的键和值不是存储在 Table 值中,而是使用Sui的对象系统(sui::dynamic_field)进行存储
  • Table 结构仅作为一个句柄,用于在对象系统中检索这些键和值
  • 具有完全相同的键值映射的 Table 值不会被 == 判断为相等
  • Table<K, V> 是一个同构映射,意味着所有其键和值都具有相同的类型

源码路径

table.move

方法图解

结构定义

public struct Table<phantom K: copy + drop + store, phantom V: store> has key, store {
    /// the ID of this table
    id: UID,
    /// the number of key-value pairs in the table
    size: u64,
}

方法说明

分类方法说明
初始化new<...>(ctx: &mut TxContext): Table<K, V>创建空Table
清理destroy_empty<...>(table: Table<K, V>)销毁空Table,若不为空,将报错:ETableNotEmpty
drop<...>(table: Table<K, V>)删除一个可能非空的表格。只有在值具有drop能力时才可用
add<...>(table: &mut Table<K, V>, k: K, v: V)添加键值对到Table
Key已存在,将报错:EFieldAlreadyExists
remove<...>(table: &mut Table<K, V>, k: K): VTable中删除并返回指定Key的键值对,若Key不存在将报错:EFieldDoesNotExist
borrow_mut<...>(table: &mut Table<K, V>, k: K): &mut VTable中读取指定Key的值的可变引用,以便进行对值进行修改,若Key不存在将报错:EFieldDoesNotExist
borrow<...>(table: &Table<K, V>, k: K): &VTable中读取指定Key的值,若Key不存在将报错:EFieldDoesNotExist
contains<...>(table: &Table<K, V>, k: K): boolTable中包含指定的Key的值返回true,否则返回false
length<...>(table: &Table<K, V>): u64 获取Table的长度
is_empty<...>(table: &Table<K, V>): bool 当且仅当Table为空时返回true,否则返回false

代码示例

同样采用书架和书本的示例,书本对象将添加到书架的Table中。

结构定义

public struct Bookshelf has key {
    id: UID,
    books: Table<String, Book>
}

public struct Book has key, store {
    id: UID,
    title: String,
    description: String,
}

创建书架共享对象

调用table::new方法

public fun create_bookshelf(ctx: &mut TxContext) {
    transfer::share_object(Bookshelf {
        id: object::new(ctx),
        books: table::new<String, Book>(ctx),
    });
}

添加书本到书架

调用table::add方法

public fun add_book(bookshelf: &mut Bookshelf, title: vector<u8>, description: vector<u8>, ctx: &mut TxContext) {
    let book = Book {
        id: object::new(ctx),
        title: ascii::string(title),
        description: ascii::string(description)
    };

    bookshelf.books.add(book.title, book);
}

获取书本

调用table::borrow方法。

public fun get_book(bookshelf: &Bookshelf, title: vector<u8>): &Book {
    bookshelf.books.borrow(ascii::string(title))
}

设置书本的描述信息

调用table::borrow_mut方法。

public fun set_book_desc(bookshelf: &mut Bookshelf, title: vector<u8>, description: vector<u8>) {
    let book_mut_ref = bookshelf.books.borrow_mut(ascii::string(title));
    book_mut_ref.description = ascii::string(description);
}

判断书本是否存在

调用table::contains方法。

public fun is_book_existed(bookshelf: &Bookshelf, title: vector<u8>): bool {
    bookshelf.books.contains(ascii::string(title))
}

从书架上移除书本

调用table::remove方法。

// 从书架上移除书本
public fun remove_book(bookshelf: &mut Bookshelf, title: vector<u8>): Book {
    bookshelf.books.remove(ascii::string(title))
}

判断书架是否为空

调用table::is_empty方法。

public fun is_bookshelf_empty(bookshelf: &Bookshelf): bool {
    bookshelf.books.is_empty()
}

获取书本数量

调用table::length方法。

public fun get_book_count(bookshelf: &Bookshelf): u64{
    bookshelf.books.length()
}

销毁空书架

调用table::destroy_empty方法。

public fun destroy_empty_bookshelf(bookshelf: Bookshelf) {
    let Bookshelf {id, books} = bookshelf;
    books.destroy_empty();
    id.delete()
}

完整代码

  • table
module cookbook::table {
    use sui::table::{Self, Table};
    use std::ascii::{Self, String};

    public struct Bookshelf has key {
        id: UID,
        books: Table<String, Book> 
    }

    public struct Book has key, store {
        id: UID,
        title: String, 
        description: String,
    }

    // 创建书架
    public fun create_bookshelf(ctx: &mut TxContext) {
        transfer::share_object(Bookshelf {
            id: object::new(ctx),
            books: table::new<String, Book>(ctx),
        });
	}

    // 销毁空书架
    public fun destroy_empty_bookshelf(bookshelf: Bookshelf) {
        let Bookshelf {id, books} = bookshelf;
        books.destroy_empty();
        id.delete()
    }

    // 添加书籍
    public fun add_book(bookshelf: &mut Bookshelf, title: vector<u8>, 
        description: vector<u8>, ctx: &mut TxContext) {
        let book = Book {
            id: object::new(ctx),
            title: ascii::string(title),
            description: ascii::string(description)
        };

        bookshelf.books.add(book.title, book);
    }

    // 拿取书本
    public fun get_book(bookshelf: &Bookshelf, title: vector<u8>): &Book {
        bookshelf.books.borrow(ascii::string(title))
    }

    // 设置书本描述
    public fun set_book_desc(bookshelf: &mut Bookshelf, title: vector<u8>, description: vector<u8>) {
        let book_mut_ref = bookshelf.books.borrow_mut(ascii::string(title));
        book_mut_ref.description = ascii::string(description);
    }

    // 从书架上移除书本
    public fun remove_book(bookshelf: &mut Bookshelf, title: vector<u8>): Book {
        bookshelf.books.remove(ascii::string(title))
    }

    // 判断书本是否存在
    public fun is_book_existed(bookshelf: &Bookshelf, title: vector<u8>): bool {
        bookshelf.books.contains(ascii::string(title))
    }

    // 判断书架是否为空
    public fun is_bookshelf_empty(bookshelf: &Bookshelf): bool {
        bookshelf.books.is_empty()
    }

    // 获取书本数量
    public fun get_book_count(bookshelf: &Bookshelf): u64{
        bookshelf.books.length()
    }

    public fun get_book_title(book: &Book): String {
        book.title
    }

    public fun get_book_desc(book: &Book): String {
        book.description
    }
}
  • table_tests
#[test_only]
module cookbook::table_tests {
    use std::ascii;
    use sui::test_scenario as ts;
    use cookbook::table::{Bookshelf, create_bookshelf, destroy_empty_bookshelf, 
        add_book, get_book, set_book_desc, is_book_existed, remove_book, is_bookshelf_empty,
        get_book_count, get_book_title, get_book_desc};

    #[test_only]
    use sui::test_utils::assert_eq;

    #[test]
    public fun test_table() {
        let alice = @0xa;    

        let mut ts = ts::begin(alice);

        // 创建书架
        {
            create_bookshelf(ts.ctx());
        };

        // 放置书本到书架
        let expected_title = b"Mastering Bitcoin";
        let expected_description= b"1st Edition";
        let expected_new_description= b"3rd Edition";

        {
            ts.next_tx(alice);
            let mut bookshelf: Bookshelf = ts.take_shared();

            add_book(
                &mut bookshelf, 
                expected_title, 
                expected_description,
                ts.ctx(),
            );

            assert_eq(bookshelf.get_book_count(), 1);
            assert_eq(bookshelf.is_bookshelf_empty(), false);

            ts::return_shared(bookshelf);
        };

        // 放置书本2到书架
        let expected_title2 = b"Move Cookbook";
        let expected_description2= b"1st Edition";

        {
            ts.next_tx(alice);
            let mut bookshelf: Bookshelf = ts.take_shared();

            add_book(
                &mut bookshelf, 
                expected_title2, 
                expected_description2,
                ts.ctx(),
            );

            assert_eq(bookshelf.get_book_count(), 2);

            ts::return_shared(bookshelf);
        };

        // 拿取书本
        {
            ts.next_tx(alice);
            let bookshelf: Bookshelf = ts.take_shared();

            let book = get_book(
                &bookshelf, 
                expected_title, 
            );

            assert_eq(book.get_book_title(), ascii::string(expected_title));
            assert_eq(book.get_book_desc(), ascii::string(expected_description));

            ts::return_shared(bookshelf);
        };

        // 设置书本的描述信息
        {
            ts.next_tx(alice);
            let mut bookshelf: Bookshelf = ts.take_shared();

            set_book_desc(
                &mut bookshelf, 
                expected_title, 
                expected_new_description,
            );

            let book = get_book(
                &bookshelf, 
                expected_title, 
            );

            assert_eq(book.get_book_title(), ascii::string(expected_title));
            assert_eq(book.get_book_desc(), ascii::string(expected_new_description));

            ts::return_shared(bookshelf);
        };

        // 判断书本是否存在
        {
            ts.next_tx(alice);
            let bookshelf: Bookshelf = ts.take_shared();

            let is_existed = is_book_existed(
                &bookshelf, 
                expected_title, 
            );
            assert_eq(is_existed, true);

            ts::return_shared(bookshelf);
        };

        // 从书架上借走书本
        {
            ts.next_tx(alice);
            let mut bookshelf: Bookshelf = ts.take_shared();

            {
                assert_eq(bookshelf.get_book_count(), 2);
                let book = remove_book(
                    &mut bookshelf, 
                    expected_title, 
                );
                assert_eq(bookshelf.get_book_count(), 1);
                assert_eq(book.get_book_title(), ascii::string(expected_title));
                assert_eq(book.get_book_desc(), ascii::string(expected_new_description));
                transfer::public_transfer(book, alice);
            };

            {
                assert_eq(bookshelf.get_book_count(), 1);
                let book = remove_book(
                    &mut bookshelf, 
                    expected_title2, 
                );
                assert_eq(bookshelf.get_book_count(), 0);
                assert_eq(book.get_book_title(), ascii::string(expected_title2));
                assert_eq(book.get_book_desc(), ascii::string(expected_description2));
                transfer::public_transfer(book, alice);
            };

            ts::return_shared(bookshelf);
        };

        // 销毁书架
        {
            ts.next_tx(alice);
            let bookshelf: Bookshelf = ts.take_shared();
            destroy_empty_bookshelf(bookshelf);
        };

        ts.end();
    }
}