Skip to content

Commit ba5bdb3

Browse files
authored
demo for beryllium (#1036)
1 parent 4bc2a65 commit ba5bdb3

File tree

1 file changed

+26
-0
lines changed
  • rust/canister-snapshots/src/chat/src

1 file changed

+26
-0
lines changed

rust/canister-snapshots/src/chat/src/lib.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,20 @@ use std::{cell::RefCell, collections::HashSet};
33

44
thread_local! {
55
static CHAT: RefCell<Vec<String>> = Default::default();
6+
static LENGTH: RefCell<u64> = Default::default();
67
}
78

89
/// Appends a new message to the chat database.
910
#[ic_cdk_macros::update]
1011
fn append(message: String) {
12+
// Ensure that the length of the chat is consistent with the actual chat
13+
// contents.
14+
assert_eq!(
15+
LENGTH.with_borrow(|len| *len),
16+
CHAT.with_borrow(|chat| chat.len() as u64)
17+
);
1118
CHAT.with_borrow_mut(|chat| chat.push(message));
19+
LENGTH.with_borrow_mut(|len| *len += 1);
1220
}
1321

1422
/// Dumps all the chat messages.
@@ -36,6 +44,7 @@ fn remove_spam() -> u64 {
3644
for message in chat {
3745
if message.split(" ").any(|word| spam_keywords.contains(word)) {
3846
spam += 1;
47+
ic_cdk::println!("Found spam message: {message}");
3948
new_chat.push("(removed spam message)".into());
4049
} else {
4150
new_chat.push(message);
@@ -47,5 +56,22 @@ fn remove_spam() -> u64 {
4756
ic_cdk::println!("Removed {spam} messages, updating the chat...");
4857
CHAT.set(new_chat);
4958
}
59+
ic_cdk::println!("Filtered chat: {:?}", CHAT.with_borrow(|chat| chat.clone()));
5060
spam
5161
}
62+
63+
#[ic_cdk_macros::pre_upgrade]
64+
fn pre_upgrade() {
65+
let chat = CHAT.with_borrow(|chat| chat.clone());
66+
let length = LENGTH.with_borrow(|len| *len);
67+
ic_cdk::storage::stable_save((chat, length)).expect("failed to save stable state");
68+
}
69+
70+
#[ic_cdk_macros::post_upgrade]
71+
fn post_upgrade() {
72+
let (chat, length): (Vec<String>, u64) =
73+
ic_cdk::storage::stable_restore().expect("failed to restore stable state");
74+
75+
CHAT.set(chat);
76+
LENGTH.with_borrow_mut(|len| *len = length);
77+
}

0 commit comments

Comments
 (0)