Get rid of mut refs

This commit is contained in:
Natsu Kagami 2020-02-02 20:21:07 -05:00
parent 8c34c7a3ba
commit 9287bdf5b7
7 changed files with 52 additions and 67 deletions

View file

@ -33,9 +33,9 @@ pub fn soft_ban(ctx: &mut Context, msg: &Message, mut args: Args) -> CommandResu
};
let guild = msg.guild_id.ok_or(Error::from("Command is guild only"))?;
let mut data = ctx.data.write();
let mut data = data
.get_mut::<SoftBans>()
let data = ctx.data.read();
let data = data
.get::<SoftBans>()
.ok_or(Error::from("DB initialized"))
.map(|v| DBWriteGuard::from(v))?;
let mut data = data.borrow_mut()?;
@ -98,14 +98,14 @@ pub fn soft_ban_init(ctx: &mut Context, msg: &Message, mut args: Args) -> Comman
)));
}
// Check if we already set up
let mut data = ctx.data.write();
let mut db: DBWriteGuard<_> = data
.get_mut::<SoftBans>()
let data = ctx.data.read();
let db: DBWriteGuard<_> = data
.get::<SoftBans>()
.ok_or(Error::from("DB uninitialized"))?
.into();
let mut db = db.borrow_mut()?;
let server = db
.get_mut(&guild.id)
.get(&guild.id)
.map(|v| match v {
ServerSoftBans::Unimplemented => false,
_ => true,
@ -135,9 +135,9 @@ pub fn watch_soft_bans(client: &mut serenity::Client) -> impl FnOnce() -> () + '
// Scope so that locks are released
{
// Poll the data for any changes.
let mut data = data.write();
let mut db: DBWriteGuard<_> = data
.get_mut::<SoftBans>()
let data = data.read();
let db: DBWriteGuard<_> = data
.get::<SoftBans>()
.expect("DB wrongly initialized")
.into();
let mut db = db.borrow_mut().expect("cannot unpack DB");

View file

@ -14,15 +14,12 @@ pub trait Announcer {
fn announcer_key() -> &'static str;
fn send_messages(
c: &Http,
d: &mut ShareMap,
d: &ShareMap,
channels: impl Fn(UserId) -> Vec<ChannelId> + Sync,
) -> CommandResult;
fn set_channel(d: &mut ShareMap, guild: GuildId, channel: ChannelId) -> CommandResult {
let mut data: DBWriteGuard<_> = d
.get_mut::<AnnouncerChannels>()
.expect("DB initialized")
.into();
fn set_channel(d: &ShareMap, guild: GuildId, channel: ChannelId) -> CommandResult {
let data: DBWriteGuard<_> = d.get::<AnnouncerChannels>().expect("DB initialized").into();
let mut data = data.borrow_mut()?;
data.entry(Self::announcer_key().to_owned())
.or_default()
@ -30,7 +27,7 @@ pub trait Announcer {
Ok(())
}
fn get_guilds(d: &mut ShareMap) -> Result<Vec<(GuildId, ChannelId)>, Error> {
fn get_guilds(d: &ShareMap) -> Result<Vec<(GuildId, ChannelId)>, Error> {
let data = d
.get::<AnnouncerChannels>()
.expect("DB initialized")
@ -42,7 +39,7 @@ pub trait Announcer {
Ok(data)
}
fn announce(c: &Http, d: &mut ShareMap) -> CommandResult {
fn announce(c: &Http, d: &ShareMap) -> CommandResult {
let guilds: Vec<_> = Self::get_guilds(d)?;
let member_sets = {
let mut v = Vec::with_capacity(guilds.len());
@ -75,7 +72,7 @@ pub trait Announcer {
let c = client.cache_and_http.clone();
let data = client.data.clone();
spawn(move || loop {
if let Err(e) = Self::announce(c.http(), &mut *data.write()) {
if let Err(e) = Self::announce(c.http(), &*data.read()) {
dbg!(e);
}
std::thread::sleep(cooldown);

View file

@ -2,10 +2,9 @@ use super::{embeds::score_embed, BeatmapWithMode};
use crate::{
commands::announcer::Announcer,
db::{OsuSavedUsers, OsuUser},
http::{Osu, HTTP},
http::Osu,
};
use rayon::prelude::*;
use reqwest::blocking::Client as HTTPClient;
use serenity::{
framework::standard::{CommandError as Error, CommandResult},
http::Http,
@ -30,7 +29,7 @@ impl Announcer for OsuAnnouncer {
}
fn send_messages(
c: &Http,
d: &mut ShareMap,
d: &ShareMap,
channels: impl Fn(UserId) -> Vec<ChannelId> + Sync,
) -> CommandResult {
let osu = d.get::<Osu>().expect("osu!client").clone();
@ -87,7 +86,7 @@ impl Announcer for OsuAnnouncer {
osu_user.last_update = chrono::Utc::now();
}
// Update users
let f = d.get_mut::<OsuSavedUsers>().expect("DB initialized");
let f = d.get::<OsuSavedUsers>().expect("DB initialized");
f.write(|f| *f = data)?;
f.save()?;
Ok(())

View file

@ -8,12 +8,12 @@ use serenity::{
/// Save the beatmap into the server data storage.
pub(crate) fn save_beatmap(
data: &mut ShareMap,
data: &ShareMap,
channel_id: ChannelId,
bm: &BeatmapWithMode,
) -> CommandResult {
let mut db: DBWriteGuard<_> = data
.get_mut::<OsuLastBeatmap>()
let db: DBWriteGuard<_> = data
.get::<OsuLastBeatmap>()
.expect("DB is implemented")
.into();
let mut db = db.borrow_mut()?;

View file

@ -47,7 +47,7 @@ pub fn hook(ctx: &mut Context, msg: &Message) -> () {
}
// Save the beatmap for query later.
if let Some(t) = last_beatmap {
if let Err(v) = super::cache::save_beatmap(&mut *ctx.data.write(), msg.channel_id, &t) {
if let Err(v) = super::cache::save_beatmap(&*ctx.data.read(), msg.channel_id, &t) {
dbg!(v);
}
}
@ -121,8 +121,7 @@ fn handle_old_links<'a>(ctx: &mut Context, content: &'a str) -> Result<Vec<ToPri
}
fn handle_new_links<'a>(ctx: &mut Context, content: &'a str) -> Result<Vec<ToPrint<'a>>, Error> {
let data = ctx.data.write();
let osu = data.get::<http::Osu>().unwrap().clone();
let osu = ctx.data.read().get::<http::Osu>().unwrap().clone();
let mut to_prints: Vec<ToPrint<'a>> = Vec::new();
for capture in NEW_LINK_REGEX.captures_iter(content) {
let mode = capture.name("mode").and_then(|v| {

View file

@ -97,9 +97,9 @@ pub fn save(ctx: &mut Context, msg: &Message, mut args: Args) -> CommandResult {
let user: Option<User> = osu.user(UserID::Auto(user), |f| f)?;
match user {
Some(u) => {
let mut db = ctx.data.write();
let mut db: DBWriteGuard<_> = db
.get_mut::<OsuSavedUsers>()
let db = ctx.data.read();
let db: DBWriteGuard<_> = db
.get::<OsuSavedUsers>()
.ok_or(Error::from("DB uninitialized"))?
.into();
let mut db = db.borrow_mut()?;
@ -147,18 +147,14 @@ enum UsernameArg {
}
impl UsernameArg {
fn to_user_id_query(
s: Option<Self>,
data: &mut ShareMap,
msg: &Message,
) -> Result<UserID, Error> {
fn to_user_id_query(s: Option<Self>, data: &ShareMap, msg: &Message) -> Result<UserID, Error> {
let id = match s {
Some(UsernameArg::Raw(s)) => return Ok(UserID::Auto(s)),
Some(UsernameArg::Tagged(r)) => r,
None => msg.author.id,
};
let db: DBWriteGuard<_> = data
.get_mut::<OsuSavedUsers>()
.get::<OsuSavedUsers>()
.ok_or(Error::from("DB uninitialized"))?
.into();
let db = db.borrow()?;
@ -202,11 +198,8 @@ impl FromStr for Nth {
pub fn recent(ctx: &mut Context, msg: &Message, mut args: Args) -> CommandResult {
let nth = args.single::<Nth>().unwrap_or(Nth(1)).0.min(50).max(1);
let mode = args.single::<ModeArg>().unwrap_or(ModeArg(Mode::Std)).0;
let user = UsernameArg::to_user_id_query(
args.single::<UsernameArg>().ok(),
&mut *ctx.data.write(),
msg,
)?;
let user =
UsernameArg::to_user_id_query(args.single::<UsernameArg>().ok(), &*ctx.data.read(), msg)?;
let osu: OsuClient = ctx.data.read().get::<http::Osu>().unwrap().clone();
let user = osu
@ -235,7 +228,7 @@ pub fn recent(ctx: &mut Context, msg: &Message, mut args: Args) -> CommandResult
})?;
// Save the beatmap...
cache::save_beatmap(&mut *ctx.data.write(), msg.channel_id, &beatmap)?;
cache::save_beatmap(&*ctx.data.read(), msg.channel_id, &beatmap)?;
Ok(())
}
@ -244,9 +237,7 @@ pub fn recent(ctx: &mut Context, msg: &Message, mut args: Args) -> CommandResult
#[description = "Show information from the last queried beatmap."]
#[num_args(0)]
pub fn last(ctx: &mut Context, msg: &Message, _: Args) -> CommandResult {
let mut data = ctx.data.write();
let b = cache::get_beatmap(&mut *data, msg.channel_id)?;
let b = cache::get_beatmap(&*ctx.data.read(), msg.channel_id)?;
match b {
Some(BeatmapWithMode(b, m)) => {
@ -271,9 +262,7 @@ pub fn last(ctx: &mut Context, msg: &Message, _: Args) -> CommandResult {
#[description = "Check your own or someone else's best record on the last beatmap."]
#[max_args(1)]
pub fn check(ctx: &mut Context, msg: &Message, mut args: Args) -> CommandResult {
let mut data = ctx.data.write();
let bm = cache::get_beatmap(&mut *data, msg.channel_id)?;
let bm = cache::get_beatmap(&*ctx.data.read(), msg.channel_id)?;
match bm {
None => {
@ -282,10 +271,13 @@ pub fn check(ctx: &mut Context, msg: &Message, mut args: Args) -> CommandResult
Some(bm) => {
let b = &bm.0;
let m = bm.1;
let user =
UsernameArg::to_user_id_query(args.single::<UsernameArg>().ok(), &mut *data, msg)?;
let user = UsernameArg::to_user_id_query(
args.single::<UsernameArg>().ok(),
&*ctx.data.read(),
msg,
)?;
let osu = data.get::<http::Osu>().unwrap().clone();
let osu = ctx.data.read().get::<http::Osu>().unwrap().clone();
let user = osu
.user(user, |f| f)?
@ -319,10 +311,10 @@ pub fn top(ctx: &mut Context, msg: &Message, mut args: Args) -> CommandResult {
.map(|ModeArg(t)| t)
.unwrap_or(Mode::Std);
let mut data = ctx.data.write();
let user = UsernameArg::to_user_id_query(args.single::<UsernameArg>().ok(), &mut *data, msg)?;
let user =
UsernameArg::to_user_id_query(args.single::<UsernameArg>().ok(), &*ctx.data.read(), msg)?;
let osu: OsuClient = data.get::<http::Osu>().unwrap().clone();
let osu: OsuClient = ctx.data.read().get::<http::Osu>().unwrap().clone();
let user = osu
.user(user, |f| f.mode(mode))?
.ok_or(Error::from("User not found"))?;
@ -352,15 +344,15 @@ pub fn top(ctx: &mut Context, msg: &Message, mut args: Args) -> CommandResult {
})?;
// Save the beatmap...
cache::save_beatmap(&mut *data, msg.channel_id, &beatmap)?;
cache::save_beatmap(&*ctx.data.read(), msg.channel_id, &beatmap)?;
Ok(())
}
fn get_user(ctx: &mut Context, msg: &Message, mut args: Args, mode: Mode) -> CommandResult {
let mut data = ctx.data.write();
let user = UsernameArg::to_user_id_query(args.single::<UsernameArg>().ok(), &mut *data, msg)?;
let osu = data.get::<http::Osu>().unwrap().clone();
let user =
UsernameArg::to_user_id_query(args.single::<UsernameArg>().ok(), &*ctx.data.read(), msg)?;
let osu = ctx.data.read().get::<http::Osu>().unwrap().clone();
let user = osu.user(user, |f| f.mode(mode))?;
match user {
Some(u) => {

View file

@ -63,15 +63,15 @@ pub fn setup_db(client: &mut Client) -> Result<(), Error> {
Ok(())
}
pub struct DBWriteGuard<'a, T>(&'a mut FileDatabase<T, Ron>)
pub struct DBWriteGuard<'a, T>(&'a FileDatabase<T, Ron>)
where
T: Send + Sync + Clone + std::fmt::Debug + Serialize + DeserializeOwned;
impl<'a, T> From<&'a mut FileDatabase<T, Ron>> for DBWriteGuard<'a, T>
impl<'a, T> From<&'a FileDatabase<T, Ron>> for DBWriteGuard<'a, T>
where
T: Send + Sync + Clone + std::fmt::Debug + Serialize + DeserializeOwned,
{
fn from(v: &'a mut FileDatabase<T, Ron>) -> Self {
fn from(v: &'a FileDatabase<T, Ron>) -> Self {
DBWriteGuard(v)
}
}
@ -83,9 +83,7 @@ where
pub fn borrow(&self) -> Result<std::sync::RwLockReadGuard<T>, rustbreak::RustbreakError> {
(*self).0.borrow_data()
}
pub fn borrow_mut(
&mut self,
) -> Result<std::sync::RwLockWriteGuard<T>, rustbreak::RustbreakError> {
pub fn borrow_mut(&self) -> Result<std::sync::RwLockWriteGuard<T>, rustbreak::RustbreakError> {
(*self).0.borrow_data_mut()
}
}
@ -112,7 +110,7 @@ impl ServerSoftBans {
// Create a new, implemented role.
pub fn new_implemented(role: RoleId) -> ServerSoftBans {
ServerSoftBans::Implemented(ImplementedSoftBans {
role: role,
role,
periodical_bans: HashMap::new(),
})
}