Skip to content

Commit

Permalink
Merge pull request #4 from adhamsalama/implement-sub-multiple-channels
Browse files Browse the repository at this point in the history
Implement subscribing to multiple channels
  • Loading branch information
adhamsalama authored Apr 19, 2023
2 parents a9f070d + a902055 commit 57b61c4
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 19 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
name = "sider"
description = "A Multithreaded Redis clone written from scratch in Rust."
license = "MIT"
version = "0.1.3"
version = "0.1.4"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand Down
31 changes: 16 additions & 15 deletions src/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -398,20 +398,21 @@ pub fn handle_subscribe(
stream: TcpStream,
) -> String {
let mut bus = bus.write().unwrap();
let value = bus.get_mut(&req.key);
let topic_name = req.key.clone();
let topic_name_len = topic_name.len();

let response = format!("*3\r\n$9\r\nsubscribe\r\n${topic_name_len}\r\n{topic_name}\r\n:1\r\n");
// let stream: Arc<&mut TcpStream> = Arc::clone(&stream);
match value {
Some(streams) => {
streams.push(stream);
response
}
None => {
bus.insert(topic_name, vec![stream]);
response
}
let topics = &req.value;
let mut response = String::new();
for topic in topics {
let channel = bus.get_mut(topic);
let stream = stream.try_clone().unwrap();
let topic_name_len = topic.len();
response += &format!("*3\r\n$9\r\nsubscribe\r\n${topic_name_len}\r\n{topic}\r\n:1\r\n");
match channel {
Some(streams) => {
streams.push(stream);
}
None => {
bus.insert(topic.to_string(), vec![stream]);
}
};
}
response
}
13 changes: 11 additions & 2 deletions src/parser.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::collections::HashSet;

use crate::{Command, Request};

pub fn parse_resp(s: &String) -> Request {
Expand Down Expand Up @@ -38,9 +40,16 @@ pub fn parse_resp(s: &String) -> Request {
}
}
match command {
Some(c) => {
Some(command) => {
if let Command::SUBSCRIBE = command {
value.insert(0, key);
// Remove duplicates as it's the official Redis behavior
let set: HashSet<_> = value.drain(..).collect();
value.extend(set);
key = String::new();
}
let req = Request {
command: c,
command,
key,
value,
};
Expand Down

0 comments on commit 57b61c4

Please sign in to comment.