feat(protocol): add typed command decoding and dispatch
- add Command enum for protocol command codes - convert raw u8 command values via TryFrom - validate commands through Command conversion - dispatch decoded commands in Connection - reject unknown command codes
This commit is contained in:
+41
-7
@@ -44,6 +44,43 @@ pub struct Header {
|
||||
body_size: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Command {
|
||||
/// Клиент загружает файл на сервер.
|
||||
Upload,
|
||||
|
||||
/// Клиент запрашивает скачивание файла с сервера.
|
||||
Download,
|
||||
|
||||
/// Клиент запрашивает удаление файла на сервере.
|
||||
Delete,
|
||||
|
||||
/// Клиент запрашивает информацию о файле.
|
||||
Stat,
|
||||
|
||||
/// Ответ на ранее отправленный запрос.
|
||||
Response,
|
||||
|
||||
/// Сервер передаёт клиенту запрошенный файл.
|
||||
FileData,
|
||||
}
|
||||
|
||||
impl TryFrom<u8> for Command {
|
||||
type Error = HeaderError;
|
||||
|
||||
fn try_from(value: u8) -> Result<Self, Self::Error> {
|
||||
match value {
|
||||
0x01 => Ok(Command::Upload), //клиент → сервер
|
||||
0x02 => Ok(Command::Download),
|
||||
0x03 => Ok(Command::Delete),
|
||||
0x04 => Ok(Command::Stat),
|
||||
0x80 => Ok(Command::Response),
|
||||
0x81 => Ok(Command::FileData),
|
||||
other => Err(HeaderError::UnsupportedCommand(other)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn decode_header(
|
||||
input: &[u8; HEADER_SIZE],
|
||||
) -> Result<Header, HeaderError> {
|
||||
@@ -97,8 +134,9 @@ impl Header {
|
||||
}
|
||||
|
||||
/// Возвращает код команды (например, 1, 2, 80 или 81)
|
||||
pub fn command(&self) -> u8 {
|
||||
self.command
|
||||
pub fn command(&self) -> Command {
|
||||
Command::try_from(self.command)
|
||||
.expect("Header уже прошёл валидацию команды")
|
||||
}
|
||||
|
||||
/// Возвращает битовые флаги пакета (уже прошедшие валидацию)
|
||||
@@ -128,11 +166,7 @@ impl Header {
|
||||
}
|
||||
|
||||
// Валидация command
|
||||
if self.command != 1 {
|
||||
return Err(
|
||||
HeaderError::UnsupportedCommand(self.command)
|
||||
);
|
||||
}
|
||||
Command::try_from(self.command)?;
|
||||
|
||||
// Валидация flags
|
||||
if !(0..=7).contains(&self.flags){
|
||||
|
||||
Reference in New Issue
Block a user