memes in config may now be lowercase

This commit is contained in:
LordMZTE 2021-01-15 19:08:38 +01:00
parent 75339638c6
commit 4d592bd3d1
3 changed files with 39 additions and 4 deletions

View file

@ -50,3 +50,4 @@ impl<'de> Deserialize<'de> for Event {
deserializer.deserialize_str(EventVisitor)
}
}

View file

@ -1,14 +1,15 @@
use anyhow::{Context, Result};
use once_cell::sync::OnceCell;
use serde::Deserialize;
use std::{collections::HashMap, path::PathBuf};
use serde::{Deserialize, de::{Deserializer, MapAccess, Visitor}};
use std::{collections::HashMap, path::PathBuf, marker::PhantomData};
use std::fmt;
#[derive(Deserialize)]
pub struct Config {
pub nickname: String,
pub gateways: Vec<String>,
pub api: String,
pub memes: HashMap<String, String>,
pub memes: LowerCaseMap<String>,
}
static CONFIG: OnceCell<Config> = OnceCell::new();
@ -35,3 +36,36 @@ pub async fn try_get_config<'a>() -> Result<&'a Config> {
Some(c) => Ok(c),
}
}
pub struct LowerCaseMap<T> {
pub map: HashMap<String, T>
}
impl<'de, T: Deserialize<'de>> Deserialize<'de> for LowerCaseMap<T> {
fn deserialize<D>(deserializer: D) -> Result<LowerCaseMap<T>, D::Error>
where
D: Deserializer<'de>,
{
struct LowerCaseMapVisitor<T>(PhantomData<T>);
impl<'de, T: Deserialize<'de>> Visitor<'de> for LowerCaseMapVisitor<T> {
type Value = LowerCaseMap<T>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a key-value pair with a string key")
}
fn visit_map<A: MapAccess<'de>>(self, mut access: A) -> Result<Self::Value, A::Error> {
let mut map = HashMap::new();
while let Some((k, v)) = access.next_entry::<String, T>()? {
map.insert(k.to_lowercase(), v);
}
Ok(LowerCaseMap { map })
}
}
deserializer.deserialize_map(LowerCaseMapVisitor(PhantomData))
}
}

View file

@ -122,7 +122,7 @@ async fn process_message(client: &Client, message: Message) -> Result<()> {
return Ok(());
}
if let Some(meme) = config.memes.get(&lower) {
if let Some(meme) = config.memes.map.get(&lower) {
log::info!(
r#"found meme matching message "{}". responding with "{}""#,
text,