Skip to content

Commit 57b61c4

Browse files
authored
Merge pull request #4 from adhamsalama/implement-sub-multiple-channels
Implement subscribing to multiple channels
2 parents a9f070d + a902055 commit 57b61c4

File tree

4 files changed

+29
-19
lines changed

4 files changed

+29
-19
lines changed

Cargo.lock

+1-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
name = "sider"
33
description = "A Multithreaded Redis clone written from scratch in Rust."
44
license = "MIT"
5-
version = "0.1.3"
5+
version = "0.1.4"
66
edition = "2021"
77

88
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

src/handler.rs

+16-15
Original file line numberDiff line numberDiff line change
@@ -398,20 +398,21 @@ pub fn handle_subscribe(
398398
stream: TcpStream,
399399
) -> String {
400400
let mut bus = bus.write().unwrap();
401-
let value = bus.get_mut(&req.key);
402-
let topic_name = req.key.clone();
403-
let topic_name_len = topic_name.len();
404-
405-
let response = format!("*3\r\n$9\r\nsubscribe\r\n${topic_name_len}\r\n{topic_name}\r\n:1\r\n");
406-
// let stream: Arc<&mut TcpStream> = Arc::clone(&stream);
407-
match value {
408-
Some(streams) => {
409-
streams.push(stream);
410-
response
411-
}
412-
None => {
413-
bus.insert(topic_name, vec![stream]);
414-
response
415-
}
401+
let topics = &req.value;
402+
let mut response = String::new();
403+
for topic in topics {
404+
let channel = bus.get_mut(topic);
405+
let stream = stream.try_clone().unwrap();
406+
let topic_name_len = topic.len();
407+
response += &format!("*3\r\n$9\r\nsubscribe\r\n${topic_name_len}\r\n{topic}\r\n:1\r\n");
408+
match channel {
409+
Some(streams) => {
410+
streams.push(stream);
411+
}
412+
None => {
413+
bus.insert(topic.to_string(), vec![stream]);
414+
}
415+
};
416416
}
417+
response
417418
}

src/parser.rs

+11-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::collections::HashSet;
2+
13
use crate::{Command, Request};
24

35
pub fn parse_resp(s: &String) -> Request {
@@ -38,9 +40,16 @@ pub fn parse_resp(s: &String) -> Request {
3840
}
3941
}
4042
match command {
41-
Some(c) => {
43+
Some(command) => {
44+
if let Command::SUBSCRIBE = command {
45+
value.insert(0, key);
46+
// Remove duplicates as it's the official Redis behavior
47+
let set: HashSet<_> = value.drain(..).collect();
48+
value.extend(set);
49+
key = String::new();
50+
}
4251
let req = Request {
43-
command: c,
52+
command,
4453
key,
4554
value,
4655
};

0 commit comments

Comments
 (0)