code
stringlengths 40
729k
| docstring
stringlengths 22
46.3k
| func_name
stringlengths 1
97
| language
stringclasses 1
value | repo
stringlengths 6
48
| path
stringlengths 8
176
| url
stringlengths 47
228
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
pub fn validate(self) -> Result<Self, EmbedValidationError> {
#[allow(clippy::question_mark)]
if let Err(source) = validate_embed(&self.0) {
return Err(source);
}
Ok(self)
}
|
Ensure the embed is valid.
# Errors
Refer to the documentation of [`twilight_validate::embed::embed`] for
possible errors.
|
validate
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/embed/mod.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/embed/mod.rs
|
ISC
|
pub fn author(mut self, author: impl Into<EmbedAuthor>) -> Self {
self.0.author = Some(author.into());
self
}
|
Set the author.
# Examples
Create an embed author:
```
# fn main() -> Result<(), Box<dyn std::error::Error>> {
use twilight_util::builder::embed::{EmbedAuthorBuilder, EmbedBuilder};
let author = EmbedAuthorBuilder::new("Twilight")
.url("https://github.com/twilight-rs/twilight")
.build();
let embed = EmbedBuilder::new().author(author).validate()?.build();
# Ok(()) }
```
|
author
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/embed/mod.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/embed/mod.rs
|
ISC
|
pub const fn color(mut self, color: u32) -> Self {
self.0.color = Some(color);
self
}
|
Set the color.
This must be a valid hexadecimal RGB value. Refer to
[`COLOR_MAXIMUM`] for the maximum acceptable value.
# Examples
Set the color of an embed to `0xfd69b3`:
```
# fn main() -> Result<(), Box<dyn std::error::Error>> {
use twilight_util::builder::embed::EmbedBuilder;
let embed = EmbedBuilder::new()
.color(0xfd_69_b3)
.description("a description")
.validate()?
.build();
# Ok(()) }
```
[`COLOR_MAXIMUM`]: twilight_validate::embed::COLOR_MAXIMUM
|
color
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/embed/mod.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/embed/mod.rs
|
ISC
|
pub fn description(mut self, description: impl Into<String>) -> Self {
self.0.description = Some(description.into());
self
}
|
Set the description.
Refer to [`DESCRIPTION_LENGTH`] for the maximum number of UTF-16 code
points that can be in a description.
# Examples
```
# fn main() -> Result<(), Box<dyn std::error::Error>> {
use twilight_util::builder::embed::EmbedBuilder;
let embed = EmbedBuilder::new()
.description("this is an embed")
.validate()?
.build();
# Ok(()) }
```
[`DESCRIPTION_LENGTH`]: twilight_validate::embed::DESCRIPTION_LENGTH
|
description
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/embed/mod.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/embed/mod.rs
|
ISC
|
pub fn field(mut self, field: impl Into<EmbedField>) -> Self {
self.0.fields.push(field.into());
self
}
|
Add a field to the embed.
# Examples
```
# fn main() -> Result<(), Box<dyn std::error::Error>> {
use twilight_util::builder::embed::{EmbedBuilder, EmbedFieldBuilder};
let embed = EmbedBuilder::new()
.description("this is an embed")
.field(EmbedFieldBuilder::new("a field", "and its value"))
.validate()?
.build();
# Ok(()) }
```
|
field
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/embed/mod.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/embed/mod.rs
|
ISC
|
pub fn footer(mut self, footer: impl Into<EmbedFooter>) -> Self {
self.0.footer = Some(footer.into());
self
}
|
Set the footer of the embed.
# Examples
```
# fn main() -> Result<(), Box<dyn std::error::Error>> {
use twilight_util::builder::embed::{EmbedBuilder, EmbedFooterBuilder};
let embed = EmbedBuilder::new()
.description("this is an embed")
.footer(EmbedFooterBuilder::new("a footer"))
.validate()?
.build();
# Ok(()) }
```
|
footer
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/embed/mod.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/embed/mod.rs
|
ISC
|
pub fn title(mut self, title: impl Into<String>) -> Self {
self.0.title = Some(title.into());
self
}
|
Set the title.
Refer to [`TITLE_LENGTH`] for the maximum number of UTF-16 code points
that can be in a title.
# Examples
Set the title to "twilight":
```
# fn main() -> Result<(), Box<dyn std::error::Error>> {
use twilight_util::builder::embed::EmbedBuilder;
let embed = EmbedBuilder::new()
.title("twilight")
.url("https://github.com/twilight-rs/twilight")
.validate()?
.build();
# Ok(()) }
```
[`TITLE_LENGTH`]: twilight_validate::embed::TITLE_LENGTH
|
title
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/embed/mod.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/embed/mod.rs
|
ISC
|
pub fn url(mut self, url: impl Into<String>) -> Self {
self.0.url = Some(url.into());
self
}
|
Set the URL.
# Examples
Set the URL to [twilight's repository]:
```
# fn main() -> Result<(), Box<dyn std::error::Error>> {
use twilight_util::builder::embed::{EmbedBuilder, EmbedFooterBuilder};
let embed = EmbedBuilder::new()
.description("twilight's repository")
.url("https://github.com/twilight-rs/twilight")
.validate()?
.build();
# Ok(()) }
```
[twilight's repository]: https://github.com/twilight-rs/twilight
|
url
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/embed/mod.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/embed/mod.rs
|
ISC
|
pub fn parse(url: &str) -> Result<(Id<WebhookMarker>, Option<&str>), WebhookParseError> {
let mut segments = {
let mut start = url.split("discord.com/api/webhooks/");
let path = start.nth(1).ok_or(WebhookParseError {
kind: WebhookParseErrorType::SegmentMissing,
source: None,
})?;
path.split('/')
};
let id_segment = segments.next().ok_or(WebhookParseError {
kind: WebhookParseErrorType::SegmentMissing,
source: None,
})?;
// If we don't have this check it'll return `IdInvalid`, which isn't right.
if id_segment.is_empty() {
return Err(WebhookParseError {
kind: WebhookParseErrorType::SegmentMissing,
source: None,
});
}
let id = id_segment
.parse::<NonZeroU64>()
.map_err(|source| WebhookParseError {
kind: WebhookParseErrorType::IdInvalid,
source: Some(Box::new(source)),
})?;
let mut token = segments.next();
// Don't return an empty token if the segment is empty.
if token.is_some_and(str::is_empty) {
token = None;
}
Ok((Id::from(id), token))
}
|
Parse the webhook ID and token from a webhook URL, if it exists in the
string.
# Examples
Parse a webhook URL with a token:
```
use twilight_model::id::Id;
use twilight_util::link::webhook;
# fn main() -> Result<(), Box<dyn std::error::Error>> {
let url = "https://canary.discord.com/api/webhooks/794590023369752587/tjxHaPHLKp9aEdSwJuLeHhHHGEqIxt1aay4I67FOP9uzsYEWmj0eJmDn-2ZvCYLyOb_K";
let (id, token) = webhook::parse(url)?;
assert_eq!(Id::new(794590023369752587), id);
assert_eq!(
Some("tjxHaPHLKp9aEdSwJuLeHhHHGEqIxt1aay4I67FOP9uzsYEWmj0eJmDn-2ZvCYLyOb_K"),
token,
);
# Ok(()) }
```
Parse a webhook URL without a token:
```
use twilight_model::id::Id;
use twilight_util::link::webhook;
# fn main() -> Result<(), Box<dyn std::error::Error>> {
let url = "https://canary.discord.com/api/webhooks/794590023369752587";
let (id, token) = webhook::parse(url)?;
assert_eq!(Id::new(794590023369752587), id);
assert!(token.is_none());
# Ok(()) }
```
# Errors
Returns [`WebhookParseErrorType::IdInvalid`] error type if the ID segment of
the URL is not a valid integer.
Returns [`WebhookParseErrorType::SegmentMissing`] error type if one of the
required segments is missing. This can be the "api" or "webhooks" standard
segment of the URL or the segment containing the webhook ID.
|
parse
|
rust
|
twilight-rs/twilight
|
twilight-util/src/link/webhook.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/link/webhook.rs
|
ISC
|
pub const fn bitrate(value: u32) -> Result<(), ChannelValidationError> {
if value >= CHANNEL_BITRATE_MIN {
Ok(())
} else {
Err(ChannelValidationError {
kind: ChannelValidationErrorType::BitrateInvalid,
})
}
}
|
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
|
bitrate
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/channel.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/channel.rs
|
ISC
|
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 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
|
bulk_delete_messages
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/channel.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/channel.rs
|
ISC
|
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 channel is a thread.
# Errors
Returns an error of type [`ChannelValidationErrorType::TypeInvalid`] if the
channel is not a thread.
|
is_thread
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/channel.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/channel.rs
|
ISC
|
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 forum channel's topic's length is correct.
# Errors
Returns an error of type [`TopicInvalid`] if the
topic is invalid.
[`TopicInvalid`]: ChannelValidationErrorType::TopicInvalid
|
forum_topic
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/channel.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/channel.rs
|
ISC
|
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 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
|
name
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/channel.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/channel.rs
|
ISC
|
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 topic's length is correct.
# Errors
Returns an error of type [`TopicInvalid`] if the
topic is invalid.
[`TopicInvalid`]: ChannelValidationErrorType::TopicInvalid
|
topic
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/channel.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/channel.rs
|
ISC
|
pub fn command(value: &Command) -> Result<(), CommandValidationError> {
let characters = self::command_characters(value);
if characters > COMMAND_TOTAL_LENGTH {
return Err(CommandValidationError {
kind: CommandValidationErrorType::CommandTooLarge { characters },
});
}
let Command {
description,
description_localizations,
name,
name_localizations,
kind,
..
} = value;
if *kind == CommandType::ChatInput {
self::description(description)?;
if let Some(description_localizations) = description_localizations {
for description in description_localizations.values() {
self::description(description)?;
}
}
} else if !description.is_empty() {
return Err(CommandValidationError {
kind: CommandValidationErrorType::DescriptionNotAllowed,
});
}
if let Some(name_localizations) = name_localizations {
for name in name_localizations.values() {
match kind {
CommandType::ChatInput => self::chat_input_name(name)?,
CommandType::User | CommandType::Message => {
self::name(name)?;
}
CommandType::Unknown(_) => (),
_ => unimplemented!(),
}
}
}
match kind {
CommandType::ChatInput => self::chat_input_name(name),
CommandType::User | CommandType::Message => self::name(name),
CommandType::Unknown(_) => Ok(()),
_ => unimplemented!(),
}
}
|
Validate a [`Command`].
# Errors
Returns an error of type [`DescriptionInvalid`] if the description is
invalid.
Returns an error of type [`NameLengthInvalid`] or [`NameCharacterInvalid`]
if the name is invalid.
[`DescriptionInvalid`]: CommandValidationErrorType::DescriptionInvalid
[`NameLengthInvalid`]: CommandValidationErrorType::NameLengthInvalid
[`NameCharacterInvalid`]: CommandValidationErrorType::NameCharacterInvalid
|
command
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/command.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/command.rs
|
ISC
|
pub fn command_characters(command: &Command) -> usize {
let mut characters =
longest_localization_characters(&command.name, command.name_localizations.as_ref())
+ longest_localization_characters(
&command.description,
command.description_localizations.as_ref(),
);
for option in &command.options {
characters += option_characters(option);
}
characters
}
|
Calculate the total character count of a command.
|
command_characters
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/command.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/command.rs
|
ISC
|
pub fn option_characters(option: &CommandOption) -> usize {
let mut characters = 0;
characters += longest_localization_characters(&option.name, option.name_localizations.as_ref());
characters += longest_localization_characters(
&option.description,
option.description_localizations.as_ref(),
);
match option.kind {
CommandOptionType::String => {
if let Some(choices) = option.choices.as_ref() {
for choice in choices {
if let CommandOptionChoiceValue::String(string_choice) = &choice.value {
characters += longest_localization_characters(
&choice.name,
choice.name_localizations.as_ref(),
) + string_choice.len();
}
}
}
}
CommandOptionType::SubCommandGroup | CommandOptionType::SubCommand => {
if let Some(options) = option.options.as_ref() {
for option in options {
characters += option_characters(option);
}
}
}
_ => {}
}
characters
}
|
Calculate the total character count of a command option.
|
option_characters
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/command.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/command.rs
|
ISC
|
pub fn description(value: impl AsRef<str>) -> Result<(), CommandValidationError> {
let len = value.as_ref().chars().count();
// https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-structure
if (DESCRIPTION_LENGTH_MIN..=DESCRIPTION_LENGTH_MAX).contains(&len) {
Ok(())
} else {
Err(CommandValidationError {
kind: CommandValidationErrorType::DescriptionInvalid,
})
}
}
|
Validate the description of a [`Command`].
The length of the description must be more than [`DESCRIPTION_LENGTH_MIN`]
and less than or equal to [`DESCRIPTION_LENGTH_MAX`].
# Errors
Returns an error of type [`DescriptionInvalid`] if the description is
invalid.
[`DescriptionInvalid`]: CommandValidationErrorType::DescriptionInvalid
|
description
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/command.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/command.rs
|
ISC
|
pub fn name(value: impl AsRef<str>) -> Result<(), CommandValidationError> {
let len = value.as_ref().chars().count();
// https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-structure
if (NAME_LENGTH_MIN..=NAME_LENGTH_MAX).contains(&len) {
Ok(())
} else {
Err(CommandValidationError {
kind: CommandValidationErrorType::NameLengthInvalid,
})
}
}
|
Validate the name of a [`User`] or [`Message`] command.
The length of the name must be more than [`NAME_LENGTH_MIN`] and less than
or equal to [`NAME_LENGTH_MAX`].
Use [`chat_input_name`] to validate name of a [`ChatInput`] command.
# Errors
Returns an error of type [`NameLengthInvalid`] if the name is invalid.
[`User`]: CommandType::User
[`Message`]: CommandType::Message
[`ChatInput`]: CommandType::ChatInput
[`NameLengthInvalid`]: CommandValidationErrorType::NameLengthInvalid
|
name
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/command.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/command.rs
|
ISC
|
pub fn chat_input_name(value: impl AsRef<str>) -> Result<(), CommandValidationError> {
self::name(&value)?;
self::name_characters(value)?;
Ok(())
}
|
Validate the name of a [`ChatInput`] command.
The length of the name must be more than [`NAME_LENGTH_MIN`] and less than
or equal to [`NAME_LENGTH_MAX`]. It can only contain alphanumeric characters
and lowercase variants must be used where possible. Special characters `-`
and `_` are allowed.
# Errors
Returns an error of type [`NameLengthInvalid`] if the length is invalid.
Returns an error of type [`NameCharacterInvalid`] if the name contains a
non-alphanumeric character or an uppercase character for which a lowercase
variant exists.
[`ChatInput`]: CommandType::ChatInput
[`NameLengthInvalid`]: CommandValidationErrorType::NameLengthInvalid
[`NameCharacterInvalid`]: CommandValidationErrorType::NameCharacterInvalid
|
chat_input_name
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/command.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/command.rs
|
ISC
|
pub fn option_name(value: impl AsRef<str>) -> Result<(), CommandValidationError> {
let len = value.as_ref().chars().count();
if !(OPTION_NAME_LENGTH_MIN..=OPTION_NAME_LENGTH_MAX).contains(&len) {
return Err(CommandValidationError {
kind: CommandValidationErrorType::NameLengthInvalid,
});
}
self::name_characters(value)?;
Ok(())
}
|
Validate the name of a [`CommandOption`].
The length of the name must be more than [`NAME_LENGTH_MIN`] and less than
or equal to [`NAME_LENGTH_MAX`]. It can only contain alphanumeric characters
and lowercase variants must be used where possible. Special characters `-`
and `_` are allowed.
# Errors
Returns an error of type [`NameLengthInvalid`] if the length is invalid.
Returns an error of type [`NameCharacterInvalid`] if the name contains a
non-alphanumeric character or an uppercase character for which a lowercase
variant exists.
[`NameLengthInvalid`]: CommandValidationErrorType::NameLengthInvalid
[`NameCharacterInvalid`]: CommandValidationErrorType::NameCharacterInvalid
|
option_name
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/command.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/command.rs
|
ISC
|
fn name_characters(value: impl AsRef<str>) -> Result<(), CommandValidationError> {
let chars = value.as_ref().chars();
for char in chars {
if !char.is_alphanumeric() && char != '_' && char != '-' {
return Err(CommandValidationError {
kind: CommandValidationErrorType::NameCharacterInvalid { character: char },
});
}
if char.to_lowercase().next() != Some(char) {
return Err(CommandValidationError {
kind: CommandValidationErrorType::NameCharacterInvalid { character: char },
});
}
}
Ok(())
}
|
Validate the characters of a [`ChatInput`] command name or a
[`CommandOption`] name.
The name can only contain alphanumeric characters and lowercase variants
must be used where possible. Special characters `-` and `_` are allowed.
# Errors
Returns an error of type [`NameCharacterInvalid`] if the name contains a
non-alphanumeric character or an uppercase character for which a lowercase
variant exists.
[`ChatInput`]: CommandType::ChatInput
[`NameCharacterInvalid`]: CommandValidationErrorType::NameCharacterInvalid
|
name_characters
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/command.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/command.rs
|
ISC
|
pub fn choice_name(name: &str) -> Result<(), CommandValidationError> {
let len = name.chars().count();
if (OPTION_CHOICE_NAME_LENGTH_MIN..=OPTION_CHOICE_NAME_LENGTH_MAX).contains(&len) {
Ok(())
} else {
Err(CommandValidationError {
kind: CommandValidationErrorType::OptionChoiceNameLengthInvalid,
})
}
}
|
Validate a single name localization in a [`CommandOptionChoice`].
# Errors
Returns an error of type [`OptionChoiceNameLengthInvalid`] if the name is
less than [`OPTION_CHOICE_NAME_LENGTH_MIN`] or more than [`OPTION_CHOICE_NAME_LENGTH_MAX`].
[`OptionChoiceNameLengthInvalid`]: CommandValidationErrorType::OptionChoiceNameLengthInvalid
|
choice_name
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/command.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/command.rs
|
ISC
|
pub fn choice(choice: &CommandOptionChoice) -> Result<(), CommandValidationError> {
self::choice_name(&choice.name)?;
if let CommandOptionChoiceValue::String(value) = &choice.value {
let value_len = value.chars().count();
if !(OPTION_CHOICE_STRING_VALUE_LENGTH_MIN..=OPTION_CHOICE_STRING_VALUE_LENGTH_MAX)
.contains(&value_len)
{
return Err(CommandValidationError {
kind: CommandValidationErrorType::OptionChoiceStringValueLengthInvalid,
});
}
}
if let Some(name_localizations) = &choice.name_localizations {
name_localizations
.values()
.try_for_each(|name| self::choice_name(name))?;
}
Ok(())
}
|
Validate a single [`CommandOptionChoice`].
# Errors
Returns an error of type [`OptionChoiceNameLengthInvalid`] if the name is
less than [`OPTION_CHOICE_NAME_LENGTH_MIN`] or more than [`OPTION_CHOICE_NAME_LENGTH_MAX`].
[`OptionChoiceNameLengthInvalid`]: CommandValidationErrorType::OptionChoiceNameLengthInvalid
|
choice
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/command.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/command.rs
|
ISC
|
pub fn option(option: &CommandOption) -> Result<(), CommandValidationError> {
let description_len = option.description.chars().count();
if !(OPTION_DESCRIPTION_LENGTH_MIN..=OPTION_DESCRIPTION_LENGTH_MAX).contains(&description_len) {
return Err(CommandValidationError {
kind: CommandValidationErrorType::OptionDescriptionInvalid,
});
}
if let Some(choices) = &option.choices {
choices.iter().try_for_each(self::choice)?;
}
self::option_name(&option.name)
}
|
Validate a single [`CommandOption`].
# Errors
Returns an error of type [`OptionDescriptionInvalid`] if the description is
invalid.
Returns an error of type [`OptionNameLengthInvalid`] or [`OptionNameCharacterInvalid`]
if the name is invalid.
[`OptionDescriptionInvalid`]: CommandValidationErrorType::OptionDescriptionInvalid
[`OptionNameLengthInvalid`]: CommandValidationErrorType::OptionNameLengthInvalid
[`OptionNameCharacterInvalid`]: CommandValidationErrorType::OptionNameCharacterInvalid
|
option
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/command.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/command.rs
|
ISC
|
pub fn options(options: &[CommandOption]) -> Result<(), CommandValidationError> {
// https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-structure
if options.len() > OPTIONS_LIMIT {
return Err(CommandValidationError {
kind: CommandValidationErrorType::OptionsCountInvalid,
});
}
let mut names = HashSet::with_capacity(options.len());
for (option_index, option) in options.iter().enumerate() {
if !names.insert(&option.name) {
return Err(CommandValidationError::option_name_not_unique(option_index));
}
}
// Validate that there are no required options listed after optional ones.
options
.iter()
.zip(options.iter().skip(1))
.enumerate()
.try_for_each(|(index, (first, second))| {
if !first.required.unwrap_or_default() && second.required.unwrap_or_default() {
Err(CommandValidationError::option_required_first(index))
} else {
Ok(())
}
})?;
// Validate that each option is correct.
options.iter().try_for_each(|option| {
if let Some(options) = &option.options {
self::options(options)
} else {
self::option(option)
}
})?;
Ok(())
}
|
Validate a list of command options for count, order, and internal validity.
# Errors
Returns an error of type [`OptionsRequiredFirst`] if a required option is
listed before an optional option.
Returns an error of type [`OptionsCountInvalid`] if the list of options or
any sub-list of options is too long.
[`OptionsRequiredFirst`]: CommandValidationErrorType::OptionsRequiredFirst
[`OptionsCountInvalid`]: CommandValidationErrorType::OptionsCountInvalid
|
options
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/command.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/command.rs
|
ISC
|
pub fn component(component: &Component) -> Result<(), ComponentValidationError> {
match component {
Component::ActionRow(action_row) => self::action_row(action_row)?,
other => {
return Err(ComponentValidationError {
kind: ComponentValidationErrorType::InvalidRootComponent { kind: other.kind() },
});
}
}
Ok(())
}
|
Ensure that a top-level request component is correct.
Intended to ensure that a fully formed top-level component for requests
is an action row.
Refer to other validators like [`button`] if you need to validate other
components.
# Errors
Returns an error of type [`InvalidRootComponent`] if the component is not an
[`ActionRow`].
Refer to [`action_row`] for potential errors when validating an action row
component.
[`InvalidRootComponent`]: ComponentValidationErrorType::InvalidRootComponent
|
component
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/component.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/component.rs
|
ISC
|
pub fn action_row(action_row: &ActionRow) -> Result<(), ComponentValidationError> {
self::component_action_row_components(&action_row.components)?;
for component in &action_row.components {
match component {
Component::ActionRow(_) => {
return Err(ComponentValidationError {
kind: ComponentValidationErrorType::InvalidChildComponent {
kind: ComponentType::ActionRow,
},
});
}
Component::Button(button) => self::button(button)?,
Component::SelectMenu(select_menu) => self::select_menu(select_menu)?,
Component::TextInput(text_input) => self::text_input(text_input)?,
Component::Unknown(unknown) => {
return Err(ComponentValidationError {
kind: ComponentValidationErrorType::InvalidChildComponent {
kind: ComponentType::Unknown(*unknown),
},
})
}
}
}
Ok(())
}
|
Ensure that an action row is correct.
# Errors
Returns an error of type [`ActionRowComponentCount`] if the action row has
too many components in it.
Returns an error of type [`InvalidChildComponent`] if the provided nested
component is an [`ActionRow`]. Action rows can not contain another action
row.
Refer to [`button`] for potential errors when validating a button in the
action row.
Refer to [`select_menu`] for potential errors when validating a select menu
in the action row.
Refer to [`text_input`] for potential errors when validating a text input in
the action row.
[`ActionRowComponentCount`]: ComponentValidationErrorType::ActionRowComponentCount
[`InvalidChildComponent`]: ComponentValidationErrorType::InvalidChildComponent
|
action_row
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/component.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/component.rs
|
ISC
|
pub fn button(button: &Button) -> Result<(), ComponentValidationError> {
let has_custom_id = button.custom_id.is_some();
let has_url = button.url.is_some();
// First check if a custom ID and URL are both set. If so this
// results in a conflict, as no valid button may have both set.
if has_custom_id && has_url {
return Err(ComponentValidationError {
kind: ComponentValidationErrorType::ButtonConflict,
});
}
// Next, we check if the button is a link and a URL is not set.
//
// Lastly, we check if the button is not a link and a custom ID is
// not set.
let is_link = button.style == ButtonStyle::Link;
if (is_link && !has_url) || (!is_link && !has_custom_id) {
return Err(ComponentValidationError {
kind: ComponentValidationErrorType::ButtonStyle {
style: button.style,
},
});
}
if let Some(custom_id) = button.custom_id.as_ref() {
self::component_custom_id(custom_id)?;
}
if let Some(label) = button.label.as_ref() {
self::component_button_label(label)?;
}
Ok(())
}
|
Ensure that a button is correct.
# Errors
Returns an error of type [`ButtonConflict`] if both a custom ID and URL are
specified.
Returns an error of type
[`ButtonStyle`][`ComponentValidationErrorType::ButtonStyle`] if
[`ButtonStyle::Link`] is provided and a URL is provided, or if the style is
not [`ButtonStyle::Link`] and a custom ID is not provided.
Returns an error of type [`ComponentCustomIdLength`] if the provided custom
ID is too long.
Returns an error of type [`ComponentLabelLength`] if the provided button
label is too long.
[`ButtonConflict`]: ComponentValidationErrorType::ButtonConflict
[`ComponentCustomIdLength`]: ComponentValidationErrorType::ComponentCustomIdLength
[`ComponentLabelLength`]: ComponentValidationErrorType::ComponentLabelLength
|
button
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/component.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/component.rs
|
ISC
|
pub fn select_menu(select_menu: &SelectMenu) -> Result<(), ComponentValidationError> {
self::component_custom_id(&select_menu.custom_id)?;
// There aren't any requirements for channel_types that we could validate here
if let SelectMenuType::Text = &select_menu.kind {
let options = select_menu
.options
.as_ref()
.ok_or(ComponentValidationError {
kind: ComponentValidationErrorType::SelectOptionsMissing,
})?;
for option in options {
component_select_option_label(&option.label)?;
component_select_option_value(&option.value)?;
if let Some(description) = option.description.as_ref() {
component_option_description(description)?;
}
}
component_select_options(options)?;
}
if let Some(placeholder) = select_menu.placeholder.as_ref() {
self::component_select_placeholder(placeholder)?;
}
if let Some(max_values) = select_menu.max_values {
self::component_select_max_values(usize::from(max_values))?;
}
if let Some(min_values) = select_menu.min_values {
self::component_select_min_values(usize::from(min_values))?;
}
if let Some(default_values) = select_menu.default_values.as_ref() {
component_select_default_values_supported(select_menu.kind)?;
component_select_default_values_count(
select_menu.min_values,
select_menu.max_values,
default_values.len(),
)?;
}
Ok(())
}
|
Ensure that a select menu is correct.
# Errors
Returns an error of type [`ComponentCustomIdLength`] if the provided custom
ID is too long.
Returns an error of type [`ComponentLabelLength`] if the provided button
label is too long.
Returns an error of type [`SelectMaximumValuesCount`] if the provided number
of select menu values that can be chosen is smaller than the minimum or
larger than the maximum.
Returns an error of type [`SelectMinimumValuesCount`] if the provided number
of select menu values that must be chosen is larger than the maximum.
Returns an error of type [`SelectOptionDescriptionLength`] if a provided
select option description is too long.
Returns an error of type [`SelectOptionLabelLength`] if a provided select
option label is too long.
Returns an error of type [`SelectOptionValueLength`] error type if
a provided select option value is too long.
Returns an error of type [`SelectPlaceholderLength`] if a provided select
placeholder is too long.
Returns an error of type [`SelectUnsupportedDefaultValues`] if the select menu's type doesn't
support the `default_values` field.
Returns an error of type [`SelectNotEnoughDefaultValues`] if the select menu specifies fewer
default values than its minimum values property.
Returns an error of type [`SelectTooManyDefaultValues`] if the select menu specifies more
default values than its maximum values property.
[`ComponentCustomIdLength`]: ComponentValidationErrorType::ComponentCustomIdLength
[`ComponentLabelLength`]: ComponentValidationErrorType::ComponentLabelLength
[`SelectMaximumValuesCount`]: ComponentValidationErrorType::SelectMaximumValuesCount
[`SelectMinimumValuesCount`]: ComponentValidationErrorType::SelectMinimumValuesCount
[`SelectOptionDescriptionLength`]: ComponentValidationErrorType::SelectOptionDescriptionLength
[`SelectOptionLabelLength`]: ComponentValidationErrorType::SelectOptionLabelLength
[`SelectOptionValueLength`]: ComponentValidationErrorType::SelectOptionValueLength
[`SelectPlaceholderLength`]: ComponentValidationErrorType::SelectPlaceholderLength
[`SelectUnsupportedDefaultValues`]: ComponentValidationErrorType::SelectUnsupportedDefaultValues
[`SelectNotEnoughDefaultValues`]: ComponentValidationErrorType::SelectNotEnoughDefaultValues
[`SelectTooManyDefaultValues`]: ComponentValidationErrorType::SelectTooManyDefaultValues
|
select_menu
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/component.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/component.rs
|
ISC
|
pub fn text_input(text_input: &TextInput) -> Result<(), ComponentValidationError> {
self::component_custom_id(&text_input.custom_id)?;
self::component_text_input_label(&text_input.label)?;
if let Some(max_length) = text_input.max_length {
self::component_text_input_max(max_length)?;
}
if let Some(min_length) = text_input.min_length {
self::component_text_input_min(min_length)?;
}
if let Some(placeholder) = text_input.placeholder.as_ref() {
self::component_text_input_placeholder(placeholder)?;
}
if let Some(value) = text_input.value.as_ref() {
self::component_text_input_value(value)?;
}
Ok(())
}
|
Ensure that a text input is correct.
# Errors
Returns an error of type [`ComponentCustomIdLength`] if the provided custom
ID is too long.
Returns an error of type [`ComponentLabelLength`] if the provided button
label is too long.
Returns an error of type [`TextInputMaxLength`] if the length is invalid.
Returns an error of type [`TextInputMinLength`] if the length is invalid.
Returns an error of type [`TextInputPlaceholderLength`] if the provided
placeholder is too long.
Returns an error of type [`TextInputValueLength`] if the length is invalid.
[`ComponentCustomIdLength`]: ComponentValidationErrorType::ComponentCustomIdLength
[`ComponentLabelLength`]: ComponentValidationErrorType::ComponentLabelLength
[`TextInputMaxLength`]: ComponentValidationErrorType::TextInputMaxLength
[`TextInputMinLength`]: ComponentValidationErrorType::TextInputMinLength
[`TextInputPlaceholderLength`]: ComponentValidationErrorType::TextInputPlaceholderLength
[`TextInputValueLength`]: ComponentValidationErrorType::TextInputValueLength
|
text_input
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/component.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/component.rs
|
ISC
|
const fn component_action_row_components(
components: &[Component],
) -> Result<(), ComponentValidationError> {
let count = components.len();
if count > COMPONENT_COUNT {
return Err(ComponentValidationError {
kind: ComponentValidationErrorType::ActionRowComponentCount { count },
});
}
Ok(())
}
|
Validate that an [`ActionRow`] does not contain too many components.
[`ActionRow`]s may only have so many components within it, defined by
[`ACTION_ROW_COMPONENT_COUNT`].
# Errors
Returns an error of type [`ActionRowComponentCount`] if the provided list of
components is too many for an [`ActionRow`].
[`ActionRowComponentCount`]: ComponentValidationErrorType::ActionRowComponentCount
[`ActionRow`]: twilight_model::application::component::ActionRow
|
component_action_row_components
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/component.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/component.rs
|
ISC
|
fn component_button_label(label: impl AsRef<str>) -> Result<(), ComponentValidationError> {
let chars = label.as_ref().chars().count();
if chars > COMPONENT_BUTTON_LABEL_LENGTH {
return Err(ComponentValidationError {
kind: ComponentValidationErrorType::ComponentLabelLength { chars },
});
}
Ok(())
}
|
Validate that a [`Component`]'s label is not too long.
# Errors
Returns an error of type [`ComponentLabelLength`] if the provided component
label is too long.
[`ComponentLabelLength`]: ComponentValidationErrorType::ComponentLabelLength
|
component_button_label
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/component.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/component.rs
|
ISC
|
fn component_custom_id(custom_id: impl AsRef<str>) -> Result<(), ComponentValidationError> {
let chars = custom_id.as_ref().chars().count();
if chars > COMPONENT_CUSTOM_ID_LENGTH {
return Err(ComponentValidationError {
kind: ComponentValidationErrorType::ComponentCustomIdLength { chars },
});
}
Ok(())
}
|
Validate that a custom ID is not too long.
# Errors
Returns an error of type [`ComponentCustomIdLength`] if the provided custom
ID is too long.
[`ComponentCustomIdLength`]: ComponentValidationErrorType::ComponentCustomIdLength
|
component_custom_id
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/component.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/component.rs
|
ISC
|
fn component_option_description(
description: impl AsRef<str>,
) -> Result<(), ComponentValidationError> {
let chars = description.as_ref().chars().count();
if chars > SELECT_OPTION_DESCRIPTION_LENGTH {
return Err(ComponentValidationError {
kind: ComponentValidationErrorType::SelectOptionDescriptionLength { chars },
});
}
Ok(())
}
|
Validate a [`SelectMenuOption::description`]'s length.
# Errors
Returns an error of type [`SelectOptionDescriptionLength`] if the provided
select option description is too long.
[`SelectMenuOption::description`]: twilight_model::application::component::select_menu::SelectMenuOption::description
[`SelectOptionDescriptionLength`]: ComponentValidationErrorType::SelectOptionDescriptionLength
|
component_option_description
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/component.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/component.rs
|
ISC
|
const fn component_select_default_values_supported(
menu_type: SelectMenuType,
) -> Result<(), ComponentValidationError> {
if !matches!(
menu_type,
SelectMenuType::User
| SelectMenuType::Role
| SelectMenuType::Mentionable
| SelectMenuType::Channel
) {
return Err(ComponentValidationError {
kind: ComponentValidationErrorType::SelectUnsupportedDefaultValues { kind: menu_type },
});
}
Ok(())
}
|
Validate a [`SelectMenuType`] supports the `default_values` field.
# Errors
Returns an error of type [`SelectUnsupportedDefaultValues`] if the provided component type
doesn't support the `default_values` field.
|
component_select_default_values_supported
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/component.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/component.rs
|
ISC
|
const fn component_select_default_values_count(
min_values: Option<u8>,
max_values: Option<u8>,
default_values: usize,
) -> Result<(), ComponentValidationError> {
if let Some(min) = min_values {
let min = min as usize;
if default_values < min {
return Err(ComponentValidationError {
kind: ComponentValidationErrorType::SelectNotEnoughDefaultValues {
provided: default_values,
min,
},
});
}
}
if let Some(max) = max_values {
let max = max as usize;
if default_values > max {
return Err(ComponentValidationError {
kind: ComponentValidationErrorType::SelectTooManyDefaultValues {
provided: default_values,
max,
},
});
}
}
Ok(())
}
|
Validate a [`SelectMenu`]'s `default_values` field has the correct number of values.
# Errors
Returns an error of the type [`SelectTooManyDefaultValues`] if the provided list of default
values exceeds the provided `max_values` (if present).
Alternatively, this returns an error of the type [`SelectNotEnoughDefaultValues`] if the
provided list of default values doesn't meet the provided `min_values` requirement (if present).
|
component_select_default_values_count
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/component.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/component.rs
|
ISC
|
fn component_select_option_label(label: impl AsRef<str>) -> Result<(), ComponentValidationError> {
let chars = label.as_ref().chars().count();
if chars > SELECT_OPTION_LABEL_LENGTH {
return Err(ComponentValidationError {
kind: ComponentValidationErrorType::SelectOptionLabelLength { chars },
});
}
Ok(())
}
|
Validate a [`SelectMenuOption::label`]'s length.
# Errors
Returns an error of type [`SelectOptionLabelLength`] if the provided select
option label is too long.
[`SelectMenuOption::label`]: twilight_model::application::component::select_menu::SelectMenuOption::label
[`SelectOptionLabelLength`]: ComponentValidationErrorType::SelectOptionLabelLength
|
component_select_option_label
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/component.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/component.rs
|
ISC
|
fn component_select_option_value(value: impl AsRef<str>) -> Result<(), ComponentValidationError> {
let chars = value.as_ref().chars().count();
if chars > SELECT_OPTION_VALUE_LENGTH {
return Err(ComponentValidationError {
kind: ComponentValidationErrorType::SelectOptionValueLength { chars },
});
}
Ok(())
}
|
Validate a [`SelectMenuOption::value`]'s length.
# Errors
Returns an error of type [`SelectOptionValueLength`] if the provided select
option value is too long.
[`SelectMenuOption::value`]: twilight_model::application::component::select_menu::SelectMenuOption::value
[`SelectOptionValueLength`]: ComponentValidationErrorType::SelectOptionValueLength
|
component_select_option_value
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/component.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/component.rs
|
ISC
|
const fn component_select_options(
options: &[SelectMenuOption],
) -> Result<(), ComponentValidationError> {
let count = options.len();
if count > SELECT_OPTION_COUNT {
return Err(ComponentValidationError {
kind: ComponentValidationErrorType::SelectOptionCount { count },
});
}
Ok(())
}
|
Validate a [`SelectMenu`]s number of [`options`].
[`Component::SelectMenu`]s may only have so many options within it, defined
by [`SELECT_OPTION_COUNT`].
# Errors
Returns an error of type [`SelectOptionCount`] if the provided list of
[`SelectMenuOption`]s is too many for a [`SelectMenu`].
[`SelectMenu::options`]: twilight_model::application::component::select_menu::SelectMenu::options
[`SelectMenuOption`]: twilight_model::application::component::select_menu::SelectMenuOption
[`SelectMenu`]: twilight_model::application::component::select_menu::SelectMenu
[`SelectOptionCount`]: ComponentValidationErrorType::SelectOptionCount
|
component_select_options
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/component.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/component.rs
|
ISC
|
fn component_select_placeholder(
placeholder: impl AsRef<str>,
) -> Result<(), ComponentValidationError> {
let chars = placeholder.as_ref().chars().count();
if chars > SELECT_PLACEHOLDER_LENGTH {
return Err(ComponentValidationError {
kind: ComponentValidationErrorType::SelectPlaceholderLength { chars },
});
}
Ok(())
}
|
Validate a [`SelectMenu::placeholder`]'s length.
# Errors
Returns an error of type [`SelectPlaceholderLength`] if the provided select
placeholder is too long.
[`SelectMenu::placeholder`]: twilight_model::application::component::select_menu::SelectMenu::placeholder
[`SelectPlaceholderLength`]: ComponentValidationErrorType::SelectPlaceHolderLength
|
component_select_placeholder
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/component.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/component.rs
|
ISC
|
fn component_text_input_label(label: impl AsRef<str>) -> Result<(), ComponentValidationError> {
let len = label.as_ref().len();
if (TEXT_INPUT_LABEL_MIN..=TEXT_INPUT_LABEL_MAX).contains(&len) {
Ok(())
} else {
Err(ComponentValidationError {
kind: ComponentValidationErrorType::TextInputLabelLength { len },
})
}
}
|
Ensure a [`TextInput::label`]'s length is correct.
The length must be at most [`TEXT_INPUT_LABEL_MAX`].
# Errors
Returns an error of type [`TextInputLabelLength`] if the provided
label is too long.
[`TextInput::label`]: twilight_model::application::component::text_input::TextInput::label
[`TextInputLabelLength`]: ComponentValidationErrorType::TextInputLabelLength
|
component_text_input_label
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/component.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/component.rs
|
ISC
|
const fn component_text_input_max(len: u16) -> Result<(), ComponentValidationError> {
let len = len as usize;
if len >= TEXT_INPUT_LENGTH_MIN && len <= TEXT_INPUT_LENGTH_MAX {
Ok(())
} else {
Err(ComponentValidationError {
kind: ComponentValidationErrorType::TextInputMaxLength { len },
})
}
}
|
Ensure a [`TextInput::max_length`]'s value is correct.
# Errors
Returns an error of type [`TextInputMaxLength`] if the length is invalid.
[`TextInput::max_length`]: twilight_model::application::component::text_input::TextInput::max_length
[`TextInputMaxLength`]: ComponentValidationErrorType::TextInputMaxLength
|
component_text_input_max
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/component.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/component.rs
|
ISC
|
const fn component_text_input_min(len: u16) -> Result<(), ComponentValidationError> {
let len = len as usize;
if len <= TEXT_INPUT_LENGTH_MAX {
Ok(())
} else {
Err(ComponentValidationError {
kind: ComponentValidationErrorType::TextInputMinLength { len },
})
}
}
|
Ensure a [`TextInput::min_length`]'s value is correct.
# Errors
Returns an error of type [`TextInputMinLength`] if the length is invalid.
[`TextInput::min_length`]: twilight_model::application::component::text_input::TextInput::min_length
[`TextInputMinLength`]: ComponentValidationErrorType::TextInputMinLength
|
component_text_input_min
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/component.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/component.rs
|
ISC
|
fn component_text_input_placeholder(
placeholder: impl AsRef<str>,
) -> Result<(), ComponentValidationError> {
let chars = placeholder.as_ref().chars().count();
if chars <= TEXT_INPUT_PLACEHOLDER_MAX {
Ok(())
} else {
Err(ComponentValidationError {
kind: ComponentValidationErrorType::TextInputPlaceholderLength { chars },
})
}
}
|
Ensure a [`TextInput::placeholder`]'s length is correct.
The length must be at most [`TEXT_INPUT_PLACEHOLDER_MAX`].
# Errors
Returns an error of type [`TextInputPlaceholderLength`] if the provided
placeholder is too long.
[`TextInput::placeholder`]: twilight_model::application::component::text_input::TextInput::placeholder
[`TextInputPlaceholderLength`]: ComponentValidationErrorType::TextInputPlaceholderLength
|
component_text_input_placeholder
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/component.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/component.rs
|
ISC
|
fn component_text_input_value(value: impl AsRef<str>) -> Result<(), ComponentValidationError> {
let chars = value.as_ref().chars().count();
if chars <= TEXT_INPUT_LENGTH_MAX {
Ok(())
} else {
Err(ComponentValidationError {
kind: ComponentValidationErrorType::TextInputValueLength { chars },
})
}
}
|
Ensure a [`TextInput::value`]'s length is correct.
# Errors
Returns an error of type [`TextInputValueLength`] if the length is invalid.
[`TextInput::value_length`]: twilight_model::application::component::text_input::TextInput::value
[`TextInputValueLength`]: ComponentValidationErrorType::TextInputValueLength
|
component_text_input_value
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/component.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/component.rs
|
ISC
|
pub fn embed(embed: &Embed) -> Result<(), EmbedValidationError> {
let chars = self::chars(embed);
if chars > EMBED_TOTAL_LENGTH {
return Err(EmbedValidationError {
kind: EmbedValidationErrorType::EmbedTooLarge { chars },
});
}
if let Some(color) = embed.color {
if color > COLOR_MAXIMUM {
return Err(EmbedValidationError {
kind: EmbedValidationErrorType::ColorNotRgb { color },
});
}
}
if let Some(description) = embed.description.as_ref() {
let chars = description.chars().count();
if chars > DESCRIPTION_LENGTH {
return Err(EmbedValidationError {
kind: EmbedValidationErrorType::DescriptionTooLarge { chars },
});
}
}
if embed.fields.len() > FIELD_COUNT {
return Err(EmbedValidationError {
kind: EmbedValidationErrorType::TooManyFields {
amount: embed.fields.len(),
},
});
}
for field in &embed.fields {
let name_chars = field.name.chars().count();
if name_chars > FIELD_NAME_LENGTH {
return Err(EmbedValidationError {
kind: EmbedValidationErrorType::FieldNameTooLarge { chars: name_chars },
});
}
let value_chars = field.value.chars().count();
if value_chars > FIELD_VALUE_LENGTH {
return Err(EmbedValidationError {
kind: EmbedValidationErrorType::FieldValueTooLarge { chars: value_chars },
});
}
}
if let Some(footer) = embed.footer.as_ref() {
let chars = footer.text.chars().count();
if chars > FOOTER_TEXT_LENGTH {
return Err(EmbedValidationError {
kind: EmbedValidationErrorType::FooterTextTooLarge { chars },
});
}
}
if let Some(name) = embed.author.as_ref().map(|author| &author.name) {
let chars = name.chars().count();
if chars > AUTHOR_NAME_LENGTH {
return Err(EmbedValidationError {
kind: EmbedValidationErrorType::AuthorNameTooLarge { chars },
});
}
}
if let Some(title) = embed.title.as_ref() {
let chars = title.chars().count();
if chars > TITLE_LENGTH {
return Err(EmbedValidationError {
kind: EmbedValidationErrorType::TitleTooLarge { chars },
});
}
}
Ok(())
}
|
Ensure an embed is correct.
# Errors
Returns an error of type [`AuthorNameTooLarge`] if
the author's name is too large.
Returns an error of type [`ColorNotRgb`] if if the provided color is not a
valid RGB integer. Refer to [`COLOR_MAXIMUM`] to know what the maximum
accepted value is.
Returns an error of type [`DescriptionTooLarge`] if the description is too
large.
Returns an error of type [`EmbedTooLarge`] if the embed in total is too
large.
Returns an error of type [`FieldNameTooLarge`] if
a field's name is too long.
Returns an error of type [`FieldValueTooLarge`] if
a field's value is too long.
Returns an error of type [`FooterTextTooLarge`] if
the footer text is too long.
Returns an error of type [`TitleTooLarge`] if the title is too long.
Returns an error of type [`TooManyFields`] if
there are too many fields.
[`AuthorNameTooLarge`]: EmbedValidationErrorType::AuthorNameTooLarge
[`ColorNotRgb`]: EmbedValidationErrorType::ColorNotRgb
[`DescriptionTooLarge`]: EmbedValidationErrorType::DescriptionTooLarge
[`EmbedTooLarge`]: EmbedValidationErrorType::EmbedTooLarge
[`FieldNameTooLarge`]: EmbedValidationErrorType::FieldNameTooLarge
[`FieldValueTooLarge`]: EmbedValidationErrorType::FieldValueTooLarge
[`FooterTextTooLarge`]: EmbedValidationErrorType::FooterTextTooLarge
[`TitleTooLarge`]: EmbedValidationErrorType::TitleTooLarge
[`TooManyFields`]: EmbedValidationErrorType::TooManyFields
|
embed
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/embed.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/embed.rs
|
ISC
|
pub fn attachment(attachment: &Attachment) -> Result<(), MessageValidationError> {
attachment_filename(&attachment.filename)?;
if let Some(description) = &attachment.description {
attachment_description(description)?;
}
Ok(())
}
|
Ensure an attachment is correct.
# Errors
Returns an error of type [`AttachmentDescriptionTooLarge`] if
the attachments's description is too large.
Returns an error of type [`AttachmentFilename`] if the
filename is invalid.
[`AttachmentDescriptionTooLarge`]: MessageValidationErrorType::AttachmentDescriptionTooLarge
[`AttachmentFilename`]: MessageValidationErrorType::AttachmentFilename
|
attachment
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/message.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/message.rs
|
ISC
|
pub fn attachment_description(description: impl AsRef<str>) -> Result<(), MessageValidationError> {
let chars = description.as_ref().chars().count();
if chars <= ATTACHMENT_DESCIPTION_LENGTH_MAX {
Ok(())
} else {
Err(MessageValidationError {
kind: MessageValidationErrorType::AttachmentDescriptionTooLarge { chars },
source: None,
})
}
}
|
Ensure an attachment's description is correct.
# Errors
Returns an error of type [`AttachmentDescriptionTooLarge`] if
the attachment's description is too large.
[`AttachmentDescriptionTooLarge`]: MessageValidationErrorType::AttachmentDescriptionTooLarge
|
attachment_description
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/message.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/message.rs
|
ISC
|
pub fn attachment_filename(filename: impl AsRef<str>) -> Result<(), MessageValidationError> {
if filename
.as_ref()
.chars()
.all(|c| (c.is_ascii_alphanumeric() || c == DOT || c == DASH || c == UNDERSCORE))
{
Ok(())
} else {
Err(MessageValidationError {
kind: MessageValidationErrorType::AttachmentFilename {
filename: filename.as_ref().to_string(),
},
source: None,
})
}
}
|
Ensure an attachment's description is correct.
The filename can contain ASCII alphanumeric characters, dots, dashes, and
underscores.
# Errors
Returns an error of type [`AttachmentFilename`] if the filename is invalid.
[`AttachmentFilename`]: MessageValidationErrorType::AttachmentFilename
|
attachment_filename
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/message.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/message.rs
|
ISC
|
pub fn components(components: &[Component]) -> Result<(), MessageValidationError> {
let count = components.len();
if count > COMPONENT_COUNT {
Err(MessageValidationError {
kind: MessageValidationErrorType::ComponentCount { count },
source: None,
})
} else {
for (idx, component) in components.iter().enumerate() {
crate::component::component(component).map_err(|source| {
let (kind, source) = source.into_parts();
MessageValidationError {
kind: MessageValidationErrorType::ComponentInvalid { idx, kind },
source,
}
})?;
}
Ok(())
}
}
|
Ensure a list of components is correct.
# Errors
Returns a [`ComponentValidationErrorType::ComponentCount`] if there are
too many components in the provided list.
Refer to the errors section of [`component`] for a list of errors that may
be returned as a result of validating each provided component.
[`component`]: crate::component::component
|
components
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/message.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/message.rs
|
ISC
|
pub fn content(value: impl AsRef<str>) -> Result<(), MessageValidationError> {
// <https://discordapp.com/developers/docs/resources/channel#create-message-params>
if value.as_ref().chars().count() <= MESSAGE_CONTENT_LENGTH_MAX {
Ok(())
} else {
Err(MessageValidationError {
kind: MessageValidationErrorType::ContentInvalid,
source: None,
})
}
}
|
Ensure a message's content is correct.
# Errors
Returns an error of type [`ContentInvalid`] if the message's content is
invalid.
[`ContentInvalid`]: MessageValidationErrorType::ContentInvalid
|
content
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/message.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/message.rs
|
ISC
|
pub fn embeds(embeds: &[Embed]) -> Result<(), MessageValidationError> {
if embeds.len() > EMBED_COUNT_LIMIT {
Err(MessageValidationError {
kind: MessageValidationErrorType::TooManyEmbeds,
source: None,
})
} else {
let mut chars = 0;
for (idx, embed) in embeds.iter().enumerate() {
chars += embed_chars(embed);
if chars > EMBED_TOTAL_LENGTH {
return Err(MessageValidationError {
kind: MessageValidationErrorType::EmbedInvalid {
idx,
kind: EmbedValidationErrorType::EmbedTooLarge { chars },
},
source: None,
});
}
crate::embed::embed(embed).map_err(|source| {
let (kind, source) = source.into_parts();
MessageValidationError {
kind: MessageValidationErrorType::EmbedInvalid { idx, kind },
source,
}
})?;
}
Ok(())
}
}
|
Ensure a list of embeds is correct.
# Errors
Returns an error of type [`TooManyEmbeds`] if there are too many embeds.
Otherwise, refer to the errors section of [`embed`] for a list of errors
that may occur.
[`TooManyEmbeds`]: MessageValidationErrorType::TooManyEmbeds
[`embed`]: crate::embed::embed
|
embeds
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/message.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/message.rs
|
ISC
|
pub fn sticker_ids(sticker_ids: &[Id<StickerMarker>]) -> Result<(), MessageValidationError> {
let len = sticker_ids.len();
if len <= STICKER_MAX {
Ok(())
} else {
Err(MessageValidationError {
kind: MessageValidationErrorType::StickersInvalid { len },
source: None,
})
}
}
|
Ensure that the amount of stickers in a message is correct.
There must be at most [`STICKER_MAX`] stickers. This is based on [this
documentation entry].
# Errors
Returns an error of type [`StickersInvalid`] if the length is invalid.
[`StickersInvalid`]: MessageValidationErrorType::StickersInvalid
[this documentation entry]: https://discord.com/developers/docs/resources/channel#create-message-jsonform-params
|
sticker_ids
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/message.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/message.rs
|
ISC
|
pub fn audit_reason(audit_reason: impl AsRef<str>) -> Result<(), ValidationError> {
let len = audit_reason.as_ref().chars().count();
if len <= AUDIT_REASON_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::AuditReason { len },
})
}
}
|
Ensure that an audit reason is correct.
The length must be at most [`AUDIT_REASON_MAX`]. This is based on
[this documentation entry].
# Errors
Returns an error of type [`AuditReason`] if the length is invalid.
[`AuditReason`]: ValidationErrorType::AuditReason
[this documentation entry]: https://discord.com/developers/docs/resources/audit-log#audit-log-entry-object-audit-log-entry-structure
|
audit_reason
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/request.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/request.rs
|
ISC
|
pub const fn auto_moderation_action_metadata_duration_seconds(
seconds: u32,
) -> Result<(), ValidationError> {
if seconds <= AUTO_MODERATION_ACTION_METADATA_DURATION_SECONDS_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::AutoModerationActionMetadataDurationSeconds { seconds },
})
}
}
|
Ensure that the `duration_seconds` field for an auto moderation action
metadata is correct.
The duration must be at most [`AUTO_MODERATION_ACTION_METADATA_DURATION_SECONDS_MAX`].
This is based on [this documentation entry].
# Errors
Returns an error of type [`AutoModerationActionMetadataDurationSeconds`] if the
duration is invalid.
[`AutoModerationActionMetadataDurationSeconds`]: ValidationErrorType::AutoModerationActionMetadataDurationSeconds
[this documentation entry]: https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-action-object-action-metadata
|
auto_moderation_action_metadata_duration_seconds
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/request.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/request.rs
|
ISC
|
pub const fn auto_moderation_exempt_roles(roles: &[Id<RoleMarker>]) -> Result<(), ValidationError> {
let len = roles.len();
if len <= AUTO_MODERATION_EXEMPT_ROLES_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::AutoModerationExemptRoles { len },
})
}
}
|
Ensure that the `exempt_roles` field for an auto moderation rule is correct.
The length must be at most [`AUTO_MODERATION_EXEMPT_ROLES_MAX`]. This is based
on [this documentation entry].
# Errors
Returns an error of type [`AutoModerationExemptRoles`] if the length is
invalid.
[`AutoModerationExemptRoles`]: ValidationErrorType::AutoModerationExemptRoles
[this documentation entry]: https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-auto-moderation-rule-structure
|
auto_moderation_exempt_roles
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/request.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/request.rs
|
ISC
|
pub const fn auto_moderation_exempt_channels(
channels: &[Id<ChannelMarker>],
) -> Result<(), ValidationError> {
let len = channels.len();
if len <= AUTO_MODERATION_EXEMPT_CHANNELS_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::AutoModerationExemptChannels { len },
})
}
}
|
Ensure that the `exempt_channels` field for an auto moderation rule is correct.
The length must be at most [`AUTO_MODERATION_EXEMPT_CHANNELS_MAX`]. This is based
on [this documentation entry].
# Errors
Returns an error of type [`AutoModerationExemptChannels`] if the length is
invalid.
[`AutoModerationExemptChannels`]: ValidationErrorType::AutoModerationExemptChannels
[this documentation entry]: https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-auto-moderation-rule-structure
|
auto_moderation_exempt_channels
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/request.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/request.rs
|
ISC
|
pub const fn create_guild_ban_delete_message_seconds(seconds: u32) -> Result<(), ValidationError> {
if seconds <= CREATE_GUILD_BAN_DELETE_MESSAGE_SECONDS_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::CreateGuildBanDeleteMessageSeconds { seconds },
})
}
}
|
Ensure that the delete message seconds amount for the Create Guild Ban request
is correct.
The seconds must be at most [`CREATE_GUILD_BAN_DELETE_MESSAGE_SECONDS_MAX`]. This
is based on [this documentation entry].
# Errors
Returns an error of type [`CreateGuildBanDeleteMessageSeconds`] if the seconds is
invalid.
[`CreateGuildBanDeleteMessageSeconds`]: ValidationErrorType::CreateGuildBanDeleteMessageSeconds
[this documentation entry]: https://discord.com/developers/docs/resources/guild#create-guild-ban
|
create_guild_ban_delete_message_seconds
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/request.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/request.rs
|
ISC
|
pub fn guild_name(name: impl AsRef<str>) -> Result<(), ValidationError> {
let len = name.as_ref().chars().count();
if (GUILD_NAME_LENGTH_MIN..=GUILD_NAME_LENGTH_MAX).contains(&len) {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::GuildName { len },
})
}
}
|
Ensure that a guild name's length is correct.
The length must be at least [`GUILD_NAME_LENGTH_MIN`] and at most
[`GUILD_NAME_LENGTH_MAX`]. This is based on [this documentation entry].
# Errors
Returns an error of type [`GuildName`] if the length is invalid.
[`GuildName`]: ValidationErrorType::GuildName
[this documentation entry]: https://discord.com/developers/docs/resources/guild#guild-object
|
guild_name
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/request.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/request.rs
|
ISC
|
pub const fn guild_prune_days(days: u16) -> Result<(), ValidationError> {
if days >= GUILD_PRUNE_DAYS_MIN && days <= GUILD_PRUNE_DAYS_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::GuildPruneDays { days },
})
}
}
|
Ensure that the days to prune members from a guild is correct.
The days must be at least [`GUILD_PRUNE_DAYS_MIN`] and at most
[`GUILD_PRUNE_DAYS_MAX`]. This is based on [this documentation entry].
# Errors
Returns an error of type [`GuildPruneDays`] if the days is invalid.
[`GuildPruneDays`]: ValidationErrorType::GuildPruneDays
[this documentation entry]: https://discord.com/developers/docs/resources/guild#get-guild-prune-count
|
guild_prune_days
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/request.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/request.rs
|
ISC
|
pub const fn invite_max_age(max_age: u32) -> Result<(), ValidationError> {
if max_age <= INVITE_AGE_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::InviteMaxAge { max_age },
})
}
}
|
Ensure that the invite max age is correct.
The age must be at most [`INVITE_AGE_MAX`]. This is based on
[this documentation entry].
# Errors
Returns an error of type [`InviteMaxAge`] if the age is invalid.
[`InviteMaxAge`]: ValidationErrorType::InviteMaxAge
[this documentation entry]: https://discord.com/developers/docs/resources/channel#create-channel-invite
|
invite_max_age
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/request.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/request.rs
|
ISC
|
pub const fn invite_max_uses(max_uses: u16) -> Result<(), ValidationError> {
if max_uses <= INVITE_USES_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::InviteMaxUses { max_uses },
})
}
}
|
Ensure that the invite max uses is correct.
The age must be at most [`INVITE_USES_MAX`]. This is based on
[this documentation entry].
# Errors
Returns an error of type [`InviteMaxUses`] if the uses is invalid.
[`InviteMaxUses`]: ValidationErrorType::InviteMaxUses
[this documentation entry]: https://discord.com/developers/docs/resources/channel#create-channel-invite
|
invite_max_uses
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/request.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/request.rs
|
ISC
|
pub fn scheduled_event_description(description: impl AsRef<str>) -> Result<(), ValidationError> {
let len = description.as_ref().chars().count();
if (SCHEDULED_EVENT_DESCRIPTION_MIN..=SCHEDULED_EVENT_DESCRIPTION_MAX).contains(&len) {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::ScheduledEventDescription { len },
})
}
}
|
Ensure that a scheduled event's description is correct.
The length must be at least [`SCHEDULED_EVENT_DESCRIPTION_MIN`] and at most
[`SCHEDULED_EVENT_DESCRIPTION_MAX`]. This is based on
[this documentation entry].
# Errors
Returns an error of type [`ScheduledEventDescription`] if the length is
invalid.
[`ScheduledEventDescription`]: ValidationErrorType::ScheduledEventDescription
[this documentation entry]: https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-object-guild-scheduled-event-structure
|
scheduled_event_description
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/request.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/request.rs
|
ISC
|
pub fn scheduled_event_name(name: impl AsRef<str>) -> Result<(), ValidationError> {
let len = name.as_ref().chars().count();
if (SCHEDULED_EVENT_NAME_MIN..=SCHEDULED_EVENT_NAME_MAX).contains(&len) {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::ScheduledEventName { len },
})
}
}
|
Ensure that a scheduled event's name is correct.
The length must be at least [`SCHEDULED_EVENT_NAME_MIN`] and at most
[`SCHEDULED_EVENT_NAME_MAX`]. This is based on [this documentation entry].
# Errors
Returns an error of type [`ScheduledEventName`] if the length is invalid.
[`ScheduledEventName`]: ValidationErrorType::ScheduledEventName
[this documentation entry]: https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-object-guild-scheduled-event-structure
|
scheduled_event_name
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/request.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/request.rs
|
ISC
|
pub fn stage_topic(topic: impl AsRef<str>) -> Result<(), ValidationError> {
let len = topic.as_ref().chars().count();
if (STAGE_TOPIC_LENGTH_MIN..=STAGE_TOPIC_LENGTH_MAX).contains(&len) {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::StageTopic { len },
})
}
}
|
Ensure that the stage instance's topic length is correct.
The length must be at least [`STAGE_TOPIC_LENGTH_MIN`] and at most
[`STAGE_TOPIC_LENGTH_MAX`]. This is based on [this documentation entry].
# Errors
Returns an error of type [`StageTopic`] if the length is invalid.
[`StageTopic`]: ValidationErrorType::StageTopic
[this documentation entry]: https://discord.com/developers/docs/resources/stage-instance#stage-instance-object
|
stage_topic
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/request.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/request.rs
|
ISC
|
pub fn template_description(description: impl AsRef<str>) -> Result<(), ValidationError> {
let len = description.as_ref().chars().count();
if len <= TEMPLATE_DESCRIPTION_LENGTH_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::TemplateDescription { len },
})
}
}
|
Ensure that a guild template's description length is correct.
The length must be at most [`TEMPLATE_DESCRIPTION_LENGTH_MAX`]. This is
based on [this documentation entry].
# Errors
Returns an error of type [`TemplateDescription`] if the length is invalid.
[`TemplateDescription`]: ValidationErrorType::TemplateDescription
[this documentation entry]: https://discord.com/developers/docs/resources/guild-template#guild-template-object-guild-template-structure
|
template_description
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/request.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/request.rs
|
ISC
|
pub fn template_name(name: impl AsRef<str>) -> Result<(), ValidationError> {
let len = name.as_ref().chars().count();
if (TEMPLATE_NAME_LENGTH_MIN..=TEMPLATE_NAME_LENGTH_MAX).contains(&len) {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::TemplateName { len },
})
}
}
|
Ensure that a guild template's name length is correct.
The length must be at least [`TEMPLATE_NAME_LENGTH_MIN`] and at most
[`TEMPLATE_NAME_LENGTH_MAX`]. This is based on [this documentation entry].
# Errors
Returns an error of type [`TemplateName`] if the length is invalid.
[`TemplateName`]: ValidationErrorType::TemplateName
[this documentation entry]: https://discord.com/developers/docs/resources/guild-template#guild-template-object-guild-template-structure
|
template_name
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/request.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/request.rs
|
ISC
|
pub fn description(value: impl AsRef<str>) -> Result<(), StickerValidationError> {
let len = value.as_ref().chars().count();
if (STICKER_DESCRIPTION_LENGTH_MIN..=STICKER_DESCRIPTION_LENGTH_MAX).contains(&len) {
Ok(())
} else {
Err(StickerValidationError {
kind: StickerValidationErrorType::DescriptionInvalid,
})
}
}
|
Ensure that a sticker's description is correct.
The length must be at least [`STICKER_DESCRIPTION_LENGTH_MIN`] and at most
[`STICKER_DESCRIPTION_LENGTH_MAX`]. This is based on
[this documentation entry].
# Errors
Returns an error of type [`DescriptionInvalid`] if the length is invalid.
[`DescriptionInvalid`]: StickerValidationErrorType::DescriptionInvalid
[this documentation entry]: https://discord.com/developers/docs/resources/sticker#create-guild-sticker
|
description
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/sticker.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/sticker.rs
|
ISC
|
pub fn name(value: impl AsRef<str>) -> Result<(), StickerValidationError> {
let len = value.as_ref().chars().count();
if (STICKER_NAME_LENGTH_MIN..=STICKER_NAME_LENGTH_MAX).contains(&len) {
Ok(())
} else {
Err(StickerValidationError {
kind: StickerValidationErrorType::NameInvalid,
})
}
}
|
Ensure that a sticker's name is correct.
The length must be at least [`STICKER_NAME_LENGTH_MIN`] and at most
[`STICKER_NAME_LENGTH_MAX`]. This is based on [this documentation entry].
# Errors
Returns an error of type [`NameInvalid`] if the length is invalid.
[`NameInvalid`]: StickerValidationErrorType::NameInvalid
[this documentation entry]: https://discord.com/developers/docs/resources/sticker#create-guild-sticker
|
name
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/sticker.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/sticker.rs
|
ISC
|
pub fn tags(value: impl AsRef<str>) -> Result<(), StickerValidationError> {
let len = value.as_ref().chars().count();
if (STICKER_TAGS_LENGTH_MIN..=STICKER_TAGS_LENGTH_MAX).contains(&len) {
Ok(())
} else {
Err(StickerValidationError {
kind: StickerValidationErrorType::TagsInvalid,
})
}
}
|
Ensure that a sticker's tags is correct.
The length must be at least [`STICKER_TAGS_LENGTH_MIN`] and at most
[`STICKER_TAGS_LENGTH_MAX`]. This is based on [this documentation entry].
# Errors
Returns an error of type [`TagsInvalid`] if the length is invalid.
[`TagsInvalid`]: StickerValidationErrorType::TagsInvalid
[this documentation entry]: https://discord.com/developers/docs/resources/sticker#create-guild-sticker
|
tags
|
rust
|
twilight-rs/twilight
|
twilight-validate/src/sticker.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-validate/src/sticker.rs
|
ISC
|
pub async fn run(args: args::Args) -> Result<Option<FreezeSummary>, CollectError> {
if is_help_command(&args) {
return handle_help_subcommands(args);
}
let cryo_dir = build_cryo_directory(std::path::Path::new(&args.output_dir));
let args =
if args.datatype.is_empty() { load_or_remember_command(args, &cryo_dir)? } else { args };
if args.remember {
println!("remembering this command for future use\n");
remember::save_remembered_command(cryo_dir, &args)?;
}
// handle regular flow
run_freeze_process(args).await
}
|
Entry point to run the CLI application.
|
run
|
rust
|
paradigmxyz/cryo
|
crates/cli/src/run.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/cli/src/run.rs
|
Apache-2.0
|
fn is_help_command(args: &args::Args) -> bool {
args.datatype.first() == Some(&"help".to_string())
}
|
Check if the command is a help command.
|
is_help_command
|
rust
|
paradigmxyz/cryo
|
crates/cli/src/run.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/cli/src/run.rs
|
Apache-2.0
|
fn load_or_remember_command(
mut args: args::Args,
cryo_dir: &std::path::Path,
) -> Result<args::Args, CollectError> {
let remembered = remember::load_remembered_command(cryo_dir.to_path_buf())?;
// Warn if the remembered command comes from a different Cryo version.
if remembered.cryo_version != cryo_freeze::CRYO_VERSION {
eprintln!("remembered command comes from a different Cryo version, proceed with caution\n");
}
print_remembered_command(&remembered.command);
args = args.merge_with_precedence(remembered.args);
Ok(args)
}
|
Load a previously remembered command or return the current args.
|
load_or_remember_command
|
rust
|
paradigmxyz/cryo
|
crates/cli/src/run.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/cli/src/run.rs
|
Apache-2.0
|
fn print_remembered_command(command: &[String]) {
println!(
"{} {} {}",
"remembering previous command:".truecolor(170, 170, 170),
"cryo".bold().white(),
command.iter().skip(1).cloned().collect::<Vec<_>>().join(" ").white().bold()
);
println!();
}
|
Print the remembered command to the console.
|
print_remembered_command
|
rust
|
paradigmxyz/cryo
|
crates/cli/src/run.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/cli/src/run.rs
|
Apache-2.0
|
async fn run_freeze_process(args: args::Args) -> Result<Option<FreezeSummary>, CollectError> {
let t_start_parse = Some(SystemTime::now());
let (query, source, sink, env) = parse::parse_args(&args).await?;
let source = Arc::new(source);
let env = ExecutionEnv { t_start_parse, ..env }.set_start_time();
cryo_freeze::freeze(&query, &source, &sink, &env).await
}
|
Run the main freezing process with the provided arguments.
|
run_freeze_process
|
rust
|
paradigmxyz/cryo
|
crates/cli/src/run.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/cli/src/run.rs
|
Apache-2.0
|
fn print_general_help() {
args::Args::parse_from(vec!["cryo", "-h"]);
}
|
Print general help for the CLI tool.
|
print_general_help
|
rust
|
paradigmxyz/cryo
|
crates/cli/src/run.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/cli/src/run.rs
|
Apache-2.0
|
fn print_syntax_help() {
let content = cstr!(
r#"<white><bold>Block specification syntax</bold></white>
- can use numbers <white><bold>--blocks 5000 6000 7000</bold></white>
- can use ranges <white><bold>--blocks 12M:13M 15M:16M</bold></white>
- can use a parquet file <white><bold>--blocks ./path/to/file.parquet[:COLUMN_NAME]</bold></white>
- can use multiple parquet files <white><bold>--blocks ./path/to/files/*.parquet[:COLUMN_NAME]</bold></white>
- numbers can contain { _ . K M B } <white><bold>5_000 5K 15M 15.5M</bold></white>
- omitting range end means latest <white><bold>15.5M:</bold></white> == <white><bold>15.5M:latest</bold></white>
- omitting range start means 0 <white><bold>:700</bold></white> == <white><bold>0:700</bold></white>
- minus on start means minus end <white><bold>-1000:7000</bold></white> == <white><bold>6000:7000</bold></white>
- plus sign on end means plus start <white><bold>15M:+1000</bold></white> == <white><bold>15M:15.001K</bold></white>
- can use every nth value <white><bold>2000:5000:1000</bold></white> == <white><bold>2000 3000 4000</bold></white>
- can use n values total <white><bold>100:200/5</bold></white> == <white><bold>100 124 149 174 199</bold></white>
<white><bold>Transaction specification syntax</bold></white>
- can use transaction hashes <white><bold>--txs TX_HASH1 TX_HASH2 TX_HASH3</bold></white>
- can use a parquet file <white><bold>--txs ./path/to/file.parquet[:COLUMN_NAME]</bold></white>
(default column name is <white><bold>transaction_hash</bold></white>)
- can use multiple parquet files <white><bold>--txs ./path/to/ethereum__logs*.parquet</bold></white>"#
);
println!("{}", content);
}
|
Print syntax help for block and transaction specification.
|
print_syntax_help
|
rust
|
paradigmxyz/cryo
|
crates/cli/src/run.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/cli/src/run.rs
|
Apache-2.0
|
fn handle_detailed_help(args: args::Args) -> Result<(), CollectError> {
let args = args::Args { datatype: args.datatype[1..].to_vec(), ..args };
let (datatypes, schemas) = super::parse::schemas::parse_schemas(&args)?;
for datatype in datatypes.into_iter() {
if schemas.len() > 1 {
println!("\n");
}
if let Some(schema) = schemas.get(&datatype) {
cryo_freeze::print_dataset_info(datatype, schema);
} else {
return Err(err(format!("missing schema for datatype: {:?}", datatype).as_str()));
}
}
Ok(())
}
|
Handle detailed help by parsing schemas and printing dataset information.
|
handle_detailed_help
|
rust
|
paradigmxyz/cryo
|
crates/cli/src/run.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/cli/src/run.rs
|
Apache-2.0
|
pub(crate) fn parse_binary_arg(
inputs: &[String],
default_column: &str,
) -> Result<ParsedBinaryArg, ParseError> {
let mut parsed = HashMap::new();
// separate into files vs explicit
let (files, hex_strings): (Vec<&String>, Vec<&String>) = inputs.iter().partition(|tx| {
// strip off column name if present
match parse_file_column_reference(tx, default_column) {
Ok(reference) => std::path::Path::new(&reference.path).exists(),
_ => false,
}
});
// files columns
for path in files {
let reference = parse_file_column_reference(path, default_column)?;
let values = cryo_freeze::read_binary_column(&reference.path, &reference.column)
.map_err(|_e| ParseError::ParseError("could not read input".to_string()))?;
let key = BinaryInputList::ParquetColumn(reference.path, reference.column);
parsed.insert(key, values);
}
// explicit binary strings
if !hex_strings.is_empty() {
let hex_strings: Vec<String> = hex_strings.into_iter().cloned().collect();
let binary_vec = hex_strings_to_binary(&hex_strings)?;
parsed.insert(BinaryInputList::Explicit, binary_vec);
};
Ok(parsed)
}
|
parse binary argument list
each argument can be a hex string or a parquet column reference
each parquet column is loaded into its own list, hex strings loaded into another
|
parse_binary_arg
|
rust
|
paradigmxyz/cryo
|
crates/cli/src/parse/parse_utils.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/cli/src/parse/parse_utils.rs
|
Apache-2.0
|
pub async fn parse_query(args: &Args, source: Arc<Source>) -> Result<Query, ParseError> {
let (datatypes, schemas) = parse_schemas(args)?;
let arg_aliases = find_arg_aliases(args, &schemas);
let new_args =
if !arg_aliases.is_empty() { Some(apply_arg_aliases(args, arg_aliases)?) } else { None };
let args = new_args.as_ref().unwrap_or(args);
let (partitions, partitioned_by, time_dimension) =
partitions::parse_partitions(args, source, &schemas).await?;
let datatypes = cryo_freeze::cluster_datatypes(datatypes);
let labels = QueryLabels { align: args.align, reorg_buffer: args.reorg_buffer };
Ok(Query {
datatypes,
schemas,
time_dimension,
partitions,
partitioned_by,
exclude_failed: args.exclude_failed,
js_tracer: args.js_tracer.clone(),
labels,
})
}
|
parse Query struct from cli Args
|
parse_query
|
rust
|
paradigmxyz/cryo
|
crates/cli/src/parse/query.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/cli/src/parse/query.rs
|
Apache-2.0
|
pub async fn freeze(
query: &Query,
source: &Source,
sink: &FileOutput,
env: &ExecutionEnv,
) -> Result<Option<FreezeSummary>, CollectError> {
// check validity of query
query.is_valid()?;
// get partitions
let (payloads, skipping) = get_payloads(query, source, sink, env)?;
// print summary
if env.verbose >= 1 {
summaries::print_cryo_intro(query, source, sink, env, payloads.len() as u64)?;
}
// check dry run
if env.dry {
return Ok(None)
};
// check if empty
if payloads.is_empty() {
let results = FreezeSummary { skipped: skipping, ..Default::default() };
if env.verbose >= 1 {
summaries::print_cryo_conclusion(&results, query, env)
}
return Ok(Some(results))
}
// create initial report
if env.report {
reports::write_report(env, query, sink, None)?;
};
// perform collection
let results = freeze_partitions(env, payloads, skipping).await;
// create summary
if env.verbose >= 1 {
summaries::print_cryo_conclusion(&results, query, env)
}
// create final report
if env.report {
reports::write_report(env, query, sink, Some(&results))?;
};
// return
Ok(Some(results))
}
|
collect data and output as files
|
freeze
|
rust
|
paradigmxyz/cryo
|
crates/freeze/src/freeze.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/freeze/src/freeze.rs
|
Apache-2.0
|
pub fn partition(&self, partition_by: Vec<Dim>) -> Result<Vec<Partition>, CollectError> {
let mut outputs = vec![self.clone()];
for chunk_dimension in partition_by.iter() {
outputs = match chunk_dimension {
Dim::BlockNumber => partition!(outputs, block_numbers)?,
Dim::TransactionHash => partition!(outputs, transactions)?,
Dim::Address => partition!(outputs, addresses)?,
Dim::Contract => partition!(outputs, contracts)?,
Dim::FromAddress => partition!(outputs, from_addresses)?,
Dim::ToAddress => partition!(outputs, to_addresses)?,
Dim::CallData => partition!(outputs, call_datas)?,
Dim::Slot => partition!(outputs, slots)?,
Dim::Topic0 => partition!(outputs, topic0s)?,
Dim::Topic1 => partition!(outputs, topic1s)?,
Dim::Topic2 => partition!(outputs, topic2s)?,
Dim::Topic3 => partition!(outputs, topic3s)?,
}
}
Ok(outputs)
}
|
partition Partition along given partition dimensions
|
partition
|
rust
|
paradigmxyz/cryo
|
crates/freeze/src/types/partitions.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/freeze/src/types/partitions.rs
|
Apache-2.0
|
pub fn partition_with_labels(
&self,
labels: PartitionLabels,
partition_by: Vec<Dim>,
) -> Result<Vec<Partition>, CollectError> {
let mut outputs = vec![Partition { label: Some(Vec::new()), ..self.clone() }];
for chunk_dimension in partition_by.iter() {
let dim_labels = labels.dim(chunk_dimension);
outputs = match chunk_dimension {
Dim::BlockNumber => label_partition!(outputs, dim_labels, block_numbers)?,
Dim::TransactionHash => label_partition!(outputs, dim_labels, transactions)?,
Dim::Address => label_partition!(outputs, dim_labels, addresses)?,
Dim::Contract => label_partition!(outputs, dim_labels, contracts)?,
Dim::FromAddress => label_partition!(outputs, dim_labels, from_addresses)?,
Dim::ToAddress => label_partition!(outputs, dim_labels, to_addresses)?,
Dim::CallData => label_partition!(outputs, dim_labels, call_datas)?,
Dim::Slot => label_partition!(outputs, dim_labels, slots)?,
Dim::Topic0 => label_partition!(outputs, dim_labels, topic0s)?,
Dim::Topic1 => label_partition!(outputs, dim_labels, topic1s)?,
Dim::Topic2 => label_partition!(outputs, dim_labels, topic2s)?,
Dim::Topic3 => label_partition!(outputs, dim_labels, topic3s)?,
}
}
Ok(outputs)
}
|
partition while respecting labels, ignoring all labels currently in partition
each non-None entry in labels should have same length as number of self dim chunks
|
partition_with_labels
|
rust
|
paradigmxyz/cryo
|
crates/freeze/src/types/partitions.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/freeze/src/types/partitions.rs
|
Apache-2.0
|
pub fn param_sets(&self, inner_request_size: Option<u64>) -> Result<Vec<Params>, CollectError> {
let dims = self.dims();
let include_block_ranges = inner_request_size.is_some() && dims.contains(&Dim::BlockNumber);
let mut outputs = vec![Params::default()];
for dimension in self.dims().iter() {
let mut new = Vec::new();
match dimension {
Dim::BlockNumber => {
if !include_block_ranges {
parametrize!(outputs, new, self.block_numbers, block_number)
} else {
new = outputs
}
}
Dim::TransactionHash => {
parametrize!(outputs, new, self.transactions, transaction_hash)
}
Dim::Address => parametrize!(outputs, new, self.addresses, address),
Dim::Contract => parametrize!(outputs, new, self.contracts, contract),
Dim::FromAddress => parametrize!(outputs, new, self.from_addresses, from_address),
Dim::ToAddress => parametrize!(outputs, new, self.to_addresses, to_address),
Dim::CallData => parametrize!(outputs, new, self.call_datas, call_data),
Dim::Slot => parametrize!(outputs, new, self.slots, slot),
Dim::Topic0 => parametrize!(outputs, new, self.topic0s, topic0),
Dim::Topic1 => parametrize!(outputs, new, self.topic1s, topic1),
Dim::Topic2 => parametrize!(outputs, new, self.topic2s, topic2),
Dim::Topic3 => parametrize!(outputs, new, self.topic3s, topic3),
}
outputs = new;
}
// partition blocks by inner request size
let outputs = match (inner_request_size, self.block_numbers.clone(), include_block_ranges) {
(_, _, false) => outputs,
(Some(inner_request_size), Some(block_numbers), true) => {
let mut block_ranges = Vec::new();
for block_chunk in block_numbers.subchunk_by_size(&inner_request_size) {
match block_chunk {
BlockChunk::Range(start, end) => block_ranges.push(Some((start, end))),
BlockChunk::Numbers(values) => {
for value in values.iter() {
block_ranges.push(Some((*value, *value)))
}
}
}
}
let mut new_outputs = Vec::new();
for output in outputs.iter() {
for block_range in block_ranges.iter() {
new_outputs.push(Params { block_range: *block_range, ..output.clone() })
}
}
new_outputs
}
_ => {
return Err(CollectError::CollectError(
"insufficient block information present in partition".to_string(),
))
}
};
Ok(outputs)
}
|
iterate through param sets of Partition
|
param_sets
|
rust
|
paradigmxyz/cryo
|
crates/freeze/src/types/partitions.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/freeze/src/types/partitions.rs
|
Apache-2.0
|
pub fn n_chunks(&self, dim: &Dim) -> usize {
match dim {
Dim::BlockNumber => self.block_numbers.as_ref().map(|x| x.len()).unwrap_or(0),
Dim::TransactionHash => self.transactions.as_ref().map(|x| x.len()).unwrap_or(0),
Dim::Address => self.addresses.as_ref().map(|x| x.len()).unwrap_or(0),
Dim::Contract => self.contracts.as_ref().map(|x| x.len()).unwrap_or(0),
Dim::FromAddress => self.from_addresses.as_ref().map(|x| x.len()).unwrap_or(0),
Dim::ToAddress => self.to_addresses.as_ref().map(|x| x.len()).unwrap_or(0),
Dim::CallData => self.call_datas.as_ref().map(|x| x.len()).unwrap_or(0),
Dim::Slot => self.slots.as_ref().map(|x| x.len()).unwrap_or(0),
Dim::Topic0 => self.topic0s.as_ref().map(|x| x.len()).unwrap_or(0),
Dim::Topic1 => self.topic1s.as_ref().map(|x| x.len()).unwrap_or(0),
Dim::Topic2 => self.topic2s.as_ref().map(|x| x.len()).unwrap_or(0),
Dim::Topic3 => self.topic3s.as_ref().map(|x| x.len()).unwrap_or(0),
}
}
|
number of chunks for a particular dimension
|
n_chunks
|
rust
|
paradigmxyz/cryo
|
crates/freeze/src/types/partitions.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/freeze/src/types/partitions.rs
|
Apache-2.0
|
pub fn meta_chunks_stats(chunks: &[Partition]) -> PartitionStats {
chunks
.iter()
.map(|chunk| chunk.stats())
.fold(PartitionStats { ..Default::default() }, |acc, stats| acc.fold(stats))
}
|
compute stats for Vec of Partition's
|
meta_chunks_stats
|
rust
|
paradigmxyz/cryo
|
crates/freeze/src/types/partitions.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/freeze/src/types/partitions.rs
|
Apache-2.0
|
pub fn n_tasks(&self) -> usize {
self.datatypes.len() * self.partitions.len()
}
|
total number of tasks needed to perform query
|
n_tasks
|
rust
|
paradigmxyz/cryo
|
crates/freeze/src/types/queries.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/freeze/src/types/queries.rs
|
Apache-2.0
|
pub fn n_outputs(&self) -> usize {
self.datatypes.iter().map(|x| x.datatypes().len()).sum::<usize>() * self.partitions.len()
}
|
total number of outputs of query
|
n_outputs
|
rust
|
paradigmxyz/cryo
|
crates/freeze/src/types/queries.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/freeze/src/types/queries.rs
|
Apache-2.0
|
pub async fn get_tx_receipts_in_block(
&self,
block: &Block<Transaction>,
) -> Result<Vec<TransactionReceipt>> {
let block_number = block.header.number;
if let Ok(Some(receipts)) = self.get_block_receipts(block_number).await {
return Ok(receipts);
}
self.get_tx_receipts(block.transactions.clone()).await
}
|
Returns all receipts for a block.
Tries to use `eth_getBlockReceipts` first, and falls back to `eth_getTransactionReceipt`
|
get_tx_receipts_in_block
|
rust
|
paradigmxyz/cryo
|
crates/freeze/src/types/sources.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/freeze/src/types/sources.rs
|
Apache-2.0
|
pub async fn get_tx_receipts(
&self,
transactions: BlockTransactions<Transaction>,
) -> Result<Vec<TransactionReceipt>> {
let mut tasks = Vec::new();
for tx in transactions.as_transactions().unwrap() {
let tx_hash = *tx.inner.tx_hash();
let source = self.clone();
let task: task::JoinHandle<std::result::Result<TransactionReceipt, CollectError>> =
task::spawn(async move {
match source.get_transaction_receipt(tx_hash).await? {
Some(receipt) => Ok(receipt),
None => {
Err(CollectError::CollectError("could not find tx receipt".to_string()))
}
}
});
tasks.push(task);
}
let mut receipts = Vec::new();
for task in tasks {
match task.await {
Ok(receipt) => receipts.push(receipt?),
Err(e) => return Err(CollectError::TaskFailed(e)),
}
}
Ok(receipts)
}
|
Returns all receipts for vector of transactions using `eth_getTransactionReceipt`
|
get_tx_receipts
|
rust
|
paradigmxyz/cryo
|
crates/freeze/src/types/sources.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/freeze/src/types/sources.rs
|
Apache-2.0
|
pub async fn get_logs(&self, filter: &Filter) -> Result<Vec<Log>> {
let _permit = self.permit_request().await;
Self::map_err(self.provider.get_logs(filter).await)
}
|
Returns an array (possibly empty) of logs that match the filter
|
get_logs
|
rust
|
paradigmxyz/cryo
|
crates/freeze/src/types/sources.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/freeze/src/types/sources.rs
|
Apache-2.0
|
pub async fn trace_replay_block_transactions(
&self,
block: BlockNumberOrTag,
trace_types: Vec<TraceType>,
) -> Result<Vec<TraceResultsWithTransactionHash>> {
let _permit = self.permit_request().await;
Self::map_err(
self.provider.trace_replay_block_transactions(block.into(), &trace_types).await,
)
}
|
Replays all transactions in a block returning the requested traces for each transaction
|
trace_replay_block_transactions
|
rust
|
paradigmxyz/cryo
|
crates/freeze/src/types/sources.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/freeze/src/types/sources.rs
|
Apache-2.0
|
pub async fn trace_block_state_diffs(
&self,
block: u32,
include_transaction_hashes: bool,
) -> Result<(Option<u32>, Vec<Option<Vec<u8>>>, Vec<TraceResultsWithTransactionHash>)> {
// get traces
let result = self
.trace_replay_block_transactions(
BlockNumberOrTag::Number(block as u64),
vec![TraceType::StateDiff],
)
.await?;
// get transactions
let txs = if include_transaction_hashes {
let transactions = self
.get_block(block as u64, BlockTransactionsKind::Hashes)
.await?
.ok_or(CollectError::CollectError("could not find block".to_string()))?
.transactions;
match transactions {
BlockTransactions::Hashes(hashes) => {
hashes.into_iter().map(|tx| Some(tx.to_vec())).collect()
}
_ => return Err(CollectError::CollectError("wrong transaction format".to_string())),
}
} else {
vec![None; result.len()]
};
Ok((Some(block), txs, result))
}
|
Get state diff traces of block
|
trace_block_state_diffs
|
rust
|
paradigmxyz/cryo
|
crates/freeze/src/types/sources.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/freeze/src/types/sources.rs
|
Apache-2.0
|
pub async fn trace_transaction_state_diffs(
&self,
transaction_hash: Vec<u8>,
) -> Result<(Option<u32>, Vec<Option<Vec<u8>>>, Vec<TraceResults>)> {
let result = self
.trace_replay_transaction(
B256::from_slice(&transaction_hash),
vec![TraceType::StateDiff],
)
.await;
Ok((None, vec![Some(transaction_hash)], vec![result?]))
}
|
Get state diff traces of transaction
|
trace_transaction_state_diffs
|
rust
|
paradigmxyz/cryo
|
crates/freeze/src/types/sources.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/freeze/src/types/sources.rs
|
Apache-2.0
|
pub async fn get_block(
&self,
block_num: u64,
kind: BlockTransactionsKind,
) -> Result<Option<Block>> {
let _permit = self.permit_request().await;
Self::map_err(self.provider.get_block(block_num.into(), kind).await)
}
|
Gets the block at `block_num` (transaction hashes only)
|
get_block
|
rust
|
paradigmxyz/cryo
|
crates/freeze/src/types/sources.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/freeze/src/types/sources.rs
|
Apache-2.0
|
pub async fn get_block_by_hash(
&self,
block_hash: B256,
kind: BlockTransactionsKind,
) -> Result<Option<Block>> {
let _permit = self.permit_request().await;
Self::map_err(self.provider.get_block(block_hash.into(), kind).await)
}
|
Gets the block with `block_hash` (transaction hashes only)
|
get_block_by_hash
|
rust
|
paradigmxyz/cryo
|
crates/freeze/src/types/sources.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/freeze/src/types/sources.rs
|
Apache-2.0
|
pub async fn get_block_receipts(
&self,
block_num: u64,
) -> Result<Option<Vec<TransactionReceipt>>> {
let _permit = self.permit_request().await;
Self::map_err(self.provider.get_block_receipts(block_num.into()).await)
}
|
Returns all receipts for a block.
Note that this uses the `eth_getBlockReceipts` method which is not supported by all nodes.
Consider using `FetcherExt::get_tx_receipts_in_block` which takes a block, and falls back to
`eth_getTransactionReceipt` if `eth_getBlockReceipts` is not supported.
|
get_block_receipts
|
rust
|
paradigmxyz/cryo
|
crates/freeze/src/types/sources.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/freeze/src/types/sources.rs
|
Apache-2.0
|
pub async fn trace_block(
&self,
block_num: BlockNumber,
) -> Result<Vec<LocalizedTransactionTrace>> {
let _permit = self.permit_request().await;
Self::map_err(self.provider.trace_block(block_num.into()).await)
}
|
Returns traces created at given block
|
trace_block
|
rust
|
paradigmxyz/cryo
|
crates/freeze/src/types/sources.rs
|
https://github.com/paradigmxyz/cryo/blob/master/crates/freeze/src/types/sources.rs
|
Apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.