djs_cache/view.rs
1//! Borrowed read-only views of one resource (D-162), like a discord.js manager's `cache`.
2
3use core::{fmt, hash::Hash};
4use std::sync::Arc;
5
6use djs_model::{
7 channel::Channel,
8 id::{ChannelId, GuildId},
9};
10
11use crate::{
12 Backend,
13 limits::{ChannelScopedOf, Global, GlobalOf, Index, ScopedOf},
14};
15
16/// A resource kept over the whole cache (guilds, channels, users), as returned by
17/// [`Cache::guilds`](crate::Cache::guilds), [`Cache::channels`](crate::Cache::channels) and
18/// [`Cache::users`](crate::Cache::users).
19///
20/// A view of a disabled resource is empty. Every read is a snapshot: the cache may change
21/// right after it.
22///
23/// discord.js counterpart: `client.guilds.cache`, `client.channels.cache`, `client.users.cache`.
24///
25/// # Examples
26///
27/// ```
28/// use djs_cache::Cache;
29/// use djs_model::id::GuildId;
30///
31/// let cache = Cache::new();
32/// let guilds = cache.guilds();
33/// assert!(guilds.is_enabled());
34/// assert!(guilds.get(GuildId::new(1)).is_none());
35/// assert_eq!(guilds.len(), 0);
36/// ```
37pub struct CacheView<'a, K, V, B>
38where
39 K: Eq + Hash + Copy + Send + Sync + 'static,
40 V: Send + Sync + 'static,
41 B: Backend,
42{
43 entries: Option<&'a GlobalOf<K, V, B>>,
44 guild_index: Option<&'a Index<GuildId, K>>,
45}
46
47impl<'a, K, V, B> CacheView<'a, K, V, B>
48where
49 K: Eq + Hash + Copy + Send + Sync + 'static,
50 V: Send + Sync + 'static,
51 B: Backend,
52{
53 pub(crate) const fn new(
54 entries: Option<&'a GlobalOf<K, V, B>>,
55 guild_index: Option<&'a Index<GuildId, K>>,
56 ) -> Self {
57 Self {
58 entries,
59 guild_index,
60 }
61 }
62
63 /// Returns whether the resource is cached at all.
64 ///
65 /// discord.js counterpart: none (a manager's cache always exists in discord.js).
66 #[must_use]
67 pub const fn is_enabled(&self) -> bool {
68 self.entries.is_some()
69 }
70
71 /// Returns the entry with this ID.
72 ///
73 /// discord.js counterpart: `Collection#get`.
74 #[must_use]
75 pub fn get(&self, id: K) -> Option<Arc<V>> {
76 self.entries?.get(&id)
77 }
78
79 /// Returns whether an entry with this ID is cached.
80 ///
81 /// discord.js counterpart: `Collection#has`.
82 #[must_use]
83 pub fn contains(&self, id: K) -> bool {
84 self.entries.is_some_and(|entries| entries.contains(&id))
85 }
86
87 /// Returns the number of cached entries.
88 ///
89 /// discord.js counterpart: `Collection#size`.
90 #[must_use]
91 pub fn len(&self) -> usize {
92 self.entries.map_or(0, Global::len)
93 }
94
95 /// Returns whether nothing is cached.
96 ///
97 /// discord.js counterpart: `cache.size === 0`.
98 #[must_use]
99 pub fn is_empty(&self) -> bool {
100 self.len() == 0
101 }
102
103 /// Returns the IDs of every cached entry, in no particular order.
104 ///
105 /// discord.js counterpart: `Collection#keys` of a manager's `cache`.
106 #[must_use]
107 pub fn keys(&self) -> Vec<K> {
108 self.entries.map(Global::keys).unwrap_or_default()
109 }
110
111 /// Returns every cached entry, in no particular order.
112 ///
113 /// discord.js counterpart: `Collection#values` of a manager's `cache`.
114 #[must_use]
115 pub fn values(&self) -> Vec<Arc<V>> {
116 self.entries.map(Global::values).unwrap_or_default()
117 }
118}
119
120impl<B: Backend> CacheView<'_, ChannelId, Channel, B> {
121 /// Returns the IDs of the cached channels of a guild, in no particular order.
122 ///
123 /// discord.js counterpart: `guild.channels.cache`.
124 #[must_use]
125 pub fn in_guild(&self, guild_id: GuildId) -> Vec<ChannelId> {
126 self.guild_index
127 .map(|index| index.keys_of(guild_id))
128 .unwrap_or_default()
129 }
130}
131
132impl<K, V, B> fmt::Debug for CacheView<'_, K, V, B>
133where
134 K: Eq + Hash + Copy + Send + Sync + 'static,
135 V: Send + Sync + 'static,
136 B: Backend,
137{
138 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139 f.debug_struct("CacheView")
140 .field("enabled", &self.is_enabled())
141 .field("len", &self.len())
142 .finish()
143 }
144}
145
146/// A resource kept per guild (roles, emojis, stickers, members, …), for one guild, as
147/// returned by [`Cache::roles`](crate::Cache::roles), [`Cache::members`](crate::Cache::members)
148/// and the like.
149///
150/// A view of a disabled resource is empty. Every read is a snapshot: the cache may change
151/// right after it.
152///
153/// discord.js counterpart: `guild.roles.cache`, `guild.members.cache`, ….
154///
155/// # Examples
156///
157/// ```
158/// use djs_cache::Cache;
159/// use djs_model::id::{GuildId, RoleId};
160///
161/// let cache = Cache::new();
162/// let roles = cache.roles(GuildId::new(1));
163/// assert!(roles.is_enabled());
164/// assert!(roles.get(RoleId::new(2)).is_none());
165/// // Members are not cached by default.
166/// assert!(!cache.members(GuildId::new(1)).is_enabled());
167/// ```
168pub struct GuildView<'a, K, V, B>
169where
170 K: Eq + Hash + Copy + Send + Sync + 'static,
171 V: Send + Sync + 'static,
172 B: Backend,
173{
174 entries: Option<&'a ScopedOf<K, V, B>>,
175 guild_id: GuildId,
176}
177
178impl<'a, K, V, B> GuildView<'a, K, V, B>
179where
180 K: Eq + Hash + Copy + Send + Sync + 'static,
181 V: Send + Sync + 'static,
182 B: Backend,
183{
184 pub(crate) const fn new(entries: Option<&'a ScopedOf<K, V, B>>, guild_id: GuildId) -> Self {
185 Self { entries, guild_id }
186 }
187
188 /// Returns the guild this view is about.
189 ///
190 /// discord.js counterpart: a guild manager's `guild`.
191 #[must_use]
192 pub const fn guild_id(&self) -> GuildId {
193 self.guild_id
194 }
195
196 /// Returns whether the resource is cached at all.
197 ///
198 /// discord.js counterpart: none (a manager's cache always exists in discord.js).
199 #[must_use]
200 pub const fn is_enabled(&self) -> bool {
201 self.entries.is_some()
202 }
203
204 /// Returns the guild's entry with this ID.
205 ///
206 /// discord.js counterpart: `Collection#get`.
207 #[must_use]
208 pub fn get(&self, id: K) -> Option<Arc<V>> {
209 self.entries?.get(self.guild_id, id)
210 }
211
212 /// Returns whether the guild has a cached entry with this ID.
213 ///
214 /// discord.js counterpart: `Collection#has`.
215 #[must_use]
216 pub fn contains(&self, id: K) -> bool {
217 self.get(id).is_some()
218 }
219
220 /// Returns the number of the guild's cached entries.
221 ///
222 /// discord.js counterpart: `Collection#size`.
223 #[must_use]
224 pub fn len(&self) -> usize {
225 self.entries
226 .map_or(0, |entries| entries.len_of(self.guild_id))
227 }
228
229 /// Returns whether nothing of the guild is cached.
230 ///
231 /// discord.js counterpart: `cache.size === 0`.
232 #[must_use]
233 pub fn is_empty(&self) -> bool {
234 self.len() == 0
235 }
236
237 /// Returns the IDs of the guild's cached entries, in no particular order.
238 ///
239 /// discord.js counterpart: `Collection#keys` of a guild manager's `cache`.
240 #[must_use]
241 pub fn keys(&self) -> Vec<K> {
242 self.entries
243 .map(|entries| entries.keys_of(self.guild_id))
244 .unwrap_or_default()
245 }
246
247 /// Returns the guild's cached entries, in no particular order.
248 ///
249 /// discord.js counterpart: `Collection#values` of a guild manager's `cache`.
250 #[must_use]
251 pub fn values(&self) -> Vec<Arc<V>> {
252 self.entries
253 .map(|entries| entries.values_of(self.guild_id))
254 .unwrap_or_default()
255 }
256}
257
258impl<K, V, B> fmt::Debug for GuildView<'_, K, V, B>
259where
260 K: Eq + Hash + Copy + Send + Sync + 'static,
261 V: Send + Sync + 'static,
262 B: Backend,
263{
264 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265 f.debug_struct("GuildView")
266 .field("guild_id", &self.guild_id)
267 .field("enabled", &self.is_enabled())
268 .field("len", &self.len())
269 .finish()
270 }
271}
272
273/// A resource kept per channel (messages), for one channel, as returned by
274/// [`Cache::messages`](crate::Cache::messages).
275///
276/// A view of a disabled resource is empty. Every read is a snapshot: the cache may change
277/// right after it.
278///
279/// discord.js counterpart: `channel.messages.cache`.
280///
281/// # Examples
282///
283/// ```
284/// use djs_cache::{Cache, CacheConfig, Limit};
285/// use djs_model::id::{ChannelId, MessageId};
286///
287/// let cache = Cache::with_config(CacheConfig::builder().messages(Limit::Max(100)).build());
288/// let messages = cache.messages(ChannelId::new(1));
289/// assert!(messages.is_enabled());
290/// assert!(messages.get(MessageId::new(2)).is_none());
291/// ```
292pub struct ChannelView<'a, K, V, B>
293where
294 K: Eq + Hash + Copy + Send + Sync + 'static,
295 V: Send + Sync + 'static,
296 B: Backend,
297{
298 entries: Option<&'a ChannelScopedOf<K, V, B>>,
299 channel_id: ChannelId,
300}
301
302impl<'a, K, V, B> ChannelView<'a, K, V, B>
303where
304 K: Eq + Hash + Copy + Send + Sync + 'static,
305 V: Send + Sync + 'static,
306 B: Backend,
307{
308 pub(crate) const fn new(
309 entries: Option<&'a ChannelScopedOf<K, V, B>>,
310 channel_id: ChannelId,
311 ) -> Self {
312 Self {
313 entries,
314 channel_id,
315 }
316 }
317
318 /// Returns the channel this view is about.
319 ///
320 /// discord.js counterpart: a channel manager's `channel`.
321 #[must_use]
322 pub const fn channel_id(&self) -> ChannelId {
323 self.channel_id
324 }
325
326 /// Returns whether the resource is cached at all.
327 ///
328 /// discord.js counterpart: none (a manager's cache always exists in discord.js).
329 #[must_use]
330 pub const fn is_enabled(&self) -> bool {
331 self.entries.is_some()
332 }
333
334 /// Returns the channel's entry with this ID.
335 ///
336 /// discord.js counterpart: `Collection#get`.
337 #[must_use]
338 pub fn get(&self, id: K) -> Option<Arc<V>> {
339 self.entries?.get(self.channel_id, id)
340 }
341
342 /// Returns whether the channel has a cached entry with this ID.
343 ///
344 /// discord.js counterpart: `Collection#has`.
345 #[must_use]
346 pub fn contains(&self, id: K) -> bool {
347 self.get(id).is_some()
348 }
349
350 /// Returns the number of the channel's cached entries.
351 ///
352 /// discord.js counterpart: `Collection#size`.
353 #[must_use]
354 pub fn len(&self) -> usize {
355 self.entries
356 .map_or(0, |entries| entries.len_of(self.channel_id))
357 }
358
359 /// Returns whether nothing of the channel is cached.
360 ///
361 /// discord.js counterpart: `cache.size === 0`.
362 #[must_use]
363 pub fn is_empty(&self) -> bool {
364 self.len() == 0
365 }
366
367 /// Returns the IDs of the channel's cached entries, in no particular order.
368 ///
369 /// discord.js counterpart: `Collection#keys` of `MessageManager#cache`.
370 #[must_use]
371 pub fn keys(&self) -> Vec<K> {
372 self.entries
373 .map(|entries| entries.keys_of(self.channel_id))
374 .unwrap_or_default()
375 }
376
377 /// Returns the channel's cached entries, in no particular order.
378 ///
379 /// discord.js counterpart: `Collection#values` of `MessageManager#cache`.
380 #[must_use]
381 pub fn values(&self) -> Vec<Arc<V>> {
382 self.entries
383 .map(|entries| entries.values_of(self.channel_id))
384 .unwrap_or_default()
385 }
386}
387
388impl<K, V, B> fmt::Debug for ChannelView<'_, K, V, B>
389where
390 K: Eq + Hash + Copy + Send + Sync + 'static,
391 V: Send + Sync + 'static,
392 B: Backend,
393{
394 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
395 f.debug_struct("ChannelView")
396 .field("channel_id", &self.channel_id)
397 .field("enabled", &self.is_enabled())
398 .field("len", &self.len())
399 .finish()
400 }
401}