use arrayvec::ArrayVec;
use serde::{Deserialize, Serialize};
use crate::model::prelude::*;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
enum ParseValue {
Everyone,
Users,
Roles,
}
enum ParseAction {
Remove,
Insert,
}
impl ParseAction {
fn from_allow(allow: bool) -> Self {
if allow {
Self::Insert
} else {
Self::Remove
}
}
}
#[derive(Clone, Debug, Default, Serialize, PartialEq)]
#[must_use]
pub struct CreateAllowedMentions {
parse: ArrayVec<ParseValue, 3>,
users: Vec<UserId>,
roles: Vec<RoleId>,
#[serde(skip_serializing_if = "Option::is_none")]
replied_user: Option<bool>,
}
impl CreateAllowedMentions {
pub fn new() -> Self {
Self::default()
}
fn handle_parse_unique(mut self, value: ParseValue, action: ParseAction) -> Self {
let existing_pos = self.parse.iter().position(|p| *p == value);
match (existing_pos, action) {
(Some(pos), ParseAction::Remove) => drop(self.parse.swap_remove(pos)),
(None, ParseAction::Insert) => self.parse.push(value),
_ => {},
}
self
}
pub fn all_users(self, allow: bool) -> Self {
self.handle_parse_unique(ParseValue::Users, ParseAction::from_allow(allow))
}
pub fn all_roles(self, allow: bool) -> Self {
self.handle_parse_unique(ParseValue::Roles, ParseAction::from_allow(allow))
}
pub fn everyone(self, allow: bool) -> Self {
self.handle_parse_unique(ParseValue::Everyone, ParseAction::from_allow(allow))
}
#[inline]
pub fn users(mut self, users: impl IntoIterator<Item = impl Into<UserId>>) -> Self {
self.users = users.into_iter().map(Into::into).collect();
self
}
#[inline]
pub fn empty_users(mut self) -> Self {
self.users.clear();
self
}
#[inline]
pub fn roles(mut self, roles: impl IntoIterator<Item = impl Into<RoleId>>) -> Self {
self.roles = roles.into_iter().map(Into::into).collect();
self
}
#[inline]
pub fn empty_roles(mut self) -> Self {
self.roles.clear();
self
}
#[inline]
pub fn replied_user(mut self, mention_user: bool) -> Self {
self.replied_user = Some(mention_user);
self
}
}