Skip to content

Commit

Permalink
Add with_config{_mut}
Browse files Browse the repository at this point in the history
  • Loading branch information
arqunis committed Aug 22, 2017
1 parent bfdb57c commit 1a08904
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
Expand Down Expand Up @@ -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)
}

0 comments on commit 1a08904

Please sign in to comment.