Skip to content

Instantly share code, notes, and snippets.

@daxhuiberts
Created August 1, 2014 10:22
Show Gist options
  • Save daxhuiberts/8fe8c4f7f367e32260a5 to your computer and use it in GitHub Desktop.
Save daxhuiberts/8fe8c4f7f367e32260a5 to your computer and use it in GitHub Desktop.
proof of concept memcache server in rust
use std::collections::hashmap::HashMap;
use std::io::Acceptor;
use std::io::BufferedReader;
use std::io::Listener;
use std::io::TcpListener;
use std::sync::Arc;
use std::sync::RWLock;
fn main() {
let map = Arc::new(RWLock::new(HashMap::<String, String>::new()));
let mut acceptor = TcpListener::bind("127.0.0.1", 4567).listen().unwrap();
for stream in acceptor.incoming() {
let map = map.clone();
spawn(proc() {
let mut stream = stream.unwrap();
let mut reader = BufferedReader::new(stream.clone());
for line in reader.lines() {
let line = line.unwrap();
let slice = line.as_slice().trim_right();
let mut splits = slice.splitn(' ', 2);
match splits.next() {
Some("get") => {
match splits.next() {
Some(key) => {
let map = map.read();
let value = match map.find_equiv(&key) {
Some(string) => string.as_slice(),
None => "",
};
stream.write(value.as_bytes()).unwrap();
stream.write(b"\n").unwrap();
},
None => break,
}
},
Some("put") => {
match splits.next() {
Some(key) => {
let value = match splits.next() {
Some(string) => string,
None => "",
};
let mut map = map.write();
map.insert(key.to_string(), value.to_string());
stream.write(value.as_bytes()).unwrap();
stream.write(b"\n").unwrap();
},
None => break,
}
},
Some(_) => (),
None => break,
}
}
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment