Skip to content

Commit

Permalink
Reformat code
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed Jun 7, 2024
1 parent 6b6924e commit 59c11bd
Show file tree
Hide file tree
Showing 57 changed files with 244 additions and 237 deletions.
2 changes: 1 addition & 1 deletion src/bin/tasha-cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
// Use of this source is governed by GNU Affero General Public License
// that can be found in the LICENSE file.

fn main() {}
fn main() {}
1 change: 0 additions & 1 deletion src/cluster/manager.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// Copyright (c) 2024 Xu Shaohua <[email protected]>. All rights reserved.
// Use of this source is governed by GNU Affero General Public License
// that can be found in the LICENSE file.

2 changes: 1 addition & 1 deletion src/cluster/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
// Use of this source is governed by GNU Affero General Public License
// that can be found in the LICENSE file.

mod manager;
mod manager;
39 changes: 21 additions & 18 deletions src/cmd/frame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ impl Frame {

pub fn into_bytes(self) -> Bytes {
match self {
Frame::Array(arr) => {
Self::Array(arr) => {
let mut bytes = BytesMut::new();
bytes.put_u8(b'*');
let len = arr.len();
Expand All @@ -59,7 +59,7 @@ impl Frame {

bytes.freeze()
}
Frame::Bulk(val) => {
Self::Bulk(val) => {
let len = val.len();
let mut bytes = BytesMut::new();
bytes.put_u8(b'$');
Expand All @@ -68,21 +68,21 @@ impl Frame {
bytes.put_slice(b"\r\n");
bytes.freeze()
}
Frame::Error(err) => {
Self::Error(err) => {
let mut bytes = BytesMut::new();
bytes.put_u8(b'-');
bytes.put(Bytes::from(err));
bytes.put_slice(b"\r\n");
bytes.freeze()
}
Frame::Integer(num) => {
Self::Integer(num) => {
let mut bytes = BytesMut::new();
bytes.put_u8(b':');
Self::write_i64(&mut bytes, num);
bytes.freeze()
}
Frame::Null => Bytes::from("$-1\r\n"),
Frame::Simple(s) => {
Self::Null => Bytes::from("$-1\r\n"),
Self::Simple(s) => {
let mut bytes = BytesMut::new();
bytes.put_u8(b'+');
bytes.put(Bytes::from(s));
Expand All @@ -96,7 +96,7 @@ impl Frame {
// NOTE(Shaohua): Replace String format with stack array.
let mut buf = [0u8; 32];
let mut cursor = Cursor::new(&mut buf[..]);
write!(&mut cursor, "{}", val).unwrap();
write!(&mut cursor, "{val}").unwrap();
let pos = cursor.position() as usize;
bytes.put(&cursor.get_ref()[0..pos]);
bytes.put_slice(b"\r\n");
Expand Down Expand Up @@ -144,7 +144,7 @@ impl Frame {
}
Ok(())
}
frame_type => Err(ParsingFrameError::InvalidFrameType(frame_type))
frame_type => Err(ParsingFrameError::InvalidFrameType(frame_type)),
}
}

Expand All @@ -153,22 +153,22 @@ impl Frame {
b'+' => {
let line = Self::get_line(cursor)?;
let s: String = String::from_utf8(line.to_vec())?;
Ok(Frame::Simple(s))
Ok(Self::Simple(s))
}
b'-' => {
let line = Self::get_line(cursor)?;
let s = String::from_utf8(line.to_vec())?;
Ok(Frame::Error(s))
Ok(Self::Error(s))
}
b':' => {
let val = Self::get_i64(cursor)?;
Ok(Frame::Integer(val))
Ok(Self::Integer(val))
}
b'$' => {
if b'-' == Self::peek_u8(cursor)? {
let line = Self::get_line(cursor)?;
if line == b"-1" {
Ok(Frame::Null)
Ok(Self::Null)
} else {
Err(ParsingFrameError::InvalidFrameFormat)
}
Expand All @@ -183,7 +183,7 @@ impl Frame {

let data = Bytes::copy_from_slice(&cursor.chunk()[..len]);
cursor.advance(n);
Ok(Frame::Bulk(data))
Ok(Self::Bulk(data))
}
}
b'*' => {
Expand All @@ -195,7 +195,7 @@ impl Frame {
}
log::info!("frame arr: {arr:?}");

Ok(Frame::Array(arr))
Ok(Self::Array(arr))
}
_ => unimplemented!(),
}
Expand Down Expand Up @@ -230,7 +230,7 @@ impl Frame {

fn get_i64(cursor: &mut Cursor<&[u8]>) -> Result<i64, ParsingFrameError> {
let line = Self::get_line(cursor)?;
atoi::<i64>(line).ok_or_else(|| ParsingFrameError::InvalidFrameFormat)
atoi::<i64>(line).ok_or(ParsingFrameError::InvalidFrameFormat)
}

/// Read one line from message.
Expand All @@ -250,7 +250,7 @@ impl Frame {

impl From<FromUtf8Error> for ParsingFrameError {
fn from(_err: FromUtf8Error) -> Self {
ParsingFrameError::InvalidFrameFormat
Self::InvalidFrameFormat
}
}

Expand All @@ -263,7 +263,10 @@ mod tests {
#[test]
fn test_parse_frame() {
let s = "2a320d0a24330d0a6765740d0a24340d0a6e616d650d0a";
let bytes: Vec<u8> = (0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()).collect();
let bytes: Vec<u8> = (0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
.collect();
let mut cursor = Cursor::new(&bytes[..]);
let ret = Frame::check_msg(&mut cursor);
assert!(ret.is_ok());
Expand All @@ -272,4 +275,4 @@ mod tests {
let ret = Frame::parse(&mut cursor);
assert!(ret.is_ok());
}
}
}
10 changes: 6 additions & 4 deletions src/cmd/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@
// Use of this source is governed by GNU Affero General Public License
// that can be found in the LICENSE file.


use crate::cmd::Command;
use crate::cmd::parse::{Parser, ParsingCommandError};
use crate::cmd::Command;

#[derive(Debug, Clone)]
pub enum ListCommand {
Expand All @@ -13,11 +12,14 @@ pub enum ListCommand {
}

impl ListCommand {
pub(super) fn parse(cmd_name: &str, _parser: &Parser) -> Result<Option<Command>, ParsingCommandError> {
pub(super) fn parse(
cmd_name: &str,
_parser: &Parser,
) -> Result<Option<Command>, ParsingCommandError> {
match cmd_name {
"lget" => todo!(),
"llen" => todo!(),
_ => Ok(None),
}
}
}
}
2 changes: 1 addition & 1 deletion src/cmd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ use crate::cmd::list::ListCommand;
use crate::cmd::string::StringCommand;

pub mod frame;
pub mod list;
mod parse;
pub mod string;
pub mod list;

#[derive(Debug, Clone)]
pub enum Command {
Expand Down
28 changes: 15 additions & 13 deletions src/cmd/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ use std::vec::IntoIter;

use bytes::Bytes;

use crate::cmd::Command;
use crate::cmd::frame::Frame;
use crate::cmd::list::ListCommand;
use crate::cmd::string::StringCommand;
use crate::cmd::Command;

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum ParsingCommandError {
Expand All @@ -30,17 +30,19 @@ impl TryFrom<Frame> for Command {
}
};

let mut parser = Parser { iter: arr.into_iter() };
let mut parser = Parser {
iter: arr.into_iter(),
};

let cmd_name = parser.next_string()?.to_ascii_lowercase();

// TODO(Shaohua): Add a command hash map.
let mut command: Option<Command> = StringCommand::parse(&cmd_name, &mut parser)?;
let mut command: Option<Self> = StringCommand::parse(&cmd_name, &mut parser)?;
if command.is_none() {
command = ListCommand::parse(&cmd_name, &parser)?;
}

command.ok_or_else(|| ParsingCommandError::CommandNotFound)
command.ok_or(ParsingCommandError::CommandNotFound)
}
}

Expand All @@ -50,20 +52,20 @@ pub struct Parser {

impl Parser {
pub fn next(&mut self) -> Result<Frame, ParsingCommandError> {
self.iter.next().ok_or(ParsingCommandError::InvalidParameter)
self.iter
.next()
.ok_or(ParsingCommandError::InvalidParameter)
}

pub fn next_string(&mut self) -> Result<String, ParsingCommandError> {
match self.next()? {
Frame::Simple(s) => Ok(s),
Frame::Bulk(bytes) => {
std::str::from_utf8(&bytes[..])
.map(|s| s.to_string())
.map_err(|err| {
log::warn!("Failed to parse string, got err: {err:?}");
ParsingCommandError::InvalidParameter
})
}
Frame::Bulk(bytes) => std::str::from_utf8(&bytes[..])
.map(std::string::ToString::to_string)
.map_err(|err| {
log::warn!("Failed to parse string, got err: {err:?}");
ParsingCommandError::InvalidParameter
}),
frame => {
log::warn!("Protocol error, expected simple or bulk frame, got: {frame:?}");
Err(ParsingCommandError::ProtocolError)
Expand Down
9 changes: 6 additions & 3 deletions src/cmd/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@

use bytes::Bytes;

use crate::cmd::Command;
use crate::cmd::parse::{Parser, ParsingCommandError};
use crate::cmd::Command;

#[derive(Debug, Clone)]
pub enum StringCommand {
Expand All @@ -15,7 +15,10 @@ pub enum StringCommand {
}

impl StringCommand {
pub fn parse(cmd_name: &str, parser: &mut Parser) -> Result<Option<Command>, ParsingCommandError> {
pub fn parse(
cmd_name: &str,
parser: &mut Parser,
) -> Result<Option<Command>, ParsingCommandError> {
let str_cmd = match cmd_name {
"get" => {
let key = parser.next_string()?;
Expand All @@ -35,4 +38,4 @@ impl StringCommand {

Ok(Some(Command::Str(str_cmd)))
}
}
}
4 changes: 2 additions & 2 deletions src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
// Use of this source is governed by GNU Affero General Public License
// that can be found in the LICENSE file.

use crate::cmd::Command;
use crate::cmd::frame::Frame;
use crate::cmd::Command;
use crate::listener::types::{SessionGid, SessionId};

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -45,4 +45,4 @@ pub struct DispatcherToMemCmd {
pub struct MemToDispatcherCmd {
pub session_gid: SessionGid,
pub frame: Frame,
}
}
2 changes: 1 addition & 1 deletion src/config/listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,4 +155,4 @@ impl Listener {
Ok(())
}
}
}
}
2 changes: 1 addition & 1 deletion src/config/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,4 +104,4 @@ impl Log {
pub const fn default_log_file() -> Option<String> {
None
}
}
}
2 changes: 1 addition & 1 deletion src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,4 @@ impl Config {
}
Ok(())
}
}
}
14 changes: 10 additions & 4 deletions src/dispatcher/listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,18 @@ use crate::dispatcher::Dispatcher;
use crate::error::Error;

impl Dispatcher {
pub(super) async fn handle_listener_cmd(&mut self, cmd: ListenerToDispatcherCmd) -> Result<(), Error> {
pub(super) async fn handle_listener_cmd(
&mut self,
cmd: ListenerToDispatcherCmd,
) -> Result<(), Error> {
match cmd {
ListenerToDispatcherCmd::Cmd(session_gid, command) => match command.category() {
CommandCategory::Mem => {
// Dispatch to mem module
let cmd = DispatcherToMemCmd { session_gid, command };
let cmd = DispatcherToMemCmd {
session_gid,
command,
};
Ok(self.mem_sender.send(cmd).await?)
}
CommandCategory::System => {
Expand All @@ -28,7 +34,7 @@ impl Dispatcher {
// Dispatch to storage module
todo!()
}
}
},
}
}
}
}
13 changes: 6 additions & 7 deletions src/dispatcher/mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,13 @@ impl Dispatcher {
// Send command to listener.
let listener_id = cmd.session_gid.listener_id();
if let Some(listener_sender) = self.listener_senders.get(&listener_id) {
let cmd = DispatcherToListenerCmd::Reply(
cmd.session_gid,
cmd.frame,
);
let cmd = DispatcherToListenerCmd::Reply(cmd.session_gid, cmd.frame);
Ok(listener_sender.send(cmd).await?)
} else {
Err(Error::from_string(ErrorKind::ChannelError,
format!("Failed to find listener with id: {listener_id}")))
Err(Error::from_string(
ErrorKind::ChannelError,
format!("Failed to find listener with id: {listener_id}"),
))
}
}
}
}
Loading

0 comments on commit 59c11bd

Please sign in to comment.