pub struct InMemoryCache { /* private fields */ }
Expand description

An in-memory cache of Discord data.

This is an implementation of a cache designed to be used by only the current process.

Events will only be processed if they are properly expressed with Intents; refer to function-level documentation for more details.

Using the cache in multiple tasks

To use a cache instance in multiple tasks, consider wrapping it in an std::sync::Arc or std::rc::Rc.

Caution required

The cache uses a concurrent map for mutability of cached resources. Return types of methods are immutable references to those resources. If a resource is retrieved from the cache then care must be taken to only hold it for as long as necessary. If the cache needs to mutate a resource to update it and a reference to it is being held then calls to InMemoryCache::update may be blocked.

In order to avoid blocking of cache updates care must be taken to hold them for as little as possible. For example, consider dropping references during long-running tasks such as HTTP requests. Processing HTTP requests takes milliseconds to seconds; retrieving a new reference to a resource is on the scale of nanoseconds. If only a couple of small fields are necessary from a reference consider copying or cloning them.

Implementations§

source§

impl InMemoryCache

Implemented methods and types for the cache.

source

pub fn new() -> Self

Creates a new, empty cache.

Examples

Creating a new InMemoryCache with a custom configuration, limiting the message cache to 50 messages per channel:

use twilight_cache_inmemory::InMemoryCache;

let cache = InMemoryCache::builder().message_cache_size(50).build();
source

pub const fn builder() -> InMemoryCacheBuilder

Create a new builder to configure and construct an in-memory cache.

source

pub fn clear(&self)

Clear the state of the Cache.

This is equal to creating a new empty cache.

source

pub const fn config(&self) -> &Config

Returns a copy of the config cache.

source

pub const fn iter(&self) -> InMemoryCacheIter<'_>

Create an interface for iterating over the various resources in the cache.

Via the iterator interface many resource types can be iterated over including, but not limited to, emojis, guilds, presences, and users.

Examples

Iterate over every guild in the cache and print their IDs and names:

use twilight_cache_inmemory::InMemoryCache;

let cache = InMemoryCache::new();

// later in the application...
for guild in cache.iter().guilds() {
    println!("{}: {}", guild.id(), guild.name());
}
source

pub const fn stats(&self) -> InMemoryCacheStats<'_>

Create an interface for retrieving statistics about the cache.

Examples

Print the number of guilds in a cache:

use twilight_cache_inmemory::InMemoryCache;

let cache = InMemoryCache::new();

// later on...
let guilds = cache.stats().guilds();
println!("guild count: {guilds}");
source

pub const fn permissions(&self) -> InMemoryCachePermissions<'_>

Available on crate feature permission-calculator only.

Create an interface for retrieving the permissions of a member in a guild or channel.

ResourceTypes must be configured for the permission interface to properly work; refer to the permission module-level documentation for more information.

Examples

Calculate the permissions of a member in a guild channel:

use twilight_cache_inmemory::{InMemoryCache, ResourceType};
use twilight_model::id::Id;

let resource_types = ResourceType::CHANNEL | ResourceType::MEMBER | ResourceType::ROLE;

let cache = InMemoryCache::builder()
    .resource_types(resource_types)
    .build();

let channel_id = Id::new(4);
let user_id = Id::new(5);

let permissions = cache.permissions().in_channel(user_id, channel_id)?;
println!("member has these permissions: {permissions:?}");
source

pub fn update(&self, value: &impl UpdateCache)

Update the cache with an event from the gateway.

source

pub fn current_user(&self) -> Option<CurrentUser>

Gets the current user.

source

pub fn channel(
&self,
channel_id: Id<ChannelMarker>
) -> Option<Reference<'_, Id<ChannelMarker>, Channel>>

Gets a channel by ID.

source

pub fn channel_messages(
&self,
channel_id: Id<ChannelMarker>
) -> Option<Reference<'_, Id<ChannelMarker>, VecDeque<Id<MessageMarker>>>>

Gets the set of messages in a channel.

This requires the DIRECT_MESSAGES or GUILD_MESSAGES intents.

source

pub fn emoji(
&self,
emoji_id: Id<EmojiMarker>
) -> Option<Reference<'_, Id<EmojiMarker>, GuildResource<CachedEmoji>>>

Gets an emoji by ID.

This requires the GUILD_EMOJIS_AND_STICKERS intent.

source

pub fn guild(
&self,
guild_id: Id<GuildMarker>
) -> Option<Reference<'_, Id<GuildMarker>, CachedGuild>>

Gets a guild by ID.

This requires the GUILDS intent.

source

pub fn guild_channels(
&self,
guild_id: Id<GuildMarker>
) -> Option<Reference<'_, Id<GuildMarker>, HashSet<Id<ChannelMarker>>>>

Gets the set of channels in a guild.

This requires the GUILDS intent.

source

pub fn guild_emojis(
&self,
guild_id: Id<GuildMarker>
) -> Option<Reference<'_, Id<GuildMarker>, HashSet<Id<EmojiMarker>>>>

Gets the set of emojis in a guild.

This requires both the GUILDS and GUILD_EMOJIS_AND_STICKERS intents.

source

pub fn guild_integrations(
&self,
guild_id: Id<GuildMarker>
) -> Option<Reference<'_, Id<GuildMarker>, HashSet<Id<IntegrationMarker>>>>

Gets the set of integrations in a guild.

This requires the GUILD_INTEGRATIONS intent. The ResourceType::INTEGRATION resource type must be enabled.

source

pub fn guild_members(
&self,
guild_id: Id<GuildMarker>
) -> Option<Reference<'_, Id<GuildMarker>, HashSet<Id<UserMarker>>>>

Gets the set of members in a guild.

This list may be incomplete if not all members have been cached.

This requires the GUILD_MEMBERS intent.

source

pub fn guild_presences(
&self,
guild_id: Id<GuildMarker>
) -> Option<Reference<'_, Id<GuildMarker>, HashSet<Id<UserMarker>>>>

Gets the set of presences in a guild.

This list may be incomplete if not all members have been cached.

This requires the GUILD_PRESENCES intent.

source

pub fn guild_roles(
&self,
guild_id: Id<GuildMarker>
) -> Option<Reference<'_, Id<GuildMarker>, HashSet<Id<RoleMarker>>>>

Gets the set of roles in a guild.

This requires the GUILDS intent.

source

pub fn guild_stage_instances(
&self,
guild_id: Id<GuildMarker>
) -> Option<Reference<'_, Id<GuildMarker>, HashSet<Id<StageMarker>>>>

Gets the set of stage instances in a guild.

This requires the GUILDS intent.

source

pub fn guild_stickers(
&self,
guild_id: Id<GuildMarker>
) -> Option<Reference<'_, Id<GuildMarker>, HashSet<Id<StickerMarker>>>>

Gets the set of the stickers in a guild.

This is an O(m) operation, where m is the amount of stickers in the guild. This requires the GUILDS and GUILD_EMOJIS_AND_STICKERS intents and the STICKER resource type.

source

pub fn guild_voice_states(
&self,
guild_id: Id<GuildMarker>
) -> Option<Reference<'_, Id<GuildMarker>, HashSet<Id<UserMarker>>>>

Gets the set of voice states in a guild.

This requires both the GUILDS and GUILD_VOICE_STATES intents.

source

pub fn integration(
&self,
guild_id: Id<GuildMarker>,
integration_id: Id<IntegrationMarker>
) -> Option<Reference<'_, (Id<GuildMarker>, Id<IntegrationMarker>), GuildResource<GuildIntegration>>>

Gets an integration by guild ID and integration ID.

This requires the GUILD_INTEGRATIONS intent. The ResourceType::INTEGRATION resource type must be enabled.

source

pub fn member(
&self,
guild_id: Id<GuildMarker>,
user_id: Id<UserMarker>
) -> Option<Reference<'_, (Id<GuildMarker>, Id<UserMarker>), CachedMember>>

Gets a member by guild ID and user ID.

This requires the GUILD_MEMBERS intent.

source

pub fn message(
&self,
message_id: Id<MessageMarker>
) -> Option<Reference<'_, Id<MessageMarker>, CachedMessage>>

Gets a message by ID.

This requires one or both of the GUILD_MESSAGES or DIRECT_MESSAGES intents.

source

pub fn presence(
&self,
guild_id: Id<GuildMarker>,
user_id: Id<UserMarker>
) -> Option<Reference<'_, (Id<GuildMarker>, Id<UserMarker>), CachedPresence>>

Gets a presence by, optionally, guild ID, and user ID.

This requires the GUILD_PRESENCES intent.

source

pub fn role(
&self,
role_id: Id<RoleMarker>
) -> Option<Reference<'_, Id<RoleMarker>, GuildResource<Role>>>

Gets a role by ID.

This requires the GUILDS intent.

source

pub fn stage_instance(
&self,
stage_id: Id<StageMarker>
) -> Option<Reference<'_, Id<StageMarker>, GuildResource<StageInstance>>>

Gets a stage instance by ID.

This requires the GUILDS intent.

source

pub fn sticker(
&self,
sticker_id: Id<StickerMarker>
) -> Option<Reference<'_, Id<StickerMarker>, GuildResource<CachedSticker>>>

Gets a sticker by ID.

This is the O(1) operation. This requires the GUILDS and the GUILD_EMOJIS_AND_STICKERS intents and the STICKER resource type.

source

pub fn user(
&self,
user_id: Id<UserMarker>
) -> Option<Reference<'_, Id<UserMarker>, User>>

Gets a user by ID.

This requires the GUILD_MEMBERS intent.

source

pub fn user_guilds(
&self,
user_id: Id<UserMarker>
) -> Option<Reference<'_, Id<UserMarker>, HashSet<Id<GuildMarker>>>>

Get the guilds a user is in by ID.

Users are cached from a range of events such as InteractionCreate and MemberAdd, so although no specific intent is required to cache users the intents required for different events are required.

Requires the USER resource type.

source

pub fn voice_channel_states(
&self,
channel_id: Id<ChannelMarker>
) -> Option<VoiceChannelStates<'_>>

Gets the voice states within a voice channel.

This requires both the GUILDS and GUILD_VOICE_STATES intents.

source

pub fn voice_state(
&self,
user_id: Id<UserMarker>,
guild_id: Id<GuildMarker>
) -> Option<Reference<'_, (Id<GuildMarker>, Id<UserMarker>), CachedVoiceState>>

Gets a voice state by user ID and Guild ID.

This requires both the GUILDS and GUILD_VOICE_STATES intents.

source

pub fn member_highest_role(
&self,
guild_id: Id<GuildMarker>,
user_id: Id<UserMarker>
) -> Option<Id<RoleMarker>>

Gets the highest role of a member.

This requires both the GUILDS and GUILD_MEMBERS intents.

Trait Implementations§

source§

impl Debug for InMemoryCache

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for InMemoryCache

source§

fn default() -> InMemoryCache

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for Twhere
T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere
T: ?Sized,

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere
T: ?Sized,

const: unstable · source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for Twhere
U: From<T>,

const: unstable · source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for Twhere
U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere
U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
const: unstable · source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where
S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more