From 82dac384cd13d97e07a1bca446c0af826696fd27 Mon Sep 17 00:00:00 2001 From: coco <1285015889@qq.com> Date: Sat, 28 Sep 2024 23:53:48 +0800 Subject: [PATCH] create 2024.09.28 note --- River.md | 79 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/River.md b/River.md index db71459..ad0efd2 100644 --- a/River.md +++ b/River.md @@ -916,4 +916,83 @@ balances.get('Maria'); 当运行“字典的基础用法”一节中的例子时,并不会执行字典压缩的操作,但是程序还是会编译成功。这是因为压缩操作会通过`Felt252Dict`所实现的`Destruct`特征来自动调用,这个调用仅仅在字典离开其作用域前执行 +### 2024.09.28 + +#### 字典的`Entry`和`Finalize` + +`Cairo`提供了`entry`和`finalize`方法来复制字典数据。 + +* `entry`:通过给定的`key`来创建一个新的entry。一旦被调用,这个方法会获得字典的所有权,并返回要更新的entry。方法签名如下: + + ~~~rust + fn entry(self: Felt252Dict, key: felt252) -> (Felt252DictEntry, T) nopanic + ~~~ + + 第一个参数来获取字典的所有权,第二个参数是用来创建合适的entry。该方法返回一个元组:`Felt252DictEntry`表示字典的entry,`T`表示entry的前一个值。`nopanic`表示该方法不会发生panic + +* `finalize`:向字典中插入entry,并返回其所有权。方法签名如下: + + ~~~rust + fn finalize(self: Felt252DictEntry, new_value: T) -> Felt252Dict + ~~~ + +🌰例子: + +自定义`get`方法: + +~~~rust +use core::dict::{Felt252Dict, Felt252DictEntryTrait}; + +fn custom_get, +Drop, +Copy>( + ref dict: Felt252Dict, key: felt252 +) -> T { + // Get the new entry and the previous value held at `key` + let (entry, prev_value) = dict.entry(key); + + // Store the value to return + let return_value = prev_value; + + // Update the entry with `prev_value` and get back ownership of the dictionary + dict = entry.finalize(prev_value); + + // Return the read value + return_value +} +~~~ + +自定义`insert`方法: + +~~~rust +use core::dict::{Felt252Dict, Felt252DictEntryTrait}; + +fn custom_insert, +Destruct, +Drop>( + ref dict: Felt252Dict, key: felt252, value: T +) { + // Get the last entry associated with `key` + // Notice that if `key` does not exist, `_prev_value` will + // be the default value of T. + let (entry, _prev_value) = dict.entry(key); + + // Insert `entry` back in the dictionary with the updated value, + // and receive ownership of the dictionary + dict = entry.finalize(value); +} +~~~ + +使用上面自定义的`get`和`insert`方法: + +~~~rust +fn main() { + let mut dict: Felt252Dict = Default::default(); + + custom_insert(ref dict, '0', 100); + + let val = custom_get(ref dict, '0'); + + assert!(val == 100, "Expecting 100"); +} +~~~ + + +