1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
use super::{Error, Writer};
use crate::helpers::RateLimit;
use std::io::Write;
pub trait WriterExt {
fn join_many<'a, I, S>(&self, channels: I) -> Result<(), Error>
where
I: IntoIterator<Item = S> + 'a,
S: AsRef<str> + 'a;
fn join_many_limited<'a, I, S>(
&self,
channels: I,
rate: Option<RateLimit>,
) -> Result<(), Error>
where
I: IntoIterator<Item = S> + 'a,
S: AsRef<str> + 'a;
}
impl<W: Write> WriterExt for Writer<W> {
fn join_many_limited<'a, I, S>(&self, channels: I, rate: Option<RateLimit>) -> Result<(), Error>
where
I: IntoIterator<Item = S> + 'a,
S: AsRef<str> + 'a,
{
join_limited(channels, self, true, rate)
}
fn join_many<'a, I, S>(&self, channels: I) -> Result<(), Error>
where
I: IntoIterator<Item = S> + 'a,
S: AsRef<str> + 'a,
{
join_limited(channels, self, false, None)
}
}
fn join_limited<'a, I, S, W>(
channels: I,
w: &Writer<W>,
try_rate: bool,
rate: Option<RateLimit>,
) -> Result<(), Error>
where
I: IntoIterator<Item = S> + 'a,
S: AsRef<str> + 'a,
W: Write,
{
use std::time::Duration;
let mut rate = if try_rate {
Some(rate.unwrap_or_else(|| RateLimit::full_unsync(50, Duration::from_secs(15))))
} else {
None
};
let cap = rate.as_ref().map(RateLimit::cap);
let mut buf = String::with_capacity(512);
let mut count = 0;
let mut prev = 0;
for channel in channels.into_iter() {
let channel = channel.as_ref();
if buf.len() + channel.len() + 1 > 510 || Some(count) == cap {
w.write_line(&buf)?;
buf.clear();
if let Some(ref mut rate) = &mut rate {
for _ in 0..if prev != 0 { prev } else { count } {
let _ = rate.take();
}
}
if let Some(cap) = cap {
prev = 0;
if count == cap {
count = 0
} else {
prev = cap - prev
}
}
}
if buf.is_empty() {
buf.push_str("JOIN ");
} else {
buf.push(',');
}
if !channel.starts_with('#') {
buf.push_str(&["#", channel].concat());
} else {
buf.push_str(&channel);
}
count += 1;
}
if !buf.is_empty() {
w.write_line(&buf)?;
}
Ok(())
}