From 2a7a97f592ace2b4394c9d7ba4c128b5dc5a32b4 Mon Sep 17 00:00:00 2001 From: ennucore Date: Mon, 6 Dec 2021 15:00:38 +0300 Subject: [PATCH] Wrote TestInterface --- Cargo.lock | 21 ++++++++++- Cargo.toml | 1 + examples/test_ip_connection.rs | 1 + src/interface.rs | 67 ++++++++++++++++++++++++++++++++-- src/interfaces/ip.rs | 22 +++++------ src/lib.rs | 1 + src/message.rs | 3 -- src/transport.rs | 8 ++-- 8 files changed, 100 insertions(+), 24 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 30d9cb4..22c61f0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -237,6 +237,7 @@ dependencies = [ "serde", "serde_cbor", "sha2", + "spin 0.9.2", ] [[package]] @@ -245,7 +246,7 @@ version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" dependencies = [ - "spin", + "spin 0.5.2", ] [[package]] @@ -260,6 +261,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7d73b3f436185384286bd8098d17ec07c9a7d2388a6599f824d8502b529702a" +[[package]] +name = "lock_api" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712a4d093c9976e24e7dbca41db895dabcbac38eb5f4045393d17a95bdfb1109" +dependencies = [ + "scopeguard", +] + [[package]] name = "memoffset" version = "0.6.4" @@ -557,6 +567,15 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" +[[package]] +name = "spin" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "511254be0c5bcf062b019a6c89c01a664aa359ded62f78aa72c6fc137c0590e5" +dependencies = [ + "lock_api", +] + [[package]] name = "spki" version = "0.4.1" diff --git a/Cargo.toml b/Cargo.toml index 27c2cb0..5b67582 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,6 +20,7 @@ serde = { version = "1.0", features = ["derive", "alloc"], default-features = fa rayon = { version = "1.5.1", optional = true } core-error = "0.0.1-rc4" serde_cbor = "0.11.2" +spin = "0.9.2" [profile.dev.package.num-bigint-dig] opt-level = 3 diff --git a/examples/test_ip_connection.rs b/examples/test_ip_connection.rs index 9a31824..cc59e8e 100644 --- a/examples/test_ip_connection.rs +++ b/examples/test_ip_connection.rs @@ -15,6 +15,7 @@ fn main() { test(); } +#[cfg(feature = "std")] fn test() -> IFResult<()> { let message = *b"Hello world from iron forest"; diff --git a/src/interface.rs b/src/interface.rs index eeec7cf..4a38a57 100644 --- a/src/interface.rs +++ b/src/interface.rs @@ -48,16 +48,21 @@ pub mod test_interface { use crate::interface::{Interface, InterfaceRequirements, TargetingData}; use crate::message::MessageBytes; use crate::res::IFResult; + use alloc::string::String; use alloc::vec::Vec; + use alloc::vec; + use alloc::string::ToString; + use alloc::sync::Arc; + use spin::Mutex; #[derive(Default)] - pub struct TestInterface { + pub struct SimpleTestInterface { messages: Vec<(Vec, TargetingData)>, } - impl InterfaceRequirements for TestInterface {} + impl InterfaceRequirements for SimpleTestInterface {} - impl Interface for TestInterface { + impl Interface for SimpleTestInterface { fn main_loop_iteration(&mut self) -> IFResult<()> { Ok(()) } @@ -76,4 +81,60 @@ pub mod test_interface { Ok(self.messages.pop()) } } + + pub type Storage = Vec<(Vec, TargetingData)>; + + #[derive(Default)] + pub struct TestInterface { + this_peer_id: String, + storage: Arc>, + messages: Vec<(Vec, TargetingData)>, + } + + impl Interface for TestInterface { + fn main_loop_iteration(&mut self) -> IFResult<()> { + let mut storage_locked = self.storage.lock(); + while let Some(i) = storage_locked + .iter() + .position(|msg| msg.1 == self.this_peer_id) + { + self.messages.push(storage_locked.remove(i)); + } + Ok(()) + } + + fn id(&self) -> &str { + "test_interface" + } + + fn send(&mut self, message: &[u8], target: Option) -> IFResult<()> { + Ok(self + .storage + .lock() + .push((Vec::from(message), target.unwrap_or_default()))) + } + + fn receive(&mut self) -> IFResult> { + Ok(self.messages.pop()) + } + } + + impl InterfaceRequirements for TestInterface {} + + pub fn create_test_interfaces(n: usize) -> Vec { + let storage_mutex = Arc::new(Mutex::new(vec![])); + (0..n).map(|i| TestInterface { + this_peer_id: i.to_string(), + storage: storage_mutex.clone(), + messages: vec![], + }).collect() + } + + #[test] + fn test_test_interface() { + let mut interfaces = create_test_interfaces(2); + interfaces[0].send(b"123", Some("1".to_string())).unwrap(); + interfaces[1].main_loop_iteration().unwrap(); + assert_eq!(interfaces[1].receive().unwrap().unwrap().0.as_slice(), b"123"); + } } diff --git a/src/interfaces/ip.rs b/src/interfaces/ip.rs index e4e833c..d68b791 100644 --- a/src/interfaces/ip.rs +++ b/src/interfaces/ip.rs @@ -4,13 +4,10 @@ use std::thread; use alloc::vec; use alloc::vec::Vec; use alloc::string::{String, ToString}; -use core::cmp::min; use core::ops::RangeInclusive; -use core::str::from_utf8; use core::time::Duration; use crate::interface::{Interface, InterfaceRequirements, TargetingData}; -use crate::interfaces::ip::MessageType::PeerRequest; use crate::message::MessageBytes; use crate::res::{IFError, IFResult}; use crate::res::IFError::General; @@ -74,7 +71,7 @@ impl Interface for IPInterface { println!("New client: {:?}", addr); self.connections.push(stream) } - Err(e) => return Err(IFError::General(String::from("No incoming connection"))), + Err(_e) => return Err(IFError::General(String::from("No incoming connection"))), } println!("Hello from mainloop"); @@ -87,7 +84,7 @@ impl Interface for IPInterface { let mut message_take = connection.take(size as u64); let mut message: Vec = vec![]; - message_take.read_to_end(&mut message); + message_take.read_to_end(&mut message)?; let package = IPPackage {version, package_type, size, message}; self.package_queue.push(package); @@ -134,7 +131,7 @@ impl Interface for IPInterface { package_type: MessageType::Common, size: message.len() as u32, message: Vec::from(message), - }); + })?; println!("Sent message"); Ok(()) } @@ -148,7 +145,7 @@ impl Interface for IPInterface { impl IPInterface { pub fn new() -> IFResult { - let mut listener = match create_tcp_listener() { + let listener = match create_tcp_listener() { Some(listener) => listener, None => { return Err(IFError::General(String::from("Unable to open TCP listener"))); @@ -194,7 +191,7 @@ fn create_tcp_listener() -> Option { for port in SOCKET_RANGE { match net::TcpListener::bind("127.0.0.1:".to_owned() + &port.to_string()) { Ok(listener) => return Some(listener), - Err(e) => {} + Err(_e) => {} } }; None @@ -235,20 +232,19 @@ fn test_creating_connection() -> IFResult<()> { let mut interface2 = IPInterface::new()?; let t1 = std::thread::spawn(move || { - interface1.send(&message, Some(String::from("127.0.0.1:50001"))); + interface1.send(&message, Some(String::from("127.0.0.1:50001"))).unwrap(); interface1 }); thread::sleep(Duration::from_millis(10)); let t2 = std::thread::spawn(move || { - interface2.main_loop_iteration(); + interface2.main_loop_iteration().unwrap(); interface2 }); let res1 = t1.join(); match res1 { - Ok(mut res) => { + Ok(_res) => { println!("Thread Ok"); - } Err(e) => println!("{:?}", e) } @@ -258,7 +254,7 @@ fn test_creating_connection() -> IFResult<()> { println!("Thread Ok"); match res.receive() { Ok(tmp) => match tmp { - Some((message, metadata)) => println!("Received {:?}", message), + Some((message, _metadata)) => println!("Received {:?}", message), None => println!("None") } Err(e) => println!("{:?}", e) diff --git a/src/lib.rs b/src/lib.rs index 5131dd2..06b35b5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,6 +10,7 @@ extern crate rand; extern crate rsa; extern crate serde; extern crate core_error; +extern crate spin; mod crypto; mod ironforce; diff --git a/src/message.rs b/src/message.rs index defcc9e..53ccd9e 100644 --- a/src/message.rs +++ b/src/message.rs @@ -338,9 +338,6 @@ impl MessageBuilder { #[cfg(test)] use alloc::vec; -#[cfg(feature = "std")] -#[cfg(test)] -use std::println; #[test] fn test_hashing_message_type() { diff --git a/src/transport.rs b/src/transport.rs index f48f528..53ac106 100644 --- a/src/transport.rs +++ b/src/transport.rs @@ -147,11 +147,11 @@ impl Transport { } #[cfg(test)] -use crate::interface::test_interface::TestInterface; +use crate::interface::test_interface::SimpleTestInterface; #[test] fn test_adding_peer_to_transport() { - let mut transport = Transport::new(vec![Box::new(TestInterface::default())]); + let mut transport = Transport::new(vec![Box::new(SimpleTestInterface::default())]); let (interface_id, interface_targeting_data) = ("test_interface".to_string(), "hi".to_string()); assert!(transport.get_peer_by_parameters(interface_id.as_str(), interface_targeting_data.as_str()).is_none()); let peer_id = transport.find_or_add_peer(interface_id.clone(), interface_targeting_data.clone()); @@ -166,7 +166,7 @@ fn test_adding_peer_to_transport() { #[test] fn test_transport_sending() { - let mut transport = Transport::new(vec![Box::new(TestInterface::default())]); + let mut transport = Transport::new(vec![Box::new(SimpleTestInterface::default())]); let (interface_id, interface_targeting_data) = ("test_interface".to_string(), "hi".to_string()); let peer_id = transport.find_or_add_peer(interface_id.clone(), interface_targeting_data.clone()); transport.send_message(vec![239, 123], None).unwrap(); @@ -178,7 +178,7 @@ fn test_transport_sending() { #[test] fn test_transport_receiving() { - let mut transport = Transport::new(vec![Box::new(TestInterface::default())]); + let mut transport = Transport::new(vec![Box::new(SimpleTestInterface::default())]); let (interface_id, interface_targeting_data) = ("test_interface".to_string(), "hi".to_string()); let peer_id = transport.find_or_add_peer(interface_id.clone(), interface_targeting_data.clone()); transport.send_message(vec![239, 123], None).unwrap();