-
Notifications
You must be signed in to change notification settings - Fork 17
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(backend): extract add and remove user token
- Loading branch information
1 parent
5316f33
commit 26bd05a
Showing
2 changed files
with
63 additions
and
31 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
use crate::{Candid, StoredPrincipal, VMem}; | ||
use candid::{CandidType, Deserialize}; | ||
use ic_stable_structures::StableBTreeMap; | ||
|
||
const MAX_TOKEN_LIST_LENGTH: usize = 100; | ||
|
||
pub fn add_to_user_token<T>( | ||
stored_principal: StoredPrincipal, | ||
user_token: &mut StableBTreeMap<StoredPrincipal, Candid<Vec<T>>, VMem>, | ||
token: &T, | ||
find: &dyn Fn(&T) -> bool, | ||
) where | ||
T: for<'a> Deserialize<'a> + CandidType + Clone, | ||
{ | ||
let Candid(mut tokens) = user_token.get(&stored_principal).unwrap_or_default(); | ||
|
||
match tokens.iter().position(find) { | ||
Some(p) => { | ||
tokens[p] = token.clone(); | ||
} | ||
None => { | ||
if tokens.len() == MAX_TOKEN_LIST_LENGTH { | ||
ic_cdk::trap(&format!( | ||
"Token list length should not exceed {MAX_TOKEN_LIST_LENGTH}" | ||
)); | ||
} | ||
tokens.push(token.clone()); | ||
} | ||
} | ||
|
||
user_token.insert(stored_principal, Candid(tokens)); | ||
} | ||
|
||
pub fn remove_from_user_token<T>( | ||
stored_principal: StoredPrincipal, | ||
user_token: &mut StableBTreeMap<StoredPrincipal, Candid<Vec<T>>, VMem>, | ||
find: &dyn Fn(&T) -> bool, | ||
) where | ||
T: for<'a> Deserialize<'a> + CandidType, | ||
{ | ||
match user_token.get(&stored_principal) { | ||
None => (), | ||
Some(Candid(mut tokens)) => { | ||
if let Some(p) = tokens.iter().position(find) { | ||
tokens.swap_remove(p); | ||
user_token.insert(stored_principal, Candid(tokens)); | ||
} | ||
} | ||
} | ||
} |