twilight_validate/channel.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
//! Constants, error types, and functions for validating channel fields.
use std::{
error::Error,
fmt::{Display, Formatter, Result as FmtResult},
};
use twilight_model::channel::ChannelType;
/// Minimum bitrate of a voice channel.
pub const CHANNEL_BITRATE_MIN: u32 = 8000;
/// Maximum number of bulk messages that can be deleted.
pub const CHANNEL_BULK_DELETE_MESSAGES_MAX: usize = 100;
/// Minimum number of bulk messages that can be deleted.
pub const CHANNEL_BULK_DELETE_MESSAGES_MIN: usize = 2;
/// Maximum length of a forum channel's topic.
pub const CHANNEL_FORUM_TOPIC_LENGTH_MAX: usize = 4096;
/// Maximum length of a channel's name.
pub const CHANNEL_NAME_LENGTH_MAX: usize = 100;
/// Minimum length of a channel's name.
pub const CHANNEL_NAME_LENGTH_MIN: usize = 1;
/// Maximum length of a channel's rate limit per user.
pub const CHANNEL_RATE_LIMIT_PER_USER_MAX: u16 = 21_600;
/// Maximum number of members that can be returned in a thread.
pub const CHANNEL_THREAD_GET_MEMBERS_LIMIT_MAX: u32 = 100;
/// Minimum number of members that can be returned in a thread.
pub const CHANNEL_THREAD_GET_MEMBERS_LIMIT_MIN: u32 = 1;
/// Maximum length of a channel's topic.
pub const CHANNEL_TOPIC_LENGTH_MAX: usize = 1024;
/// Maximum user limit of an audio channel.
pub const CHANNEL_USER_LIMIT_MAX: u16 = 99;
/// Returned when the channel can not be updated as configured.
#[derive(Debug)]
pub struct ChannelValidationError {
/// Type of error that occurred.
kind: ChannelValidationErrorType,
}
impl ChannelValidationError {
/// Immutable reference to the type of error that occurred.
#[must_use = "retrieving the type has no effect if left unused"]
pub const fn kind(&self) -> &ChannelValidationErrorType {
&self.kind
}
/// Consume the error, returning the source error if there is any.
#[allow(clippy::unused_self)]
#[must_use = "consuming the error and retrieving the source has no effect if left unused"]
pub fn into_source(self) -> Option<Box<dyn Error + Send + Sync>> {
None
}
/// Consume the error, returning the owned error type and the source error.
#[must_use = "consuming the error into its parts has no effect if left unused"]
pub fn into_parts(
self,
) -> (
ChannelValidationErrorType,
Option<Box<dyn Error + Send + Sync>>,
) {
(self.kind, None)
}
}
impl Display for ChannelValidationError {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
match &self.kind {
ChannelValidationErrorType::BitrateInvalid => {
f.write_str("bitrate is less than ")?;
Display::fmt(&CHANNEL_BITRATE_MIN, f)
}
ChannelValidationErrorType::BulkDeleteMessagesInvalid => {
f.write_str("number of messages deleted in bulk is less than ")?;
Display::fmt(&CHANNEL_BULK_DELETE_MESSAGES_MIN, f)?;
f.write_str(" or greater than ")?;
Display::fmt(&CHANNEL_BULK_DELETE_MESSAGES_MAX, f)
}
ChannelValidationErrorType::ForumTopicInvalid => {
f.write_str("the forum topic is invalid")
}
ChannelValidationErrorType::NameInvalid => {
f.write_str("the length of the name is invalid")
}
ChannelValidationErrorType::RateLimitPerUserInvalid { .. } => {
f.write_str("the rate limit per user is invalid")
}
ChannelValidationErrorType::ThreadMemberLimitInvalid => {
f.write_str("number of members to return is less than ")?;
Display::fmt(&CHANNEL_THREAD_GET_MEMBERS_LIMIT_MIN, f)?;
f.write_str(" or greater than ")?;
Display::fmt(&CHANNEL_THREAD_GET_MEMBERS_LIMIT_MAX, f)
}
ChannelValidationErrorType::TopicInvalid => f.write_str("the topic is invalid"),
ChannelValidationErrorType::TypeInvalid { kind } => {
Display::fmt(kind.name(), f)?;
f.write_str(" is not a thread")
}
ChannelValidationErrorType::UserLimitInvalid => {
f.write_str("user limit is greater than ")?;
Display::fmt(&CHANNEL_USER_LIMIT_MAX, f)
}
}
}
}
impl Error for ChannelValidationError {}
/// Type of [`ChannelValidationError`] that occurred.
#[derive(Debug)]
#[non_exhaustive]
pub enum ChannelValidationErrorType {
/// The bitrate is less than 8000.
BitrateInvalid,
/// Number of messages being deleted in bulk is invalid.
BulkDeleteMessagesInvalid,
/// The length of the topic is more than 4096 UTF-16 characters.
ForumTopicInvalid,
/// The length of the name is either fewer than 1 UTF-16 characters or
/// more than 100 UTF-16 characters.
NameInvalid,
/// The seconds of the rate limit per user is more than 21600.
RateLimitPerUserInvalid {
/// Provided ratelimit is invalid.
rate_limit_per_user: u16,
},
/// The number of members to return is less than 1 or greater than 100.
ThreadMemberLimitInvalid,
/// The length of the topic is more than 1024 UTF-16 characters.
TopicInvalid,
/// Provided type was not a thread.
TypeInvalid {
/// Provided type.
kind: ChannelType,
},
/// User limit is greater than 99.
UserLimitInvalid,
}
/// Ensure a channel's bitrate is collect.
///
/// Must be at least 8000.
///
/// # Errors
///
/// Returns an error of type [`BitrateInvalid`] if the bitrate is invalid.
///
/// [`BitrateInvalid`]: ChannelValidationErrorType::BitrateInvalid
pub const fn bitrate(value: u32) -> Result<(), ChannelValidationError> {
if value >= CHANNEL_BITRATE_MIN {
Ok(())
} else {
Err(ChannelValidationError {
kind: ChannelValidationErrorType::BitrateInvalid,
})
}
}
/// Ensure the number of messages to delete in bulk is correct.
///
/// # Errors
///
/// Returns an error of type [`BulkDeleteMessagesInvalid`] if the number of
/// messages to delete in bulk is invalid.
///
/// [`BulkDeleteMessagesInvalid`]: ChannelValidationErrorType::BulkDeleteMessagesInvalid
pub const fn bulk_delete_messages(message_count: usize) -> Result<(), ChannelValidationError> {
if message_count >= CHANNEL_BULK_DELETE_MESSAGES_MIN
&& message_count <= CHANNEL_BULK_DELETE_MESSAGES_MAX
{
Ok(())
} else {
Err(ChannelValidationError {
kind: ChannelValidationErrorType::BulkDeleteMessagesInvalid,
})
}
}
/// Ensure a channel is a thread.
///
/// # Errors
///
/// Returns an error of type [`ChannelValidationErrorType::TypeInvalid`] if the
/// channel is not a thread.
pub const fn is_thread(kind: ChannelType) -> Result<(), ChannelValidationError> {
if matches!(
kind,
ChannelType::AnnouncementThread | ChannelType::PublicThread | ChannelType::PrivateThread
) {
Ok(())
} else {
Err(ChannelValidationError {
kind: ChannelValidationErrorType::TypeInvalid { kind },
})
}
}
/// Ensure a forum channel's topic's length is correct.
///
/// # Errors
///
/// Returns an error of type [`TopicInvalid`] if the
/// topic is invalid.
///
/// [`TopicInvalid`]: ChannelValidationErrorType::TopicInvalid
pub fn forum_topic(value: impl AsRef<str>) -> Result<(), ChannelValidationError> {
let count = value.as_ref().chars().count();
if count <= CHANNEL_FORUM_TOPIC_LENGTH_MAX {
Ok(())
} else {
Err(ChannelValidationError {
kind: ChannelValidationErrorType::TopicInvalid,
})
}
}
/// Ensure a channel's name's length is correct.
///
/// The length must be less than [`CHANNEL_NAME_LENGTH_MIN`] and at most
/// [`CHANNEL_NAME_LENGTH_MAX`]. This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`NameInvalid`] if the channel's name's length is
/// incorrect.
///
/// [`NameInvalid`]: ChannelValidationErrorType::NameInvalid
/// [this documentation entry]: https://discord.com/developers/docs/resources/channel#channels-resource
pub fn name(value: impl AsRef<str>) -> Result<(), ChannelValidationError> {
let len = value.as_ref().chars().count();
if (CHANNEL_NAME_LENGTH_MIN..=CHANNEL_NAME_LENGTH_MAX).contains(&len) {
Ok(())
} else {
Err(ChannelValidationError {
kind: ChannelValidationErrorType::NameInvalid,
})
}
}
/// Ensure a channel's rate limit per user is correct.
///
/// The value must be at most [`CHANNEL_RATE_LIMIT_PER_USER_MAX`]. This is based
/// on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`RateLimitPerUserInvalid`] if the rate limit is
/// invalid.
///
/// [`RateLimitPerUserInvalid`]: ChannelValidationErrorType::RateLimitPerUserInvalid
/// [this documentation entry]: https://discord.com/developers/docs/resources/channel#channels-resource
pub const fn rate_limit_per_user(value: u16) -> Result<(), ChannelValidationError> {
if value <= CHANNEL_RATE_LIMIT_PER_USER_MAX {
Ok(())
} else {
Err(ChannelValidationError {
kind: ChannelValidationErrorType::RateLimitPerUserInvalid {
rate_limit_per_user: value,
},
})
}
}
/// Ensure the limit set for the number of thread members to return is correct.
///
/// The value must be at least [`CHANNEL_THREAD_GET_MEMBERS_LIMIT_MIN`] and at most
/// [`CHANNEL_THREAD_GET_MEMBERS_LIMIT_MAX`]. This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`ThreadMemberLimitInvalid`] if the limit is invalid.
///
/// [`ThreadMemberLimitInvalid`]: ChannelValidationErrorType::ThreadMemberLimitInvalid
/// [this documentation entry]: https://discord.com/developers/docs/resources/channel#list-thread-members-query-string-params
pub const fn thread_member_limit(value: u32) -> Result<(), ChannelValidationError> {
if value >= CHANNEL_THREAD_GET_MEMBERS_LIMIT_MIN
&& value <= CHANNEL_THREAD_GET_MEMBERS_LIMIT_MAX
{
Ok(())
} else {
Err(ChannelValidationError {
kind: ChannelValidationErrorType::ThreadMemberLimitInvalid,
})
}
}
/// Ensure a channel's topic's length is correct.
///
/// # Errors
///
/// Returns an error of type [`TopicInvalid`] if the
/// topic is invalid.
///
/// [`TopicInvalid`]: ChannelValidationErrorType::TopicInvalid
pub fn topic(value: impl AsRef<str>) -> Result<(), ChannelValidationError> {
let count = value.as_ref().chars().count();
if count <= CHANNEL_TOPIC_LENGTH_MAX {
Ok(())
} else {
Err(ChannelValidationError {
kind: ChannelValidationErrorType::TopicInvalid,
})
}
}
/// Ensure a channel's user limit is correct.
///
/// Must be at most 99.
///
/// # Errors
///
/// Returns an error of type [`UserLimitInvalid`] if the user limit is invalid.
///
/// [`UserLimitInvalid`]: ChannelValidationErrorType::BitrateInvalid
pub const fn user_limit(value: u16) -> Result<(), ChannelValidationError> {
if value <= CHANNEL_USER_LIMIT_MAX {
Ok(())
} else {
Err(ChannelValidationError {
kind: ChannelValidationErrorType::UserLimitInvalid,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bulk_delete_messages() {
assert!(matches!(
super::bulk_delete_messages(0).unwrap_err().kind(),
ChannelValidationErrorType::BulkDeleteMessagesInvalid,
));
assert!(matches!(
super::bulk_delete_messages(1).unwrap_err().kind(),
ChannelValidationErrorType::BulkDeleteMessagesInvalid,
));
assert!(super::bulk_delete_messages(100).is_ok());
assert!(matches!(
super::bulk_delete_messages(101).unwrap_err().kind(),
ChannelValidationErrorType::BulkDeleteMessagesInvalid,
));
}
#[test]
fn channel_bitrate() {
assert!(bitrate(8000).is_ok());
assert!(bitrate(7000).is_err());
}
#[test]
fn thread_is_thread() {
assert!(is_thread(ChannelType::AnnouncementThread).is_ok());
assert!(is_thread(ChannelType::PrivateThread).is_ok());
assert!(is_thread(ChannelType::PublicThread).is_ok());
assert!(is_thread(ChannelType::Group).is_err());
}
#[test]
fn channel_name() {
assert!(name("a").is_ok());
assert!(name("a".repeat(100)).is_ok());
assert!(name("").is_err());
assert!(name("a".repeat(101)).is_err());
}
#[test]
fn rate_limit_per_user_value() {
assert!(rate_limit_per_user(0).is_ok());
assert!(rate_limit_per_user(21_600).is_ok());
assert!(rate_limit_per_user(21_601).is_err());
}
#[test]
fn thread_member_limit_value() {
assert!(thread_member_limit(1).is_ok());
assert!(thread_member_limit(100).is_ok());
assert!(thread_member_limit(50).is_ok());
assert!(thread_member_limit(0).is_err());
assert!(thread_member_limit(101).is_err());
}
#[test]
fn topic_length() {
assert!(topic("").is_ok());
assert!(topic("a").is_ok());
assert!(topic("a".repeat(1_024)).is_ok());
assert!(topic("a".repeat(1_025)).is_err());
}
#[test]
fn user_limit() {
assert!(super::user_limit(0).is_ok());
assert!(super::user_limit(99).is_ok());
assert!(matches!(
super::user_limit(100).unwrap_err().kind(),
ChannelValidationErrorType::UserLimitInvalid
));
}
}