diff options
| author | acdenisSK <[email protected]> | 2017-08-23 00:17:01 +0200 |
|---|---|---|
| committer | acdenisSK <[email protected]> | 2017-08-23 00:18:00 +0200 |
| commit | 1a089048138e85607bd298ebc07e30f57fb4ac53 (patch) | |
| tree | eb76fa584044b973bf648ef3e6acbfd2e8df3d6b /src/utils | |
| parent | Use cache when possible in UserId's get method (#146) (diff) | |
| download | serenity-1a089048138e85607bd298ebc07e30f57fb4ac53.tar.xz serenity-1a089048138e85607bd298ebc07e30f57fb4ac53.zip | |
Add `with_config{_mut}`
Diffstat (limited to 'src/utils')
| -rw-r--r-- | src/utils/mod.rs | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 8467613..8f83c07 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -19,6 +19,8 @@ use std::io::Read; use std::path::Path; use internal::prelude::*; use model::{EmojiId, EmojiIdentifier}; +use cache::Cache; +use ::CACHE; /// Determines if a name is NSFW. /// @@ -432,3 +434,41 @@ pub fn parse_quotes(s: &str) -> Vec<String> { /// ``` #[inline] pub fn shard_id(guild_id: u64, shard_count: u64) -> u64 { (guild_id >> 22) % shard_count } + +/// A function for doing automatic `read`ing (and the releasing of the guard as well) +/// This is particularly useful if you just want to use the cache for this one time, +/// or don't want to be messing with the `RwLock` directly. +/// +/// # Examples +/// +/// Return the bot's id +/// +/// ```rust,ignore +/// use serenity::utils; +/// +/// // assuming that the id is `1234`: +/// assert_eq!(1234, utils::with_cache(|cache| cache.user.id)); +/// ``` +pub fn with_cache<T, F>(f: F) -> T where F: Fn(&Cache) -> T { + let cache = CACHE.read().unwrap(); + f(&cache) +} + +/// Like [`with_cache`] but as the name says, allows for modifications to be done. +/// +/// # Examples +/// +/// Return the bot's id, and changes the shard count +/// +/// ```rust,ignore +/// use serenity::utils; +/// +/// // assuming that the id is `1234`: +/// assert_eq!(1234, utils::with_cache_mut(|cache| { cache.shard_count = 8; cache.user.id })); +/// ``` +/// +/// [`with_cache`]: #fn.with_cache +pub fn with_cache_mut<T, F>(mut f: F) -> T where F: FnMut(&mut Cache) -> T { + let mut cache = CACHE.write().unwrap(); + f(&mut cache) +}
\ No newline at end of file |