Skip to main content

twilight_validate/
search_guild_messages.rs

1//! Constants, error types, and functions for validating the query parameters of
2//! the Search Guild Messages HTTP request.
3//!
4//! All constants are based on the values provided in the documentation for the
5//! request located at [Discord Docs/Search Guild Messages][docs].
6//!
7//! [docs]: https://docs.discord.com/developers/resources/message#search-guild-messages-query-string-params
8
9use std::{
10    error::Error,
11    fmt::{Display, Formatter, Result as FmtResult},
12};
13use twilight_model::id::{
14    Id,
15    marker::{ChannelMarker, MessageMarker, RoleMarker, UserMarker},
16};
17
18/// Maximum length of an individual attachment extension entry.
19pub const ATTACHMENT_EXTENSION_ENTRY_MAX: usize = 256;
20
21/// Maximum number of attachment extensions to filter by.
22pub const ATTACHMENT_EXTENSION_LIMIT: usize = 100;
23
24/// Maximum length of an individual attachment filename entry.
25pub const ATTACHMENT_FILENAME_ENTRY_MAX: usize = 1024;
26
27/// Maximum number of attachment filenames to filter by.
28pub const ATTACHMENT_FILENAME_LIMIT: usize = 100;
29
30/// Maximum number of author IDs to filter by.
31pub const AUTHOR_ID_LIMIT: usize = 100;
32
33/// Maximum length of content.
34pub const CONTENT_LENGTH_MAX: usize = 1024;
35
36/// Maximum number of channel IDs to filter by.
37pub const CHANNEL_ID_LIMIT: usize = 500;
38
39/// Maximum length of an individual embed provider entry.
40pub const EMBED_PROVIDER_ENTRY_MAX: usize = 256;
41
42/// Maximum number of embed providers to filter by.
43pub const EMBED_PROVIDER_LIMIT: usize = 100;
44
45/// Maximum amount of messages to get.
46pub const LIMIT_MAX: usize = 25;
47
48/// Minimum amount of messages to get.
49pub const LIMIT_MIN: usize = 1;
50
51/// Maximum length of an individual link hostname entry.
52pub const LINK_HOSTNAME_ENTRY_MAX: usize = 256;
53
54/// Maximum number of link hostnames to filter by.
55pub const LINK_HOSTNAME_LIMIT: usize = 100;
56
57/// Maximum number of user mentions to filter by.
58pub const MENTIONS_LIMIT: usize = 100;
59
60/// Maximum number of role mentions to filter by.
61pub const MENTIONS_ROLE_ID_LIMIT: usize = 100;
62
63/// Maximum offset of messages.
64pub const OFFSET_MAX: usize = 9975;
65
66/// Maximum number of replied messages to filter by.
67pub const REPLIED_TO_MESSAGE_ID_LIMIT: usize = 100;
68
69/// Maximum number of replied users to filter by.
70pub const REPLIED_TO_USER_ID_LIMIT: usize = 100;
71
72/// Maximum amount of slop.
73pub const SLOP_MAX: usize = 100;
74
75/// A message is not valid.
76#[derive(Debug)]
77pub struct SearchGuildMessagesError {
78    /// Type of error that occurred.
79    kind: SearchGuildMessagesErrorType,
80}
81
82impl SearchGuildMessagesError {
83    /// Immutable reference to the type of error that occurred.
84    #[must_use = "retrieving the type has no effect if left unused"]
85    pub const fn kind(&self) -> &SearchGuildMessagesErrorType {
86        &self.kind
87    }
88
89    /// Consume the error, returning the source error if there is any.
90    #[must_use = "consuming the error and retrieving the source has no effect if left unused"]
91    pub fn into_source(self) -> Option<Box<dyn Error + Send + Sync>> {
92        None
93    }
94
95    /// Consume the error, returning the owned error type and the source error.
96    #[must_use = "consuming the error into its parts has no effect if left unused"]
97    pub fn into_parts(
98        self,
99    ) -> (
100        SearchGuildMessagesErrorType,
101        Option<Box<dyn Error + Send + Sync>>,
102    ) {
103        (self.kind, None)
104    }
105}
106
107#[expect(clippy::too_many_lines)]
108impl Display for SearchGuildMessagesError {
109    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
110        match &self.kind {
111            SearchGuildMessagesErrorType::AttachmentExtensionCount { count } => {
112                f.write_str("amount of attachment extensions provided is ")?;
113                Display::fmt(count, f)?;
114                f.write_str(" but must be at most ")?;
115
116                Display::fmt(&ATTACHMENT_EXTENSION_LIMIT, f)
117            }
118            SearchGuildMessagesErrorType::AttachmentExtensionEntryLength { index, value } => {
119                f.write_str("attachment extension entry at index ")?;
120                Display::fmt(index, f)?;
121                f.write_str(" is ")?;
122                Display::fmt(value, f)?;
123                f.write_str(" characters long but must be at most ")?;
124                Display::fmt(&ATTACHMENT_EXTENSION_ENTRY_MAX, f)?;
125
126                f.write_str(" characters long")
127            }
128            SearchGuildMessagesErrorType::AttachmentFilenameCount { count } => {
129                f.write_str("amount of attachment filenames provided is ")?;
130                Display::fmt(count, f)?;
131                f.write_str(" but must be at most ")?;
132
133                Display::fmt(&ATTACHMENT_FILENAME_LIMIT, f)
134            }
135            SearchGuildMessagesErrorType::AttachmentFilenameEntryLength { index, value } => {
136                f.write_str("attachment filename entry at index ")?;
137                Display::fmt(index, f)?;
138                f.write_str(" is ")?;
139                Display::fmt(value, f)?;
140                f.write_str(" characters long but must be at most ")?;
141                Display::fmt(&ATTACHMENT_FILENAME_ENTRY_MAX, f)?;
142
143                f.write_str(" characters long")
144            }
145            SearchGuildMessagesErrorType::AuthorIdCount { count } => {
146                f.write_str("amount of author IDs provided is ")?;
147                Display::fmt(count, f)?;
148                f.write_str(" but must be at most ")?;
149
150                Display::fmt(&AUTHOR_ID_LIMIT, f)
151            }
152            SearchGuildMessagesErrorType::ChannelIdCount { count } => {
153                f.write_str("amount of channel IDs provided is ")?;
154                Display::fmt(count, f)?;
155                f.write_str(" but must be at most ")?;
156
157                Display::fmt(&CHANNEL_ID_LIMIT, f)
158            }
159            SearchGuildMessagesErrorType::ContentLength { value } => {
160                f.write_str("content is ")?;
161                Display::fmt(value, f)?;
162                f.write_str(" characters long but must be at most ")?;
163                Display::fmt(&CONTENT_LENGTH_MAX, f)?;
164
165                f.write_str(" characters long")
166            }
167            SearchGuildMessagesErrorType::EmbedProviderCount { count } => {
168                f.write_str("amount of embed providers provided is ")?;
169                Display::fmt(count, f)?;
170                f.write_str(" but must be at most ")?;
171
172                Display::fmt(&EMBED_PROVIDER_LIMIT, f)
173            }
174            SearchGuildMessagesErrorType::EmbedProviderEntryLength { index, value } => {
175                f.write_str("embed provider entry at index ")?;
176                Display::fmt(index, f)?;
177                f.write_str(" is ")?;
178                Display::fmt(value, f)?;
179                f.write_str(" characters long but must be at most ")?;
180                Display::fmt(&EMBED_PROVIDER_ENTRY_MAX, f)?;
181
182                f.write_str(" characters long")
183            }
184            SearchGuildMessagesErrorType::Limit { value } => {
185                f.write_str("provided limit is ")?;
186                Display::fmt(value, f)?;
187                f.write_str(" but it must be at least ")?;
188                Display::fmt(&LIMIT_MIN, f)?;
189                f.write_str(" and at most ")?;
190
191                Display::fmt(&LIMIT_MAX, f)
192            }
193            SearchGuildMessagesErrorType::LinkHostnameCount { count } => {
194                f.write_str("amount of link hostnames provided is ")?;
195                Display::fmt(count, f)?;
196                f.write_str(" but must be at most ")?;
197
198                Display::fmt(&LINK_HOSTNAME_LIMIT, f)
199            }
200            SearchGuildMessagesErrorType::LinkHostnameEntryLength { index, value } => {
201                f.write_str("link hostname entry at index ")?;
202                Display::fmt(index, f)?;
203                f.write_str(" is ")?;
204                Display::fmt(value, f)?;
205                f.write_str(" characters long but must be at most ")?;
206                Display::fmt(&LINK_HOSTNAME_ENTRY_MAX, f)?;
207
208                f.write_str(" characters long")
209            }
210            SearchGuildMessagesErrorType::MentionsCount { count } => {
211                f.write_str("amount of mentions provided is ")?;
212                Display::fmt(count, f)?;
213                f.write_str(" but must be at most ")?;
214
215                Display::fmt(&MENTIONS_LIMIT, f)
216            }
217            SearchGuildMessagesErrorType::MentionsRoleIdCount { count } => {
218                f.write_str("amount of mention role IDs provided is ")?;
219                Display::fmt(count, f)?;
220                f.write_str(" but must be at most ")?;
221
222                Display::fmt(&MENTIONS_ROLE_ID_LIMIT, f)
223            }
224            SearchGuildMessagesErrorType::Offset { value } => {
225                f.write_str("provided offset is ")?;
226                Display::fmt(value, f)?;
227                f.write_str(" but must be at most ")?;
228
229                Display::fmt(&OFFSET_MAX, f)
230            }
231            SearchGuildMessagesErrorType::RepliedToMessageIdCount { count } => {
232                f.write_str("amount of replied to message IDs provided is ")?;
233                Display::fmt(count, f)?;
234                f.write_str(" but must be at most ")?;
235
236                Display::fmt(&REPLIED_TO_MESSAGE_ID_LIMIT, f)
237            }
238            SearchGuildMessagesErrorType::RepliedToUserIdCount { count } => {
239                f.write_str("amount of replied to user IDs provided is ")?;
240                Display::fmt(count, f)?;
241                f.write_str(" but must be at most ")?;
242
243                Display::fmt(&REPLIED_TO_USER_ID_LIMIT, f)
244            }
245            SearchGuildMessagesErrorType::Slop { value } => {
246                f.write_str("provided slop is ")?;
247                Display::fmt(value, f)?;
248                f.write_str(" but it must be at most ")?;
249
250                Display::fmt(&SLOP_MAX, f)
251            }
252        }
253    }
254}
255
256impl Error for SearchGuildMessagesError {}
257
258/// Type of [`SearchGuildMessagesError`] that occurred.
259#[derive(Debug)]
260#[non_exhaustive]
261pub enum SearchGuildMessagesErrorType {
262    /// Number of attachment extensions is invalid.
263    AttachmentExtensionCount {
264        /// Invalid count.
265        count: usize,
266    },
267    /// Length of an attachment extension entry is invalid.
268    AttachmentExtensionEntryLength {
269        /// Index of the first invalid entry.
270        index: usize,
271        /// Invalid length.
272        value: usize,
273    },
274    /// Number of attachment filenames is invalid.
275    AttachmentFilenameCount {
276        /// Invalid count.
277        count: usize,
278    },
279    /// Length of an attachment filename entry is invalid.
280    AttachmentFilenameEntryLength {
281        /// Index of the first invalid entry.
282        index: usize,
283        /// Invalid length.
284        value: usize,
285    },
286    /// Number of author IDs is invalid.
287    AuthorIdCount {
288        /// Invalid count.
289        count: usize,
290    },
291    /// Number of channel IDs is invalid.
292    ChannelIdCount {
293        /// Invalid count.
294        count: usize,
295    },
296    /// Length of content is invalid.
297    ContentLength {
298        /// Invalid length.
299        value: usize,
300    },
301    /// Number of embed providers is invalid.
302    EmbedProviderCount {
303        /// Invalid count.
304        count: usize,
305    },
306    /// Length of an embed provider entry is invalid.
307    EmbedProviderEntryLength {
308        /// Index of the first invalid entry.
309        index: usize,
310        /// Invalid length.
311        value: usize,
312    },
313    /// Number of messages to return is too small or too large.
314    Limit {
315        /// Invalid value.
316        value: usize,
317    },
318    /// Length of a link hostname entry is invalid.
319    LinkHostnameEntryLength {
320        /// Index of the first invalid entry.
321        index: usize,
322        /// Invalid length.
323        value: usize,
324    },
325    /// Number of link hostnames is invalid.
326    LinkHostnameCount {
327        /// Invalid count.
328        count: usize,
329    },
330    /// Number of mentions is invalid.
331    MentionsCount {
332        /// Invalid count.
333        count: usize,
334    },
335    /// Number of mention roles is invalid.
336    MentionsRoleIdCount {
337        /// Invalid count.
338        count: usize,
339    },
340    /// Number of messages to offset by is invalid.
341    Offset {
342        /// Invalid value.
343        value: usize,
344    },
345    /// Number of replied messages is invalid.
346    RepliedToMessageIdCount {
347        /// Invalid count.
348        count: usize,
349    },
350    /// Number of replied users is invalid.
351    RepliedToUserIdCount {
352        /// Invalid count.
353        count: usize,
354    },
355    /// Amount of slop is invalid.
356    Slop {
357        /// Invalid value.
358        value: usize,
359    },
360}
361
362/// Ensure a list of attachment extensions is correct.
363///
364/// # Errors
365///
366/// Returns an error of type [`AttachmentExtensionCount`] if the number of
367/// attachment extension entries is invalid.
368///
369/// Returns an error of type [`AttachmentExtensionEntryLength`] if one of the
370/// attachment extension entries has an invalid length.
371///
372/// [`AttachmentExtensionCount`]: SearchGuildMessagesErrorType::AttachmentExtensionCount
373/// [`AttachmentExtensionEntryLength`]: SearchGuildMessagesErrorType::AttachmentExtensionEntryLength
374pub fn attachment_extension(attachment_extension: &[&str]) -> Result<(), SearchGuildMessagesError> {
375    if attachment_extension.len() > ATTACHMENT_EXTENSION_LIMIT {
376        return Err(SearchGuildMessagesError {
377            kind: SearchGuildMessagesErrorType::AttachmentExtensionCount {
378                count: attachment_extension.len(),
379            },
380        });
381    }
382
383    for (index, entry) in attachment_extension.iter().enumerate() {
384        let length = entry.chars().count();
385
386        if length > ATTACHMENT_EXTENSION_ENTRY_MAX {
387            return Err(SearchGuildMessagesError {
388                kind: SearchGuildMessagesErrorType::AttachmentExtensionEntryLength {
389                    index,
390                    value: length,
391                },
392            });
393        }
394    }
395
396    Ok(())
397}
398
399/// Ensure a list of attachment filenames is correct.
400///
401/// # Errors
402///
403/// Returns an error of type [`AttachmentFilenameCount`] if the number of
404/// attachment filename entries is invalid.
405///
406/// Returns an error of type [`AttachmentFilenameEntryLength`] if one of the
407/// attachment filename entries has an invalid length.
408///
409/// [`AttachmentFilenameCount`]: SearchGuildMessagesErrorType::AttachmentFilenameCount
410/// [`AttachmentFilenameEntryLength`]: SearchGuildMessagesErrorType::AttachmentFilenameEntryLength
411pub fn attachment_filename(attachment_filename: &[&str]) -> Result<(), SearchGuildMessagesError> {
412    if attachment_filename.len() > ATTACHMENT_FILENAME_LIMIT {
413        return Err(SearchGuildMessagesError {
414            kind: SearchGuildMessagesErrorType::AttachmentFilenameCount {
415                count: attachment_filename.len(),
416            },
417        });
418    }
419
420    for (index, entry) in attachment_filename.iter().enumerate() {
421        let length = entry.chars().count();
422
423        if length > ATTACHMENT_FILENAME_ENTRY_MAX {
424            return Err(SearchGuildMessagesError {
425                kind: SearchGuildMessagesErrorType::AttachmentFilenameEntryLength {
426                    index,
427                    value: length,
428                },
429            });
430        }
431    }
432
433    Ok(())
434}
435
436/// Ensure that the amount of author IDs is correct.
437///
438/// # Errors
439///
440/// Returns an error of type [`AuthorIdCount`] if the number of author IDs is
441/// invalid.
442///
443/// [`AuthorIdCount`]: SearchGuildMessagesErrorType::AuthorIdCount
444pub const fn author_id(author_id: &[Id<UserMarker>]) -> Result<(), SearchGuildMessagesError> {
445    if author_id.len() > AUTHOR_ID_LIMIT {
446        return Err(SearchGuildMessagesError {
447            kind: SearchGuildMessagesErrorType::AuthorIdCount {
448                count: author_id.len(),
449            },
450        });
451    }
452
453    Ok(())
454}
455
456/// Ensure that the amount of channel IDs is correct.
457///
458/// # Errors
459///
460/// Returns an error of type [`ChannelIdCount`] if the number of channel IDs is
461/// invalid.
462///
463/// [`ChannelIdCount`]: SearchGuildMessagesErrorType::ChannelIdCount
464pub const fn channel_id(channel_id: &[Id<ChannelMarker>]) -> Result<(), SearchGuildMessagesError> {
465    if channel_id.len() > CHANNEL_ID_LIMIT {
466        return Err(SearchGuildMessagesError {
467            kind: SearchGuildMessagesErrorType::ChannelIdCount {
468                count: channel_id.len(),
469            },
470        });
471    }
472
473    Ok(())
474}
475
476/// Ensure the content is correct.
477///
478/// # Errors
479///
480/// Returns an error of type [`ContentLength`] is the content is too long.
481///
482/// [`ContentLength`]: SearchGuildMessagesErrorType::ContentLength
483pub fn content(content: &str) -> Result<(), SearchGuildMessagesError> {
484    let length = content.chars().count();
485
486    if length > CONTENT_LENGTH_MAX {
487        return Err(SearchGuildMessagesError {
488            kind: SearchGuildMessagesErrorType::ContentLength { value: length },
489        });
490    }
491
492    Ok(())
493}
494
495/// Ensure a list of embed providers is correct.
496///
497/// # Errors
498///
499/// Returns an error of type [`EmbedProviderCount`] if the number of
500/// embed provider entries is invalid.
501///
502/// Returns an error of type [`EmbedProviderEntryLength`] if one of the
503/// embed provider entries has an invalid length.
504///
505/// [`EmbedProviderCount`]: SearchGuildMessagesErrorType::EmbedProviderCount
506/// [`EmbedProviderEntryLength`]: SearchGuildMessagesErrorType::EmbedProviderEntryLength
507pub fn embed_provider(embed_provider: &[&str]) -> Result<(), SearchGuildMessagesError> {
508    if embed_provider.len() > EMBED_PROVIDER_LIMIT {
509        return Err(SearchGuildMessagesError {
510            kind: SearchGuildMessagesErrorType::EmbedProviderCount {
511                count: embed_provider.len(),
512            },
513        });
514    }
515
516    for (index, entry) in embed_provider.iter().enumerate() {
517        let length = entry.chars().count();
518
519        if length > EMBED_PROVIDER_ENTRY_MAX {
520            return Err(SearchGuildMessagesError {
521                kind: SearchGuildMessagesErrorType::EmbedProviderEntryLength {
522                    index,
523                    value: length,
524                },
525            });
526        }
527    }
528
529    Ok(())
530}
531
532/// Ensure that the limit is correct.
533///
534/// The limit must be at least [`LIMIT_MIN`] and at most [`LIMIT_MAX`].
535///
536/// # Errors
537///
538/// Returns an error of type [`Limit`] if the limit is invalid.
539///
540/// [`Limit`]: SearchGuildMessagesErrorType::Limit
541pub const fn limit(value: usize) -> Result<(), SearchGuildMessagesError> {
542    if value < LIMIT_MIN || value > LIMIT_MAX {
543        return Err(SearchGuildMessagesError {
544            kind: SearchGuildMessagesErrorType::Limit { value },
545        });
546    }
547
548    Ok(())
549}
550
551/// Ensure a list of link hostnames is correct.
552///
553/// # Errors
554///
555/// Returns an error of type [`LinkHostnameCount`] if the number of
556/// link hostname entries is invalid.
557///
558/// Returns an error of type [`LinkHostnameEntryLength`] if one of the
559/// link hostname entries has an invalid length.
560///
561/// [`LinkHostnameCount`]: SearchGuildMessagesErrorType::LinkHostnameCount
562/// [`LinkHostnameEntryLength`]: SearchGuildMessagesErrorType::LinkHostnameEntryLength
563pub fn link_hostname(link_hostname: &[&str]) -> Result<(), SearchGuildMessagesError> {
564    if link_hostname.len() > LINK_HOSTNAME_LIMIT {
565        return Err(SearchGuildMessagesError {
566            kind: SearchGuildMessagesErrorType::LinkHostnameCount {
567                count: link_hostname.len(),
568            },
569        });
570    }
571
572    for (index, entry) in link_hostname.iter().enumerate() {
573        let length = entry.chars().count();
574
575        if length > LINK_HOSTNAME_ENTRY_MAX {
576            return Err(SearchGuildMessagesError {
577                kind: SearchGuildMessagesErrorType::LinkHostnameEntryLength {
578                    index,
579                    value: length,
580                },
581            });
582        }
583    }
584
585    Ok(())
586}
587
588/// Ensure that the amount of mentions is correct.
589///
590/// # Errors
591///
592/// Returns an error of type [`MentionsCount`] if the number of mentions is
593/// invalid.
594///
595/// [`MentionsCount`]: SearchGuildMessagesErrorType::MentionsCount
596pub const fn mentions(mentions: &[Id<UserMarker>]) -> Result<(), SearchGuildMessagesError> {
597    if mentions.len() > MENTIONS_LIMIT {
598        return Err(SearchGuildMessagesError {
599            kind: SearchGuildMessagesErrorType::MentionsCount {
600                count: mentions.len(),
601            },
602        });
603    }
604
605    Ok(())
606}
607
608/// Ensure that the amount of mention roles is correct.
609///
610/// # Errors
611///
612/// Returns an error of type [`MentionsRoleIdCount`] if the number of mention
613/// roles is invalid.
614///
615/// [`MentionsRoleIdCount`]: SearchGuildMessagesErrorType::MentionsRoleIdCount
616pub const fn mentions_role_id(
617    mentions_role_id: &[Id<RoleMarker>],
618) -> Result<(), SearchGuildMessagesError> {
619    if mentions_role_id.len() > MENTIONS_ROLE_ID_LIMIT {
620        return Err(SearchGuildMessagesError {
621            kind: SearchGuildMessagesErrorType::MentionsRoleIdCount {
622                count: mentions_role_id.len(),
623            },
624        });
625    }
626
627    Ok(())
628}
629
630/// Ensure that the offset is correct.
631///
632/// The offset must be at most [`OFFSET_MAX`].
633///
634/// # Errors
635///
636/// Returns an error of type [`Offset`] if the offset is invalid.
637///
638/// [`Offset`]: SearchGuildMessagesErrorType::Offset
639pub const fn offset(value: usize) -> Result<(), SearchGuildMessagesError> {
640    if value > OFFSET_MAX {
641        return Err(SearchGuildMessagesError {
642            kind: SearchGuildMessagesErrorType::Offset { value },
643        });
644    }
645
646    Ok(())
647}
648
649/// Ensure that the amount of replied to message IDs is correct.
650///
651/// # Errors
652///
653/// Returns an error of type [`RepliedToMessageIdCount`] if the number of
654/// replied to message IDs is invalid.
655///
656/// [`RepliedToMessageIdCount`]: SearchGuildMessagesErrorType::RepliedToMessageIdCount
657pub const fn replied_to_message_id(
658    replied_to_message_id: &[Id<MessageMarker>],
659) -> Result<(), SearchGuildMessagesError> {
660    if replied_to_message_id.len() > REPLIED_TO_MESSAGE_ID_LIMIT {
661        return Err(SearchGuildMessagesError {
662            kind: SearchGuildMessagesErrorType::RepliedToMessageIdCount {
663                count: replied_to_message_id.len(),
664            },
665        });
666    }
667
668    Ok(())
669}
670
671/// Ensure that the amount of replied to user IDs is correct.
672///
673/// # Errors
674///
675/// Returns an error of type [`RepliedToUserIdCount`] if the number of replied
676/// to user IDs is invalid.
677///
678/// [`RepliedToUserIdCount`]: SearchGuildMessagesErrorType::RepliedToUserIdCount
679pub const fn replied_to_user_id(
680    replied_to_user_id: &[Id<UserMarker>],
681) -> Result<(), SearchGuildMessagesError> {
682    if replied_to_user_id.len() > REPLIED_TO_USER_ID_LIMIT {
683        return Err(SearchGuildMessagesError {
684            kind: SearchGuildMessagesErrorType::RepliedToUserIdCount {
685                count: replied_to_user_id.len(),
686            },
687        });
688    }
689
690    Ok(())
691}
692
693/// Ensure that the slop is correct.
694///
695/// The slop must be at most [`SLOP_MAX`].
696///
697/// # Errors
698///
699/// Returns an error of type [`Slop`] if the slop is invalid.
700///
701/// [`Slop`]: SearchGuildMessagesErrorType::Slop
702pub const fn slop(value: usize) -> Result<(), SearchGuildMessagesError> {
703    if value > SLOP_MAX {
704        return Err(SearchGuildMessagesError {
705            kind: SearchGuildMessagesErrorType::Slop { value },
706        });
707    }
708
709    Ok(())
710}
711
712#[cfg(test)]
713mod tests {
714    use super::*;
715    use std::iter;
716
717    #[test]
718    fn attachment_extension_limit() {
719        assert!(attachment_extension(&iter::repeat_n("a", 0).collect::<Vec<_>>()).is_ok());
720        assert!(attachment_extension(&iter::repeat_n("a", 1).collect::<Vec<_>>()).is_ok());
721        assert!(attachment_extension(&iter::repeat_n("a", 100).collect::<Vec<_>>()).is_ok());
722        assert!(attachment_extension(&iter::repeat_n("a", 101).collect::<Vec<_>>()).is_err());
723    }
724
725    #[test]
726    fn attachment_extension_entry_limit() {
727        assert!(attachment_extension(&[""]).is_ok());
728        assert!(attachment_extension(&["a"]).is_ok());
729        assert!(attachment_extension(&[&"a".repeat(256)]).is_ok());
730        assert!(attachment_extension(&[&"a".repeat(257)]).is_err());
731    }
732
733    #[test]
734    fn attachment_filename_limit() {
735        assert!(attachment_filename(&iter::repeat_n("a", 0).collect::<Vec<_>>()).is_ok());
736        assert!(attachment_filename(&iter::repeat_n("a", 1).collect::<Vec<_>>()).is_ok());
737        assert!(attachment_filename(&iter::repeat_n("a", 100).collect::<Vec<_>>()).is_ok());
738        assert!(attachment_filename(&iter::repeat_n("a", 101).collect::<Vec<_>>()).is_err());
739    }
740
741    #[test]
742    fn attachment_filename_entry_limit() {
743        assert!(attachment_filename(&[""]).is_ok());
744        assert!(attachment_filename(&["a"]).is_ok());
745        assert!(attachment_filename(&[&"a".repeat(1024)]).is_ok());
746        assert!(attachment_filename(&[&"a".repeat(1025)]).is_err());
747    }
748
749    #[test]
750    fn author_id_limit() {
751        assert!(author_id(&iter::repeat_n(Id::new(1), 0).collect::<Vec<_>>()).is_ok());
752        assert!(author_id(&iter::repeat_n(Id::new(1), 1).collect::<Vec<_>>()).is_ok());
753        assert!(author_id(&iter::repeat_n(Id::new(1), 100).collect::<Vec<_>>()).is_ok());
754        assert!(author_id(&iter::repeat_n(Id::new(1), 101).collect::<Vec<_>>()).is_err());
755    }
756
757    #[test]
758    fn channel_id_limit() {
759        assert!(channel_id(&iter::repeat_n(Id::new(1), 0).collect::<Vec<_>>()).is_ok());
760        assert!(channel_id(&iter::repeat_n(Id::new(1), 1).collect::<Vec<_>>()).is_ok());
761        assert!(channel_id(&iter::repeat_n(Id::new(1), 500).collect::<Vec<_>>()).is_ok());
762        assert!(channel_id(&iter::repeat_n(Id::new(1), 501).collect::<Vec<_>>()).is_err());
763    }
764
765    #[test]
766    fn content_length() {
767        assert!(content("").is_ok());
768        assert!(content("a").is_ok());
769        assert!(content(&"a".repeat(1024)).is_ok());
770        assert!(content(&"a".repeat(1025)).is_err());
771    }
772
773    #[test]
774    fn embed_provider_limit() {
775        assert!(embed_provider(&iter::repeat_n("a", 0).collect::<Vec<_>>()).is_ok());
776        assert!(embed_provider(&iter::repeat_n("a", 1).collect::<Vec<_>>()).is_ok());
777        assert!(embed_provider(&iter::repeat_n("a", 100).collect::<Vec<_>>()).is_ok());
778        assert!(embed_provider(&iter::repeat_n("a", 101).collect::<Vec<_>>()).is_err());
779    }
780
781    #[test]
782    fn embed_provider_entry_limit() {
783        assert!(embed_provider(&[""]).is_ok());
784        assert!(embed_provider(&["a"]).is_ok());
785        assert!(embed_provider(&[&"a".repeat(256)]).is_ok());
786        assert!(embed_provider(&[&"a".repeat(257)]).is_err());
787    }
788
789    #[test]
790    fn limit_count() {
791        assert!(limit(0).is_err());
792        assert!(limit(1).is_ok());
793        assert!(limit(25).is_ok());
794        assert!(limit(26).is_err());
795    }
796
797    #[test]
798    fn link_hostname_limit() {
799        assert!(link_hostname(&iter::repeat_n("a", 0).collect::<Vec<_>>()).is_ok());
800        assert!(link_hostname(&iter::repeat_n("a", 1).collect::<Vec<_>>()).is_ok());
801        assert!(link_hostname(&iter::repeat_n("a", 100).collect::<Vec<_>>()).is_ok());
802        assert!(link_hostname(&iter::repeat_n("a", 101).collect::<Vec<_>>()).is_err());
803    }
804
805    #[test]
806    fn link_hostname_entry_limit() {
807        assert!(link_hostname(&[""]).is_ok());
808        assert!(link_hostname(&["a"]).is_ok());
809        assert!(link_hostname(&[&"a".repeat(256)]).is_ok());
810        assert!(link_hostname(&[&"a".repeat(257)]).is_err());
811    }
812
813    #[test]
814    fn mentions_limit() {
815        assert!(mentions(&iter::repeat_n(Id::new(1), 0).collect::<Vec<_>>()).is_ok());
816        assert!(mentions(&iter::repeat_n(Id::new(1), 1).collect::<Vec<_>>()).is_ok());
817        assert!(mentions(&iter::repeat_n(Id::new(1), 100).collect::<Vec<_>>()).is_ok());
818        assert!(mentions(&iter::repeat_n(Id::new(1), 101).collect::<Vec<_>>()).is_err());
819    }
820
821    #[test]
822    fn mentions_role_id_limit() {
823        assert!(mentions_role_id(&iter::repeat_n(Id::new(1), 0).collect::<Vec<_>>()).is_ok());
824        assert!(mentions_role_id(&iter::repeat_n(Id::new(1), 1).collect::<Vec<_>>()).is_ok());
825        assert!(mentions_role_id(&iter::repeat_n(Id::new(1), 100).collect::<Vec<_>>()).is_ok());
826        assert!(mentions_role_id(&iter::repeat_n(Id::new(1), 101).collect::<Vec<_>>()).is_err());
827    }
828
829    #[test]
830    fn offset_count() {
831        assert!(offset(0).is_ok());
832        assert!(offset(1).is_ok());
833        assert!(offset(9975).is_ok());
834        assert!(offset(9976).is_err());
835    }
836
837    #[test]
838    fn replied_to_message_id_limit() {
839        assert!(replied_to_message_id(&iter::repeat_n(Id::new(1), 0).collect::<Vec<_>>()).is_ok());
840        assert!(replied_to_message_id(&iter::repeat_n(Id::new(1), 1).collect::<Vec<_>>()).is_ok());
841        assert!(
842            replied_to_message_id(&iter::repeat_n(Id::new(1), 100).collect::<Vec<_>>()).is_ok()
843        );
844        assert!(
845            replied_to_message_id(&iter::repeat_n(Id::new(1), 101).collect::<Vec<_>>()).is_err()
846        );
847    }
848
849    #[test]
850    fn replied_to_user_id_limit() {
851        assert!(replied_to_user_id(&iter::repeat_n(Id::new(1), 0).collect::<Vec<_>>()).is_ok());
852        assert!(replied_to_user_id(&iter::repeat_n(Id::new(1), 1).collect::<Vec<_>>()).is_ok());
853        assert!(replied_to_user_id(&iter::repeat_n(Id::new(1), 100).collect::<Vec<_>>()).is_ok());
854        assert!(replied_to_user_id(&iter::repeat_n(Id::new(1), 101).collect::<Vec<_>>()).is_err());
855    }
856
857    #[test]
858    fn slop_count() {
859        assert!(slop(0).is_ok());
860        assert!(slop(1).is_ok());
861        assert!(slop(100).is_ok());
862        assert!(slop(101).is_err());
863    }
864}