First commit.
[crypto_lab1.git] / src / command.rs
diff --git a/src/command.rs b/src/command.rs
new file mode 100644 (file)
index 0000000..7de2afc
--- /dev/null
@@ -0,0 +1,69 @@
+use std::io;
+use std::rand::{ random, task_rng, distributions };
+use std::rand::distributions::IndependentSample;
+
+pub enum ReadingError {
+   ReadIOError(io::IoError)
+   // TODO...
+}
+
+pub enum WritingError {
+   WriteIOError(io::IoError)
+   // TODO...
+}
+
+pub type ReadingResult = Result<Packet, ReadingError>;
+pub type WritingResult = Result<(), WritingError>;
+
+pub enum PacketType {
+   CommandType,
+   AnswerType
+}
+
+pub struct CommandPacket {
+   t: PacketType,
+   timestamp: u64,
+   commandID: u8,
+   commandPayload: Vec<u8>
+}
+
+pub struct ErrorPacket {
+   timestamp: u64
+}
+
+pub enum Packet {
+   Command(CommandPacket),
+   Error(ErrorPacket)
+}
+
+impl Packet {
+   pub fn newRandomCommand(timestamp: u64) -> Packet {     
+         
+      let mut rng = task_rng();
+      Command(CommandPacket {
+         t: CommandType,
+         timestamp: timestamp, 
+         commandID: random::<u8>(),
+         commandPayload: Vec::from_fn(distributions::Range::new(7u, 40u).ind_sample(&mut rng), |idx| 0u8)
+      })
+   }
+
+   pub fn write(&self, output: &mut io::Writer) ->  WritingResult {
+      
+      match self {
+         &Command(ref command) => {
+            output.write_u8(0);
+            output.write_be_u64(command.timestamp);
+            
+            
+         },
+         &Error(error) => ()
+      }
+   
+      Ok(())
+   }
+   
+   pub fn read(input: &mut io::Reader) -> ReadingResult {
+      Ok(Packet::newRandomCommand(0))
+   }
+}
\ No newline at end of file