浏览代码

task1 uses Results. task2 maps errors now.

Joshua Rutschmann 7 年前
父节点
当前提交
c905b17f03
共有 4 个文件被更改,包括 65 次插入43 次删除
  1. 10
    8
      hw9/task1/src/lib.rs
  2. 7
    6
      hw9/task1/tests/task1.rs
  3. 38
    21
      hw9/task2/src/main.rs
  4. 10
    8
      hw9/task2/srv-commands/src/lib.rs

+ 10
- 8
hw9/task1/src/lib.rs 查看文件

@@ -1,4 +1,4 @@
1
-pub fn parse(message: &str) -> Command {
1
+pub fn parse(message: &str) -> Result<Command, ParseError> {
2 2
     let m: String = String::from(message);
3 3
     let mut line = m.lines();
4 4
     match line.next() {
@@ -7,18 +7,18 @@ pub fn parse(message: &str) -> Command {
7 7
             match str.next() {
8 8
                 Some("STAGE") => {
9 9
                     let msg = m[6..].trim_left();
10
-                    Command::Stage(msg.to_string())
10
+                    Ok(Command::Stage(msg.to_string()))
11 11
                 }
12 12
                 Some("CONTROL") => {
13 13
                     let cmd = m[8..].trim_left();
14
-                    Command::Control(cmd.to_string())
14
+                    Ok(Command::Control(cmd.to_string()))
15 15
                 }
16
-                Some("RETRIEVE") => Command::Retrieve,
17
-                Some(_) => Command::ParseError(ErrorType::UnknownCommand),
18
-                None => Command::ParseError(ErrorType::EmptyString),
16
+                Some("RETRIEVE") => Ok(Command::Retrieve),
17
+                Some(_) => Err(ParseError(ErrorType::UnknownCommand)),
18
+                None => Err(ParseError(ErrorType::EmptyString)),
19 19
             }
20 20
         }
21
-        None => Command::ParseError(ErrorType::EmptyString),
21
+        None => Err(ParseError(ErrorType::EmptyString)),
22 22
     }
23 23
 }
24 24
 
@@ -27,9 +27,11 @@ pub enum Command {
27 27
     Stage(String),
28 28
     Control(String),
29 29
     Retrieve,
30
-    ParseError(ErrorType),
31 30
 }
32 31
 
32
+#[derive(Debug, PartialEq)]
33
+pub struct ParseError(pub ErrorType);
34
+
33 35
 #[derive(Debug, PartialEq)]
34 36
 pub enum ErrorType {
35 37
     UnknownCommand,

+ 7
- 6
hw9/task1/tests/task1.rs 查看文件

@@ -7,41 +7,42 @@ mod tests {
7 7
     use self::task1::Command;
8 8
     use self::task1::ErrorType;
9 9
     use self::task1::parse;
10
+    use self::task1::ParseError;
10 11
 
11 12
     #[test]
12 13
     fn empty_returns_correct_command() {
13
-        assert_eq!(parse("\n"), Command::ParseError(ErrorType::EmptyString))
14
+        assert_eq!(parse("\n"), Err(ParseError(ErrorType::EmptyString)))
14 15
     }
15 16
 
16 17
     #[test]
17 18
     fn not_known_command_returns_correct_command() {
18 19
         assert_eq!(
19 20
             parse("Hello"),
20
-            Command::ParseError(ErrorType::UnknownCommand)
21
+            Err(ParseError(ErrorType::UnknownCommand))
21 22
         )
22 23
     }
23 24
 
24 25
     #[test]
25 26
     fn stage_returns_correct_command() {
26
-        assert_eq!(parse("STAGE Hello"), Command::Stage("Hello".to_string()))
27
+        assert_eq!(parse("STAGE Hello"), Ok(Command::Stage("Hello".to_string())))
27 28
     }
28 29
 
29 30
     #[test]
30 31
     fn control_returns_correct_command() {
31 32
         assert_eq!(
32 33
             parse("CONTROL Hello"),
33
-            Command::Control("Hello".to_string())
34
+            Ok(Command::Control("Hello".to_string()))
34 35
         )
35 36
     }
36 37
 
37 38
     #[test]
38 39
     fn retrieve_returns_correct_command() {
39
-        assert_eq!(parse("RETRIEVE"), Command::Retrieve)
40
+        assert_eq!(parse("RETRIEVE"), Ok(Command::Retrieve))
40 41
     }
41 42
 
42 43
     #[test]
43 44
     fn retrieve_with_arguments_returns_correct_command() {
44
-        assert_eq!(parse("RETRIEVE Hello"), Command::Retrieve)
45
+        assert_eq!(parse("RETRIEVE Hello"), Ok(Command::Retrieve))
45 46
     }
46 47
 
47 48
 }

+ 38
- 21
hw9/task2/src/main.rs 查看文件

@@ -8,7 +8,25 @@ use std::net::{TcpListener, TcpStream};
8 8
 use srv_commands::Command;
9 9
 use srv_config::Config;
10 10
 
11
-fn handle_client(stream: TcpStream, orders: &mut VecDeque<String>) {    
11
+#[derive(Debug)]
12
+pub enum HashServerError {
13
+    Parse(srv_commands::ParseError),
14
+    Io(std::io::Error),
15
+}
16
+
17
+impl From<std::io::Error> for HashServerError {
18
+    fn from(err: std::io::Error) -> HashServerError {
19
+        HashServerError::Io(err)
20
+    }
21
+}
22
+
23
+impl From<srv_commands::ParseError> for HashServerError {
24
+    fn from(err: srv_commands::ParseError) -> HashServerError {
25
+        HashServerError::Parse(err)
26
+    }
27
+}
28
+
29
+fn handle_client(stream: TcpStream, orders: &mut VecDeque<String>, config:&Config) {    
12 30
     let mut reader = BufReader::new(&stream);
13 31
 	let mut writer = BufWriter::new(&stream);
14 32
 	
@@ -20,32 +38,34 @@ fn handle_client(stream: TcpStream, orders: &mut VecDeque<String>) {
20 38
                     break;
21 39
                 }
22 40
 
23
-                let cmd = srv_commands::parse(&line.trim_right());
41
+                let cmd = srv_commands::parse(&line.trim_right()).map_err(HashServerError::Parse);
24 42
                 
25 43
                 match cmd {
26
-                    Command::Stage(str) => {
44
+                    Ok(Command::Stage(str)) => {
27 45
                         orders.push_front(str);
28 46
                     }
29
-                    Command::Retrieve => {
47
+                    Ok(Command::Retrieve) => {
30 48
                         if orders.is_empty() {
31 49
                             let _ = writer.write(b"No order on stage!\n");
32 50
 							
33 51
                         } else {
34 52
 							if let Some(latest_order) = orders.pop_front() {
35 53
 								let _ = writer.write(latest_order.as_bytes());
36
-								writer.write(b"\n");
54
+								let _ = writer.write(b"\n");
37 55
 							}
38 56
                         }
39 57
                     }
40
-                    Command::Control(ref control_string) => {
41
-                        println!("Received Control: {}", control_string);
58
+                    Ok(Command::Control(ref control_string)) => {
59
+                        if config.verbosity > 0 {
60
+                            println!("Received Control: {}", control_string);
61
+                        }
42 62
                     }
43
-                    Command::ParseError(_) => {
44
-                        println!("Error occurred: {:?}", cmd);
63
+                    Err(ref e) => {
64
+                        println!("Error occurred: {:?}", e);
45 65
                     }
46 66
                 }
47 67
 				
48
-				writer.flush();
68
+				let _ = writer.flush();
49 69
             },
50 70
             _ => {
51 71
                 break;
@@ -73,21 +93,18 @@ pub fn main() {
73 93
 		orders.push_front(String::from("Test1"));
74 94
 	}
75 95
 	
76
-    match TcpListener::bind(host) {
96
+    match TcpListener::bind(host).map_err(HashServerError::Io) {
77 97
         Ok(listener) => {
78
-            for stream in listener.incoming() {
79
-                match stream {
80
-                    Ok(stream) => {
81
-						if c.verbosity > 1 { println!("[DEBUG] New Client connected") }
82
-						handle_client(stream, &mut orders);
83
-						if c.verbosity > 1 { println!("[DEBUG] Client diconnected") }
84
-                    }
85
-                    Err(_) => { /* connection failed */ }
98
+            for s in listener.incoming() {
99
+                if let Ok(stream) = s {
100
+                    if c.verbosity > 1 { println!("[DEBUG] New Client connected") }
101
+                    handle_client(stream, &mut orders, &c);
102
+                    if c.verbosity > 1 { println!("[DEBUG] Client diconnected") }
86 103
                 }
87 104
             }
88 105
         }
89
-        Err(_) => {
90
-            println!("Error starting server.");
106
+        Err(e) => {
107
+            println!("{:?}", e);
91 108
         }
92 109
     }
93 110
 }

+ 10
- 8
hw9/task2/srv-commands/src/lib.rs 查看文件

@@ -1,4 +1,4 @@
1
-pub fn parse(message: &str) -> Command {
1
+pub fn parse(message: &str) -> Result<Command, ParseError> {
2 2
     let m: String = String::from(message);
3 3
     let mut line = m.lines();
4 4
     match line.next() {
@@ -7,18 +7,18 @@ pub fn parse(message: &str) -> Command {
7 7
             match str.next() {
8 8
                 Some("STAGE") => {
9 9
                     let msg = m[6..].trim_left();
10
-                    Command::Stage(msg.to_string())
10
+                    Ok(Command::Stage(msg.to_string()))
11 11
                 }
12 12
                 Some("CONTROL") => {
13 13
                     let cmd = m[8..].trim_left();
14
-                    Command::Control(cmd.to_string())
14
+                    Ok(Command::Control(cmd.to_string()))
15 15
                 }
16
-                Some("RETRIEVE") => Command::Retrieve,
17
-                Some(_) => Command::ParseError(ErrorType::UnknownCommand),
18
-                None => Command::ParseError(ErrorType::EmptyString),
16
+                Some("RETRIEVE") => Ok(Command::Retrieve),
17
+                Some(_) => Err(ParseError(ErrorType::UnknownCommand)),
18
+                None => Err(ParseError(ErrorType::EmptyString)),
19 19
             }
20 20
         }
21
-        None => Command::ParseError(ErrorType::EmptyString),
21
+        None => Err(ParseError(ErrorType::EmptyString)),
22 22
     }
23 23
 }
24 24
 
@@ -27,9 +27,11 @@ pub enum Command {
27 27
     Stage(String),
28 28
     Control(String),
29 29
     Retrieve,
30
-    ParseError(ErrorType),
31 30
 }
32 31
 
32
+#[derive(Debug, PartialEq)]
33
+pub struct ParseError(pub ErrorType);
34
+
33 35
 #[derive(Debug, PartialEq)]
34 36
 pub enum ErrorType {
35 37
     UnknownCommand,

正在加载...
取消
保存