themultiplexer 8 years ago
parent
commit
6783e52892
3 changed files with 46 additions and 58 deletions
  1. 18
    19
      hw6/task1/src/main.rs
  2. 7
    15
      hw6/task2/src/command.rs
  3. 21
    24
      hw6/task2/src/shell.rs

+ 18
- 19
hw6/task1/src/main.rs View File

@@ -10,7 +10,7 @@ use nix::sys::wait::WaitStatus;
10 10
 use nix::unistd::ForkResult::{Child, Parent};
11 11
 use std::os::unix::io::RawFd;
12 12
 
13
-const BUFFER_SIZE : usize = 256;
13
+const BUFFER_SIZE: usize = 256;
14 14
 
15 15
 
16 16
 fn main() {
@@ -18,13 +18,12 @@ fn main() {
18 18
     let arguments: Vec<String> = args().collect();
19 19
 
20 20
     if arguments.len() > 2 {
21
-        if let Ok((reader, writer)) = pipe(){
21
+        if let Ok((reader, writer)) = pipe() {
22 22
             let numbers = arguments[1..].to_vec();
23 23
 
24 24
             let pid = fork();
25 25
             match pid {
26 26
                 Ok(Child) => {
27
-
28 27
                     match read_from_pipe(reader) {
29 28
                         Ok(msg_received) => {
30 29
                             let vec = split_into_strings(&msg_received);
@@ -36,34 +35,34 @@ fn main() {
36 35
                                         Ok(res) => println!("Sum = {}", res),
37 36
                                         Err(e) => println!("{}", e),
38 37
                                     }
39
-                                },
40
-                                Ok(Parent{..}) => {
38
+                                }
39
+                                Ok(Parent { .. }) => {
41 40
                                     if let Ok(ws) = wait() {
42
-                                        if let WaitStatus::Exited(_,_) = ws {
41
+                                        if let WaitStatus::Exited(_, _) = ws {
43 42
                                             match mul_strings(vec) {
44 43
                                                 Ok(res) => println!("Mul = {}", res),
45 44
                                                 Err(e) => println!("{}", e),
46 45
                                             }
47 46
                                         }
48 47
                                     }
49
-                                },
48
+                                }
50 49
                                 Err(_) => println!("Fatal error: Fork failed"),
51 50
                             }
52 51
 
53
-                        },
54
-                        Err(_) => {},
52
+                        }
53
+                        Err(_) => {}
55 54
                     }
56
-
57
-
58 55
                 }
59 56
 
60
-                Ok(Parent{..}) => {
57
+                Ok(Parent { .. }) => {
61 58
                     let mut args = String::new();
62 59
                     for s in numbers {
63
-                        args = concatenate_strings(&args, &concatenate_strings(&s , " "));
60
+                        args = concatenate_strings(&args, &concatenate_strings(&s, " "));
64 61
                     }
65 62
                     println!("sending to children: {}", args);
66
-                    if let Err(_) = write(writer, args.as_bytes()) { println!("Broken pipe") }
63
+                    if let Err(_) = write(writer, args.as_bytes()) {
64
+                        println!("Broken pipe")
65
+                    }
67 66
 
68 67
                     if let Err(_) = wait() {
69 68
                         println!("Waiting on children failed")
@@ -80,15 +79,15 @@ fn main() {
80 79
 
81 80
 }
82 81
 
83
-fn read_from_pipe(reader:RawFd) -> Result<String, String>{
82
+fn read_from_pipe(reader: RawFd) -> Result<String, String> {
84 83
     let mut read_buf = [0u8; BUFFER_SIZE];
85
-    match read(reader, &mut read_buf){
84
+    match read(reader, &mut read_buf) {
86 85
         Ok(bytes_read) => {
87
-            match str::from_utf8(&read_buf[0 .. bytes_read]) {
86
+            match str::from_utf8(&read_buf[0..bytes_read]) {
88 87
                 Ok(msg_received) => Ok(msg_received.to_string()),
89 88
                 Err(_) => Err("Couldn't read".to_string()),
90 89
             }
91
-        },
90
+        }
92 91
         Err(_) => Err("Couldn't read".to_string()),
93 92
     }
94 93
 }
@@ -142,4 +141,4 @@ fn mul_strings(v: Vec<String>) -> Result<i32, String> {
142 141
         }
143 142
     }
144 143
     Ok(prod)
145
-}
144
+}

+ 7
- 15
hw6/task2/src/command.rs View File

@@ -17,28 +17,20 @@ impl FromStr for Command {
17 17
         let mut parts = s.split_whitespace();
18 18
 
19 19
         match parts.next() {
20
-            Some("exit") => {
21
-                Ok(Command::Exit)
22
-            },
23
-            Some("cd") => {
24
-                Ok(Command::parse_cd(parts.next()))
25
-            },
20
+            Some("exit") => Ok(Command::Exit),
21
+            Some("cd") => Ok(Command::parse_cd(parts.next())),
26 22
             Some(cmd) => {
27 23
                 //For use in next homework, to execute programs.
28 24
                 let _ = cmd;
29 25
                 Err(CommandNotFoundError)
30
-            },
31
-            None => {
32
-                Ok(Command::Empty)
33
-            },
26
+            }
27
+            None => Ok(Command::Empty),
34 28
         }
35 29
     }
36
-
37 30
 }
38 31
 
39 32
 
40 33
 impl Command {
41
-
42 34
     /// If the passed String exists, set the path of the Cd in the enum
43 35
     pub fn parse_cd(cmd: Option<&str>) -> Self {
44 36
         match cmd {
@@ -48,7 +40,7 @@ impl Command {
48 40
     }
49 41
 
50 42
     pub fn exec_cd(&self) {
51
-        if let Command::Cd(None) = *self  {
43
+        if let Command::Cd(None) = *self {
52 44
             let possible_home = env::home_dir();
53 45
 
54 46
             if let Some(home) = possible_home {
@@ -62,8 +54,8 @@ impl Command {
62 54
             match path.to_str() {
63 55
                 Some(_) => {
64 56
                     let _ = env::set_current_dir(path);
65
-                },
66
-                None => {},
57
+                }
58
+                None => {}
67 59
             }
68 60
 
69 61
         }

+ 21
- 24
hw6/task2/src/shell.rs View File

@@ -1,4 +1,4 @@
1
-use std::io::{BufRead,Write,Read, StdinLock, StdoutLock};
1
+use std::io::{BufRead, Write, Read, StdinLock, StdoutLock};
2 2
 use std::io;
3 3
 
4 4
 use command::*;
@@ -16,14 +16,14 @@ pub struct Shell<R, W> {
16 16
     pub name: String,
17 17
 }
18 18
 
19
-impl <'a> Shell<R<'a>, W<'a>> {
19
+impl<'a> Shell<R<'a>, W<'a>> {
20 20
     /// Creates a new Shell with a name, input and output.
21 21
     pub fn new(input: R<'a>, output: W<'a>, name: String) -> Self {
22 22
         Shell {
23
-            reader : input,
24
-            writer : output,
25
-            should_exit : false,
26
-            name : name,
23
+            reader: input,
24
+            writer: output,
25
+            should_exit: false,
26
+            name: name,
27 27
         }
28 28
     }
29 29
     /// Initializes the Shell Loop.
@@ -46,46 +46,44 @@ impl <'a> Shell<R<'a>, W<'a>> {
46 46
 
47 47
     /// Prints the shell prompt.
48 48
     /// Waits for user input and returns the read line.
49
-    fn prompt (&mut self) -> Result<String, &str> {
49
+    fn prompt(&mut self) -> Result<String, &str> {
50 50
         match env::current_dir() {
51 51
             Ok(pwd) => {
52
-                let _ = self.writer.write(format!("{} {} > ", self.name, pwd.display()).as_bytes());
52
+                let _ = self.writer.write(
53
+                    format!("{} {} > ", self.name, pwd.display())
54
+                        .as_bytes(),
55
+                );
53 56
                 let _ = self.writer.flush();
54 57
 
55 58
                 let mut line: String = String::new();
56 59
                 let read_result = self.reader.read_line(&mut line);
57 60
                 match read_result {
58
-                    Ok(_) => {
59
-                        Ok(line)
60
-                    },
61
-                    Err(_) => {
62
-                        Err("Error reading.")
63
-                    },
61
+                    Ok(_) => Ok(line),
62
+                    Err(_) => Err("Error reading."),
64 63
                 }
65
-            },
64
+            }
66 65
             Err(_) => return Err("Path Error"),
67 66
         }
68 67
     }
69 68
 
70 69
     /// Runs a command.
71 70
     /// Currently only `cd` and `exit` are working.
72
-    fn run(&mut self, command: Command) -> Result<(), CommandNotFoundError>{
71
+    fn run(&mut self, command: Command) -> Result<(), CommandNotFoundError> {
73 72
 
74 73
         match command {
75
-            Command::Empty => {},
74
+            Command::Empty => {}
76 75
             Command::Exit => self.should_exit = true,
77 76
             Command::Cd(_) => {
78 77
                 command.exec_cd();
79
-            },
78
+            }
80 79
         }
81 80
         Ok(())
82 81
     }
83
-
84 82
 }
85 83
 
86 84
 /// Implement Read-Trait for Tuple-Struct R
87 85
 /// Simply calls `read` of StdinLock
88
-impl <'a>Read for R<'a> {
86
+impl<'a> Read for R<'a> {
89 87
     fn read(&mut self, buf: &mut [u8]) -> Result<usize, io::Error> {
90 88
         self.0.read(buf)
91 89
     }
@@ -93,7 +91,7 @@ impl <'a>Read for R<'a> {
93 91
 
94 92
 /// Implement BufRead-Trait for Tuple-Struct R
95 93
 /// Simply calls `fill_buff` and `consume` from StdinLock
96
-impl <'a>BufRead for R<'a> {
94
+impl<'a> BufRead for R<'a> {
97 95
     fn fill_buf(&mut self) -> Result<&[u8], io::Error> {
98 96
         self.0.fill_buf()
99 97
     }
@@ -105,13 +103,12 @@ impl <'a>BufRead for R<'a> {
105 103
 
106 104
 /// Implement Write-Trait for Tuple-Struct W
107 105
 /// Simply calls `write` and `flush` from StdoutLock
108
-impl <'a>Write for W<'a> {
106
+impl<'a> Write for W<'a> {
109 107
     fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
110 108
         self.0.write(buf)
111 109
     }
112 110
 
113
-    fn flush(&mut self) -> Result<(),  io::Error> {
111
+    fn flush(&mut self) -> Result<(), io::Error> {
114 112
         self.0.flush()
115 113
     }
116 114
 }
117
-

Loading…
Cancel
Save