client.rs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. use crate::{connection::Connection, error::Error, option, value::Value};
  2. use bytes::Bytes;
  3. use std::sync::Arc;
  4. pub async fn client(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
  5. let sub = unsafe { std::str::from_utf8_unchecked(&args[1]) }.to_string();
  6. let expected = match sub.to_lowercase().as_str() {
  7. "setname" => 3,
  8. _ => 2,
  9. };
  10. if args.len() != expected {
  11. return Err(Error::WrongArgument(
  12. "client".to_owned(),
  13. sub.to_uppercase(),
  14. ));
  15. }
  16. match sub.to_lowercase().as_str() {
  17. "id" => Ok((conn.id() as i64).into()),
  18. "info" => Ok(conn.info().as_str().into()),
  19. "getname" => Ok(option!(conn.name())),
  20. "list" => {
  21. let mut v: Vec<Value> = vec![];
  22. conn.all_connections()
  23. .iter(&mut |conn: Arc<Connection>| v.push(conn.info().as_str().into()));
  24. Ok(v.into())
  25. }
  26. "setname" => {
  27. let name = unsafe { std::str::from_utf8_unchecked(&args[2]) }.to_string();
  28. conn.set_name(name);
  29. Ok(Value::OK)
  30. }
  31. _ => Err(Error::WrongArgument(
  32. "client".to_owned(),
  33. sub.to_uppercase(),
  34. )),
  35. }
  36. }
  37. pub async fn echo(_conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
  38. Ok(Value::Blob(args[1].to_owned()))
  39. }
  40. pub async fn ping(_conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
  41. match args.len() {
  42. 1 => Ok(Value::String("PONG".to_owned())),
  43. 2 => Ok(Value::Blob(args[1].to_owned())),
  44. _ => Err(Error::InvalidArgsCount("ping".to_owned())),
  45. }
  46. }