Skip to content

Commit 7ed5143

Browse files
altonenalgesten
authored andcommitted
Fix ChannelId allocation
Use a counter to allocate channel IDs, ensuring that they're unique
1 parent 7bd99d8 commit 7ed5143

1 file changed

Lines changed: 33 additions & 2 deletions

File tree

src/channel.rs

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ impl fmt::Debug for ChannelData {
9999
#[derive(Debug, Default)]
100100
pub(crate) struct ChannelHandler {
101101
allocations: Vec<ChannelAllocation>,
102+
next_channel_id: usize,
102103
}
103104

104105
#[derive(Debug)]
@@ -115,7 +116,7 @@ struct ChannelAllocation {
115116

116117
impl ChannelHandler {
117118
pub fn new_channel(&mut self, config: &ChannelConfig) -> ChannelId {
118-
let id = ChannelId(self.allocations.len());
119+
let id = self.next_channel_id();
119120

120121
// For out-of-band negotiated, the id is already set.
121122
let sctp_stream_id = config.negotiated;
@@ -181,6 +182,14 @@ impl ChannelHandler {
181182
self.open_channels(sctp);
182183
}
183184

185+
/// Allocate next available `ChannelId`.
186+
fn next_channel_id(&mut self) -> ChannelId {
187+
let id = self.next_channel_id;
188+
self.next_channel_id += 1;
189+
190+
ChannelId(id)
191+
}
192+
184193
fn need_allocation(&self) -> bool {
185194
self.allocations.iter().any(|a| a.sctp_stream_id.is_none())
186195
}
@@ -255,7 +264,7 @@ impl ChannelHandler {
255264
.any(|a| a.sctp_stream_id == Some(sctp_stream_id));
256265

257266
if !exists {
258-
let id = ChannelId(self.allocations.len());
267+
let id = self.next_channel_id();
259268
let alloc = ChannelAllocation {
260269
id,
261270
sctp_stream_id: Some(sctp_stream_id),
@@ -280,3 +289,25 @@ impl ChannelHandler {
280289
self.allocations.retain(|a| a.id != id)
281290
}
282291
}
292+
293+
#[cfg(test)]
294+
mod tests {
295+
use super::*;
296+
297+
#[test]
298+
fn channel_id_allocation() {
299+
let mut handler = ChannelHandler::default();
300+
301+
// allocate first channel, get unique id
302+
assert_eq!(handler.new_channel(&Default::default()), ChannelId(0));
303+
304+
// allocate second channel, get unique id
305+
assert_eq!(handler.new_channel(&Default::default()), ChannelId(1));
306+
307+
// free channel 0, allocate two more channels and verify that the
308+
// new channels have unique IDs.
309+
handler.remove_channel(ChannelId(0));
310+
assert_eq!(handler.new_channel(&Default::default()), ChannelId(2));
311+
assert_eq!(handler.new_channel(&Default::default()), ChannelId(3));
312+
}
313+
}

0 commit comments

Comments
 (0)