break out code generation
This commit is contained in:
parent
fbaf386ebb
commit
41175e487e
42
src/code_generator.rs
Normal file
42
src/code_generator.rs
Normal file
@ -0,0 +1,42 @@
|
||||
use rand::RngCore;
|
||||
use sha2::{Sha256, Digest};
|
||||
|
||||
pub struct CodeGenerator {
|
||||
counter: u64,
|
||||
salt: [u8; 32],
|
||||
}
|
||||
|
||||
impl CodeGenerator {
|
||||
pub fn generate(&mut self) -> String {
|
||||
let count = self.counter;
|
||||
self.counter += 1;
|
||||
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(self.salt);
|
||||
hasher.update(count.to_be_bytes());
|
||||
|
||||
format!("{:x}", hasher.finalize())[..6].to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for CodeGenerator {
|
||||
fn default() -> Self {
|
||||
let mut salt = [0; 32];
|
||||
rand::thread_rng().fill_bytes(&mut salt);
|
||||
|
||||
CodeGenerator {
|
||||
counter: 0,
|
||||
salt,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn test_generate() {
|
||||
let code = CodeGenerator::default().generate();
|
||||
assert_eq!(code.len(), 6);
|
||||
}
|
||||
}
|
35
src/main.rs
35
src/main.rs
@ -6,12 +6,11 @@ use std::collections::HashMap;
|
||||
mod message;
|
||||
use message::Message;
|
||||
|
||||
use rand::RngCore;
|
||||
mod code_generator;
|
||||
use code_generator::CodeGenerator;
|
||||
|
||||
use tungstenite::protocol::Message as WsMessage;
|
||||
|
||||
use sha2::{Sha256, Digest};
|
||||
|
||||
fn main() {
|
||||
let code_generator = Arc::new(Mutex::new(CodeGenerator::default()));
|
||||
let server = TcpListener::bind("127.0.0.1:8080").unwrap();
|
||||
@ -63,33 +62,3 @@ struct Room {
|
||||
struct Player {
|
||||
name: String,
|
||||
}
|
||||
|
||||
struct CodeGenerator {
|
||||
counter: u64,
|
||||
salt: [u8; 32],
|
||||
}
|
||||
|
||||
impl CodeGenerator {
|
||||
fn generate(&mut self) -> String {
|
||||
let count = self.counter;
|
||||
self.counter += 1;
|
||||
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(self.salt);
|
||||
hasher.update(count.to_be_bytes());
|
||||
|
||||
format!("{:x}", hasher.finalize())[..6].to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for CodeGenerator {
|
||||
fn default() -> Self {
|
||||
let mut salt = [0; 32];
|
||||
rand::thread_rng().fill_bytes(&mut salt);
|
||||
|
||||
CodeGenerator {
|
||||
counter: 0,
|
||||
salt,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -45,7 +45,6 @@ mod test {
|
||||
command: "COMMAND",
|
||||
args: vec!["arg1", "arg2"],
|
||||
}, msg);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user