Update process()

The process function no longer initializes a HashMap. Instead, it takes the shared handle to the HashMap as an argument. It also needs to lock the HashMap before using it.

  1. use tokio::net::TcpStream;
  2. use mini_redis::{Connection, Frame};
  3. async fn process(socket: TcpStream, db: Db) {
  4. use mini_redis::Command::{self, Get, Set};
  5. // Connection, provided by `mini-redis`, handles parsing frames from
  6. // the socket
  7. let mut connection = Connection::new(socket);
  8. while let Some(frame) = connection.read_frame().await.unwrap() {
  9. let response = match Command::from_frame(frame).unwrap() {
  10. Set(cmd) => {
  11. let mut db = db.lock().unwrap();
  12. db.insert(cmd.key().to_string(), cmd.value().clone());
  13. Frame::Simple("OK".to_string())
  14. }
  15. Get(cmd) => {
  16. let db = db.lock().unwrap();
  17. if let Some(value) = db.get(cmd.key()) {
  18. Frame::Bulk(value.clone())
  19. } else {
  20. Frame::Null
  21. }
  22. }
  23. cmd => panic!("unimplemented {:?}", cmd),
  24. };
  25. // Write the response to the client
  26. connection.write_frame(&response).await.unwrap();
  27. }
  28. }