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

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

17
         let mut parts = s.split_whitespace();
17
         let mut parts = s.split_whitespace();
18
 
18
 
19
         match parts.next() {
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
             Some(cmd) => {
22
             Some(cmd) => {
27
                 //For use in next homework, to execute programs.
23
                 //For use in next homework, to execute programs.
28
                 let _ = cmd;
24
                 let _ = cmd;
29
                 Err(CommandNotFoundError)
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
 impl Command {
33
 impl Command {
41
-
42
     /// If the passed String exists, set the path of the Cd in the enum
34
     /// If the passed String exists, set the path of the Cd in the enum
43
     pub fn parse_cd(cmd: Option<&str>) -> Self {
35
     pub fn parse_cd(cmd: Option<&str>) -> Self {
44
         match cmd {
36
         match cmd {
48
     }
40
     }
49
 
41
 
50
     pub fn exec_cd(&self) {
42
     pub fn exec_cd(&self) {
51
-        if let Command::Cd(None) = *self  {
43
+        if let Command::Cd(None) = *self {
52
             let possible_home = env::home_dir();
44
             let possible_home = env::home_dir();
53
 
45
 
54
             if let Some(home) = possible_home {
46
             if let Some(home) = possible_home {
62
             match path.to_str() {
54
             match path.to_str() {
63
                 Some(_) => {
55
                 Some(_) => {
64
                     let _ = env::set_current_dir(path);
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
-use std::io::{BufRead,Write,Read, StdinLock, StdoutLock};
1
+use std::io::{BufRead, Write, Read, StdinLock, StdoutLock};
2
 use std::io;
2
 use std::io;
3
 
3
 
4
 use command::*;
4
 use command::*;
16
     pub name: String,
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
     /// Creates a new Shell with a name, input and output.
20
     /// Creates a new Shell with a name, input and output.
21
     pub fn new(input: R<'a>, output: W<'a>, name: String) -> Self {
21
     pub fn new(input: R<'a>, output: W<'a>, name: String) -> Self {
22
         Shell {
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
     /// Initializes the Shell Loop.
29
     /// Initializes the Shell Loop.
46
 
46
 
47
     /// Prints the shell prompt.
47
     /// Prints the shell prompt.
48
     /// Waits for user input and returns the read line.
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
         match env::current_dir() {
50
         match env::current_dir() {
51
             Ok(pwd) => {
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
                 let _ = self.writer.flush();
56
                 let _ = self.writer.flush();
54
 
57
 
55
                 let mut line: String = String::new();
58
                 let mut line: String = String::new();
56
                 let read_result = self.reader.read_line(&mut line);
59
                 let read_result = self.reader.read_line(&mut line);
57
                 match read_result {
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
             Err(_) => return Err("Path Error"),
65
             Err(_) => return Err("Path Error"),
67
         }
66
         }
68
     }
67
     }
69
 
68
 
70
     /// Runs a command.
69
     /// Runs a command.
71
     /// Currently only `cd` and `exit` are working.
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
         match command {
73
         match command {
75
-            Command::Empty => {},
74
+            Command::Empty => {}
76
             Command::Exit => self.should_exit = true,
75
             Command::Exit => self.should_exit = true,
77
             Command::Cd(_) => {
76
             Command::Cd(_) => {
78
                 command.exec_cd();
77
                 command.exec_cd();
79
-            },
78
+            }
80
         }
79
         }
81
         Ok(())
80
         Ok(())
82
     }
81
     }
83
-
84
 }
82
 }
85
 
83
 
86
 /// Implement Read-Trait for Tuple-Struct R
84
 /// Implement Read-Trait for Tuple-Struct R
87
 /// Simply calls `read` of StdinLock
85
 /// Simply calls `read` of StdinLock
88
-impl <'a>Read for R<'a> {
86
+impl<'a> Read for R<'a> {
89
     fn read(&mut self, buf: &mut [u8]) -> Result<usize, io::Error> {
87
     fn read(&mut self, buf: &mut [u8]) -> Result<usize, io::Error> {
90
         self.0.read(buf)
88
         self.0.read(buf)
91
     }
89
     }
93
 
91
 
94
 /// Implement BufRead-Trait for Tuple-Struct R
92
 /// Implement BufRead-Trait for Tuple-Struct R
95
 /// Simply calls `fill_buff` and `consume` from StdinLock
93
 /// Simply calls `fill_buff` and `consume` from StdinLock
96
-impl <'a>BufRead for R<'a> {
94
+impl<'a> BufRead for R<'a> {
97
     fn fill_buf(&mut self) -> Result<&[u8], io::Error> {
95
     fn fill_buf(&mut self) -> Result<&[u8], io::Error> {
98
         self.0.fill_buf()
96
         self.0.fill_buf()
99
     }
97
     }
105
 
103
 
106
 /// Implement Write-Trait for Tuple-Struct W
104
 /// Implement Write-Trait for Tuple-Struct W
107
 /// Simply calls `write` and `flush` from StdoutLock
105
 /// Simply calls `write` and `flush` from StdoutLock
108
-impl <'a>Write for W<'a> {
106
+impl<'a> Write for W<'a> {
109
     fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
107
     fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
110
         self.0.write(buf)
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
         self.0.flush()
112
         self.0.flush()
115
     }
113
     }
116
 }
114
 }
117
-

Loading…
Cancel
Save