1+ use std:: collections:: HashMap ;
2+ use std:: sync:: Arc ;
3+
14use anyhow:: Result ;
25use bytes:: { BufMut , BytesMut } ;
36use redis_starter_rust:: { command:: Command , resp} ;
47use tokio:: io:: { AsyncReadExt , AsyncWriteExt } ;
58use tokio:: net:: { TcpListener , TcpStream } ;
9+ use tokio:: sync:: Mutex ;
610
711#[ tokio:: main]
812async fn main ( ) -> Result < ( ) > {
13+ let cache = Arc :: new ( Mutex :: new ( HashMap :: new ( ) ) ) ;
914 println ! ( "Logs from your program will appear here!" ) ;
1015
1116 let listener = TcpListener :: bind ( "127.0.0.1:6379" ) . await ?;
@@ -15,9 +20,10 @@ async fn main() -> Result<()> {
1520 match incoming {
1621 Ok ( ( stream, _) ) => {
1722 println ! ( "new connection" ) ;
23+ let memory = cache. clone ( ) ;
1824
1925 tokio:: spawn ( async move {
20- handle_connection ( stream) . await . unwrap ( ) ;
26+ handle_connection ( stream, memory ) . await . unwrap ( ) ;
2127 } ) ;
2228 }
2329 Err ( e) => {
@@ -27,7 +33,10 @@ async fn main() -> Result<()> {
2733 }
2834}
2935
30- async fn handle_connection ( mut stream : TcpStream ) -> Result < ( ) > {
36+ async fn handle_connection (
37+ mut stream : TcpStream ,
38+ memory : Arc < Mutex < HashMap < String , String > > > ,
39+ ) -> Result < ( ) > {
3140 let mut buf = BytesMut :: with_capacity ( 512 ) ;
3241 loop {
3342 let bytes_read = stream. read_buf ( & mut buf) . await ?;
@@ -54,6 +63,22 @@ async fn handle_connection(mut stream: TcpStream) -> Result<()> {
5463
5564 stream. write_all ( & out) . await ?;
5665 }
66+ Command :: Get ( key) => {
67+ let mut out = BytesMut :: with_capacity ( 512 ) ;
68+ let mem = memory. lock ( ) . await ;
69+ let val = mem. get ( & key) . unwrap ( ) ;
70+
71+ out. put_slice ( b"+" ) ;
72+ out. put_slice ( & val. as_bytes ( ) ) ;
73+ out. put_slice ( b"\r \n " ) ;
74+
75+ stream. write_all ( & out) . await ?;
76+ }
77+ Command :: Set ( key, value) => {
78+ let mut mem = memory. lock ( ) . await ;
79+ mem. insert ( key, value) ;
80+ stream. write_all ( b"+OK\r \n " ) . await ?;
81+ }
5782 }
5883 } else {
5984 stream. write_all ( b"-ERR unknown command\r \n " ) . await ?;
0 commit comments