Skip to main content

twilight_gateway/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![doc = include_str!("../README.md")]
3#![warn(
4    clippy::missing_const_for_fn,
5    clippy::missing_docs_in_private_items,
6    clippy::pedantic,
7    missing_docs,
8    unsafe_code
9)]
10#![allow(
11    clippy::module_name_repetitions,
12    clippy::must_use_candidate,
13    clippy::unnecessary_wraps
14)]
15
16pub mod error;
17
18mod channel;
19mod command;
20#[cfg(any(feature = "zlib", feature = "zstd"))]
21mod compression;
22mod config;
23mod event;
24mod json;
25mod latency;
26mod message;
27mod ratelimiter;
28mod session;
29mod shard;
30mod stream;
31
32pub use self::{
33    channel::MessageSender,
34    command::Command,
35    config::{Config, ConfigBuilder},
36    event::EventTypeFlags,
37    json::parse,
38    latency::Latency,
39    message::Message,
40    ratelimiter::CommandRatelimiter,
41    session::Session,
42    shard::{Shard, ShardState},
43    stream::StreamExt,
44};
45pub use twilight_model::gateway::{CloseFrame, Intents, ShardId};
46
47#[doc(no_inline)]
48pub use twilight_gateway_queue as queue;
49#[doc(no_inline)]
50pub use twilight_model::gateway::event::{Event, EventType};
51
52/// Discord Gateway API version used by this crate.
53pub const API_VERSION: u8 = 10;
54
55/// Creates an iterator of a single bucket's worth of shard identifiers.
56///
57/// Each bucket holds a consecutive range of identifiers and all identifiers
58/// share the same `total` value.
59///
60/// # Strategy
61///
62/// Shards may be bucketed per-thread for a thread-per-core architecture and/or
63/// per-machine for horizontal scaling.
64///
65/// # Examples
66///
67/// Create 1 bucket with the recommended shard count:
68///
69/// ```no_run
70/// use std::env;
71/// use twilight_http::Client;
72///
73/// # #[tokio::main(flavor = "current_thread")]
74/// # async fn main() -> anyhow::Result<()> {
75/// let http = Client::new(env::var("TOKEN")?);
76/// let info = http.gateway().authed().await?.model().await?;
77///
78/// let shards = twilight_gateway::bucket(0, 1, info.shards);
79/// assert_eq!(shards.len(), info.shards as usize);
80/// # anyhow::Ok(())
81/// # }
82/// ```
83///
84/// Create 2 buckets with 25 identifiers:
85///
86/// ```
87/// let bucket_1 = twilight_gateway::bucket(0, 2, 25);
88/// let bucket_2 = twilight_gateway::bucket(1, 2, 25);
89///
90/// assert_eq!(bucket_1.len(), 13);
91/// assert_eq!(bucket_2.len(), 12);
92/// ```
93///
94/// # Panics
95///
96/// Panics if the bucket id is greater than or equal to the total number of
97/// buckets.
98#[inline]
99#[track_caller]
100pub fn bucket(
101    bucket_id: u16,
102    buckets: u16,
103    shards: u32,
104) -> impl DoubleEndedIterator<Item = ShardId> + ExactSizeIterator {
105    let bucket_id = u32::from(bucket_id);
106    let buckets = u32::from(buckets);
107    assert!(bucket_id < buckets, "bucket_id must be less than buckets");
108
109    let (q, r) = (shards / buckets, shards % buckets);
110
111    let len = q + u32::from(bucket_id < r);
112    let start = bucket_id * q + r.min(bucket_id);
113
114    // Compiler hint deduced from mathematical proof.
115    if shards < start + len {
116        std::process::abort();
117    }
118    (start..start + len).map(move |id| ShardId::new(id, shards))
119}