From e469a58829937bb73b07f82d6a780becca617df3 Mon Sep 17 00:00:00 2001 From: Anand Bonde Date: Fri, 11 Jul 2025 11:59:07 -0700 Subject: [PATCH 1/2] demikernel: various code cleanup/improvements * Removed type annotations * Removed unnecessary `get_` prefix for obvious getters * Reduced visual clutter --- examples/rust/tcp-dump.rs | 4 +- examples/rust/tcp-pktgen.rs | 12 +- examples/rust/udp-dump.rs | 4 +- examples/rust/udp-echo.rs | 4 +- examples/rust/udp-pktgen.rs | 16 +- examples/rust/udp-relay.rs | 8 +- examples/tcp-close/args.rs | 10 +- examples/tcp-close/main.rs | 26 +-- src/catnap/linux/active_socket.rs | 4 +- src/catnap/linux/passive_socket.rs | 4 +- src/catnap/linux/socket.rs | 8 +- src/catnap/linux/transport.rs | 2 +- src/collections/async_queue.rs | 14 +- src/demikernel/bindings.rs | 5 +- src/demikernel/config.rs | 167 ++++++++---------- src/demikernel/libos/mod.rs | 20 +-- src/demikernel/libos/name.rs | 1 - src/demikernel/libos/network/libos.rs | 14 +- src/demikernel/libos/network/mod.rs | 9 +- src/demikernel/libos/network/queue.rs | 30 ++-- src/inetstack/config/arp.rs | 18 +- src/inetstack/mod.rs | 2 +- src/inetstack/protocols/layer3/arp/header.rs | 8 +- src/inetstack/protocols/layer3/arp/peer.rs | 48 ++--- src/inetstack/protocols/layer3/arp/tests.rs | 25 ++- src/inetstack/protocols/layer3/icmpv4/peer.rs | 6 +- src/inetstack/protocols/layer3/ipv4/header.rs | 6 +- src/inetstack/protocols/layer3/ipv4/tests.rs | 6 +- src/inetstack/protocols/layer3/mod.rs | 10 +- .../protocols/layer4/tcp/established/mod.rs | 2 +- .../layer4/tcp/established/receiver.rs | 6 +- .../layer4/tcp/established/sender.rs | 12 +- .../protocols/layer4/tcp/passive_open.rs | 2 +- .../protocols/layer4/tcp/tests/simulator.rs | 8 +- src/inetstack/test_helpers/engine.rs | 20 +-- src/inetstack/test_helpers/physical_layer.rs | 3 +- src/runtime/mod.rs | 11 +- src/runtime/network/transport.rs | 2 +- src/runtime/queue/mod.rs | 17 +- tests/rust/common/libos.rs | 2 +- tests/rust/udp-tests/args.rs | 2 +- tests/rust/udp-tests/main.rs | 4 +- 42 files changed, 271 insertions(+), 311 deletions(-) diff --git a/examples/rust/tcp-dump.rs b/examples/rust/tcp-dump.rs index 5002ffdb7..294b515c9 100644 --- a/examples/rust/tcp-dump.rs +++ b/examples/rust/tcp-dump.rs @@ -63,7 +63,7 @@ impl ProgramArguments { Ok(args) } - pub fn get_local_socket_addr(&self) -> SocketAddr { + pub fn local_socket_addr(&self) -> SocketAddr { self.local_socket_addr } @@ -82,7 +82,7 @@ impl Application { const LOG_INTERVAL_SECONDS: u64 = 5; pub fn new(mut libos: LibOS, args: &ProgramArguments) -> Result { - let local_socket_addr: SocketAddr = args.get_local_socket_addr(); + let local_socket_addr: SocketAddr = args.local_socket_addr(); let sockqd: QDesc = match libos.socket(AF_INET, SOCK_STREAM, 0) { Ok(sockqd) => sockqd, Err(e) => anyhow::bail!("failed to create socket: {:?}", e), diff --git a/examples/rust/tcp-pktgen.rs b/examples/rust/tcp-pktgen.rs index 95fa934f0..3f8fbb141 100644 --- a/examples/rust/tcp-pktgen.rs +++ b/examples/rust/tcp-pktgen.rs @@ -92,15 +92,15 @@ impl ProgramArguments { Ok(args) } - pub fn get_remote_socket_addr(&self) -> SocketAddr { + pub fn remote_socket_addr(&self) -> SocketAddr { self.remote_socket_addr } - pub fn get_bufsize(&self) -> usize { + pub fn bufsize(&self) -> usize { self.bufsize_bytes } - pub fn get_injection_rate(&self) -> u64 { + pub fn injection_rate(&self) -> u64 { self.injection_rate_microseconds } @@ -141,9 +141,9 @@ impl Application { const LOG_INTERVAL_SECONDS: u64 = 5; pub fn new(mut libos: LibOS, args: &ProgramArguments) -> Result { - let remote_socket_addr: SocketAddr = args.get_remote_socket_addr(); - let bufsize_bytes: usize = args.get_bufsize(); - let injection_rate_microseconds: u64 = args.get_injection_rate(); + let remote_socket_addr: SocketAddr = args.remote_socket_addr(); + let bufsize_bytes: usize = args.bufsize(); + let injection_rate_microseconds: u64 = args.injection_rate(); let sockqd: QDesc = match libos.socket(AF_INET, SOCK_STREAM, 0) { Ok(sockqd) => sockqd, diff --git a/examples/rust/udp-dump.rs b/examples/rust/udp-dump.rs index e1f30db5f..fd1b4a5ca 100644 --- a/examples/rust/udp-dump.rs +++ b/examples/rust/udp-dump.rs @@ -59,7 +59,7 @@ impl ProgramArguments { Ok(args) } - pub fn get_local_socket_addr(&self) -> SocketAddr { + pub fn local_socket_addr(&self) -> SocketAddr { self.local_socket_addr } @@ -78,7 +78,7 @@ impl Application { const LOG_INTERVAL_SECONDS: u64 = 5; pub fn new(mut libos: LibOS, args: &ProgramArguments) -> Result { - let local_socket_addr: SocketAddr = args.get_local_socket_addr(); + let local_socket_addr: SocketAddr = args.local_socket_addr(); let sockqd: QDesc = match libos.socket(AF_INET, SOCK_DGRAM, 0) { Ok(sockqd) => sockqd, Err(e) => anyhow::bail!("failed to create socket: {:?}", e), diff --git a/examples/rust/udp-echo.rs b/examples/rust/udp-echo.rs index 908531ce5..4a4a8b62c 100644 --- a/examples/rust/udp-echo.rs +++ b/examples/rust/udp-echo.rs @@ -73,7 +73,7 @@ impl ProgramArguments { Ok(args) } - pub fn get_local_socket_addr(&self) -> SocketAddr { + pub fn local_socket_addr(&self) -> SocketAddr { self.local_socket_addr } @@ -92,7 +92,7 @@ impl Application { const LOG_INTERVAL_SECONDS: u64 = 5; pub fn new(mut libos: LibOS, args: &ProgramArguments) -> Result { - let local_socket_addr: SocketAddr = args.get_local_socket_addr(); + let local_socket_addr: SocketAddr = args.local_socket_addr(); let sockqd: QDesc = match libos.socket(AF_INET_VALUE, SOCK_DGRAM, 0) { Ok(sockqd) => sockqd, Err(e) => anyhow::bail!("failed to create socket: {:?}", e), diff --git a/examples/rust/udp-pktgen.rs b/examples/rust/udp-pktgen.rs index 9d5c8a1c2..a5d1b4562 100644 --- a/examples/rust/udp-pktgen.rs +++ b/examples/rust/udp-pktgen.rs @@ -105,19 +105,19 @@ impl ProgramArguments { Ok(args) } - pub fn get_local_socket_addr(&self) -> SocketAddr { + pub fn local_socket_addr(&self) -> SocketAddr { self.local_socket_addr } - pub fn get_remote_socket_addr(&self) -> SocketAddr { + pub fn remote_socket_addr(&self) -> SocketAddr { self.remote_socket_addr } - pub fn get_bufsize(&self) -> usize { + pub fn bufsize(&self) -> usize { self.bufsize_bytes } - pub fn get_injection_rate(&self) -> u64 { + pub fn injection_rate(&self) -> u64 { self.injection_rate_microseconds } @@ -164,10 +164,10 @@ impl Application { const LOG_INTERVAL_SECONDS: u64 = 5; pub fn new(mut libos: LibOS, args: &ProgramArguments) -> Result { - let local_socket_addr: SocketAddr = args.get_local_socket_addr(); - let remote_socket_addr: SocketAddr = args.get_remote_socket_addr(); - let bufsize_byes: usize = args.get_bufsize(); - let injection_rate_microseconds: u64 = args.get_injection_rate(); + let local_socket_addr: SocketAddr = args.local_socket_addr(); + let remote_socket_addr: SocketAddr = args.remote_socket_addr(); + let bufsize_byes: usize = args.bufsize(); + let injection_rate_microseconds: u64 = args.injection_rate(); let sockqd: QDesc = match libos.socket(AF_INET, SOCK_DGRAM, 1) { Ok(sockqd) => sockqd, diff --git a/examples/rust/udp-relay.rs b/examples/rust/udp-relay.rs index 20d0f7f10..2e09abc77 100644 --- a/examples/rust/udp-relay.rs +++ b/examples/rust/udp-relay.rs @@ -74,11 +74,11 @@ impl ProgramArguments { Ok(args) } - pub fn get_local_socket_addr(&self) -> SocketAddr { + pub fn local_socket_addr(&self) -> SocketAddr { self.local_socket_addr } - pub fn get_remote_socket_addr(&self) -> SocketAddr { + pub fn remote_socket_addr(&self) -> SocketAddr { self.remote_socket_addr } @@ -103,8 +103,8 @@ impl Application { const LOG_INTERVAL_SECONDS: u64 = 5; pub fn new(mut libos: LibOS, args: &ProgramArguments) -> Result { - let local_socket_addr: SocketAddr = args.get_local_socket_addr(); - let remote_socket_addr: SocketAddr = args.get_remote_socket_addr(); + let local_socket_addr: SocketAddr = args.local_socket_addr(); + let remote_socket_addr: SocketAddr = args.remote_socket_addr(); let sockqd: QDesc = match libos.socket(AF_INET, SOCK_DGRAM, 0) { Ok(sockqd) => sockqd, diff --git a/examples/tcp-close/args.rs b/examples/tcp-close/args.rs index bcc3d7f17..a9c08cd3f 100644 --- a/examples/tcp-close/args.rs +++ b/examples/tcp-close/args.rs @@ -105,23 +105,23 @@ impl ProgramArguments { Ok(args) } - pub fn get_socket_addr(&self) -> SocketAddr { + pub fn socket_addr(&self) -> SocketAddr { self.socket_addr } - pub fn get_num_clients(&self) -> Option { + pub fn num_clients(&self) -> Option { self.num_clients } - pub fn get_peer_type(&self) -> Option { + pub fn peer_type(&self) -> Option { self.peer_type.clone() } - pub fn get_who_closes(&self) -> Option { + pub fn who_closes(&self) -> Option { self.who_closes.clone() } - pub fn get_run_mode(&self) -> String { + pub fn run_mode(&self) -> String { self.run_mode.clone() } } diff --git a/examples/tcp-close/main.rs b/examples/tcp-close/main.rs index 7af4a57b0..7c11d64d7 100644 --- a/examples/tcp-close/main.rs +++ b/examples/tcp-close/main.rs @@ -32,36 +32,36 @@ fn main() -> Result<()> { LibOS::new(libos_name, None)? }; - match args.get_who_closes().expect("missing whocloses the socket").as_str() { - "client" => match args.get_peer_type().expect("missing peer_type").as_str() { + match args.who_closes().expect("missing whocloses the socket").as_str() { + "client" => match args.peer_type().expect("missing peer_type").as_str() { "client" => { - let mut client: TcpClient = TcpClient::new(libos, args.get_socket_addr())?; - let nclients: usize = args.get_num_clients().expect("missing number of clients"); - match args.get_run_mode().as_str() { + let mut client: TcpClient = TcpClient::new(libos, args.socket_addr())?; + let nclients: usize = args.num_clients().expect("missing number of clients"); + match args.run_mode().as_str() { "sequential" => client.run_sequential(nclients), "concurrent" => client.run_concurrent(nclients), _ => anyhow::bail!("invalid run mode"), } }, "server" => { - let mut server: TcpServer = TcpServer::new(libos, args.get_socket_addr())?; - server.run(args.get_num_clients()) + let mut server: TcpServer = TcpServer::new(libos, args.socket_addr())?; + server.run(args.num_clients()) }, _ => anyhow::bail!("invalid peer type"), }, - "server" => match args.get_peer_type().expect("missing peer_type").as_str() { + "server" => match args.peer_type().expect("missing peer_type").as_str() { "client" => { - let mut client: TcpClient = TcpClient::new(libos, args.get_socket_addr())?; - let nclients: usize = args.get_num_clients().expect("missing number of clients"); - match args.get_run_mode().as_str() { + let mut client: TcpClient = TcpClient::new(libos, args.socket_addr())?; + let nclients: usize = args.num_clients().expect("missing number of clients"); + match args.run_mode().as_str() { "sequential" => client.run_sequential_expecting_server_to_close_sockets(nclients), "concurrent" => client.run_concurrent_expecting_server_to_close_sockets(nclients), _ => anyhow::bail!("invalid run mode"), } }, "server" => { - let mut server: TcpServer = TcpServer::new(libos, args.get_socket_addr())?; - server.run_close_sockets_on_accept(args.get_num_clients()) + let mut server: TcpServer = TcpServer::new(libos, args.socket_addr())?; + server.run_close_sockets_on_accept(args.num_clients()) }, _ => anyhow::bail!("invalid peer type"), }, diff --git a/src/catnap/linux/active_socket.rs b/src/catnap/linux/active_socket.rs index 50870dc0a..792c42cf1 100644 --- a/src/catnap/linux/active_socket.rs +++ b/src/catnap/linux/active_socket.rs @@ -176,11 +176,11 @@ impl ActiveSocketData { self.recv_queue.push_front(Ok((addr, buf))); } - pub fn get_socket(&self) -> &Socket { + pub fn socket(&self) -> &Socket { &self.socket } - pub fn get_mut_socket(&mut self) -> &mut Socket { + pub fn socket_mut(&mut self) -> &mut Socket { &mut self.socket } } diff --git a/src/catnap/linux/passive_socket.rs b/src/catnap/linux/passive_socket.rs index e15d46da3..ac7c7c131 100644 --- a/src/catnap/linux/passive_socket.rs +++ b/src/catnap/linux/passive_socket.rs @@ -63,11 +63,11 @@ impl PassiveSocketData { self.accept_queue.pop(None).await? } - pub fn get_socket(&self) -> &Socket { + pub fn socket(&self) -> &Socket { &self.socket } - pub fn get_mut_socket(&mut self) -> &mut Socket { + pub fn socket_mut(&mut self) -> &mut Socket { &mut self.socket } } diff --git a/src/catnap/linux/socket.rs b/src/catnap/linux/socket.rs index 004a82688..6538deb86 100644 --- a/src/catnap/linux/socket.rs +++ b/src/catnap/linux/socket.rs @@ -75,8 +75,8 @@ impl SharedSocketData { let _self = self.as_ref(); match _self { SocketData::Inactive(Some(socket)) => socket, - SocketData::Active(data) => data.get_socket(), - SocketData::Passive(data) => data.get_socket(), + SocketData::Active(data) => data.socket(), + SocketData::Passive(data) => data.socket(), _ => panic!("Should have data"), } } @@ -86,8 +86,8 @@ impl SharedSocketData { let _self = self.as_mut(); match _self { SocketData::Inactive(Some(socket)) => socket, - SocketData::Active(data) => data.get_mut_socket(), - SocketData::Passive(data) => data.get_mut_socket(), + SocketData::Active(data) => data.socket_mut(), + SocketData::Passive(data) => data.socket_mut(), _ => panic!("Should have data"), } } diff --git a/src/catnap/linux/transport.rs b/src/catnap/linux/transport.rs index f16c67548..efc8cc341 100644 --- a/src/catnap/linux/transport.rs +++ b/src/catnap/linux/transport.rs @@ -629,7 +629,7 @@ impl NetworkTransport for SharedCatnapTransport { Ok(()) } - fn get_runtime(&self) -> &SharedDemiRuntime { + fn runtime(&self) -> &SharedDemiRuntime { &self.runtime } } diff --git a/src/collections/async_queue.rs b/src/collections/async_queue.rs index 89a8e9860..be508093c 100644 --- a/src/collections/async_queue.rs +++ b/src/collections/async_queue.rs @@ -83,36 +83,30 @@ impl AsyncQueue { self.queue.pop_front() } - /// Get the length of the queue. pub fn len(&self) -> usize { self.queue.len() } - /// Check if the queue is empty. #[allow(unused)] pub fn is_empty(&self) -> bool { self.queue.is_empty() } - /// Get an iterator over values #[allow(unused)] - pub fn get_values(&self) -> Iter { + pub fn values(&self) -> Iter { self.queue.iter() } #[allow(unused)] - /// Get an iterator over mutable values - pub fn get_mut_values(&mut self) -> IterMut { + pub fn values_mut(&mut self) -> IterMut { self.queue.iter_mut() } - /// Get refernce to first item. - pub fn get_front(&self) -> Option<&T> { + pub fn front(&self) -> Option<&T> { self.queue.front() } - /// Get mutable reference to first item. - pub fn get_front_mut(&mut self) -> Option<&mut T> { + pub fn front_mut(&mut self) -> Option<&mut T> { self.queue.front_mut() } } diff --git a/src/demikernel/bindings.rs b/src/demikernel/bindings.rs index bd1a1bb69..33cc41902 100644 --- a/src/demikernel/bindings.rs +++ b/src/demikernel/bindings.rs @@ -562,8 +562,7 @@ pub unsafe extern "C" fn demi_wait_next_n( Some(unsafe { Duration::new((*timeout).tv_sec as u64, (*timeout).tv_nsec as u32) }) }; - let out_slice: &mut [MaybeUninit] = - unsafe { slice::from_raw_parts_mut(qr_out.cast(), qr_out_size as usize) }; + let out_slice = unsafe { slice::from_raw_parts_mut(qr_out.cast(), qr_out_size as usize) }; let mut result_idx = 0; let wait_callback = |result: demi_qresult_t| -> bool { out_slice[result_idx as usize] = MaybeUninit::new(result); @@ -1025,7 +1024,7 @@ mod test { fn test_set_and_get_linger() -> anyhow::Result<()> { use crate::runtime::types::demi_args_t; let args = demi_args_t::default(); - let result: c_int = unsafe { demi_init(&args) }; + let result = unsafe { demi_init(&args) }; ensure_eq!(result, 0); let mut qd = 0; diff --git a/src/demikernel/config.rs b/src/demikernel/config.rs index 6d713691d..f0416174e 100644 --- a/src/demikernel/config.rs +++ b/src/demikernel/config.rs @@ -12,8 +12,6 @@ use crate::{pal::KeepAlive, runtime::fail::Fail, MacAddress}; use ::std::ffi::CString; use ::std::{collections::HashMap, fs::File, io::Read, net::Ipv4Addr, ops::Index, str::FromStr, time::Duration}; use ::yaml_rust::{Yaml, YamlLoader}; -#[cfg(feature = "catnip-libos")] -use yaml_rust::yaml::Array; //====================================================================================================================== // Constants @@ -127,85 +125,80 @@ pub struct Config(pub Yaml); impl Config { /// Reads the config file into the [Config] object. pub fn new(config_path: String) -> Result { - let mut config_s: String = String::new(); - File::open(config_path).unwrap().read_to_string(&mut config_s).unwrap(); - let config: Vec = YamlLoader::load_from_str(&config_s).unwrap(); - let config_obj: &Yaml = match &config[..] { + let mut cfg_str = String::new(); + File::open(config_path).unwrap().read_to_string(&mut cfg_str).unwrap(); + let cfg = YamlLoader::load_from_str(&cfg_str).unwrap(); + let cfg = match &cfg[..] { [c] => c, _ => return Err(Fail::new(libc::EINVAL, "Wrong number of config objects")), }; - Ok(Self(config_obj.clone())) + Ok(Self(cfg.clone())) } - fn get_global_config(&self) -> Result<&Yaml, Fail> { + fn global_config(&self) -> Result<&Yaml, Fail> { Self::get_subsection(&self.0, global_config::SECTION_NAME) } - fn get_tcp_socket_options(&self) -> Result<&Yaml, Fail> { + fn tcp_socket_options(&self) -> Result<&Yaml, Fail> { Self::get_subsection(&self.0, tcp_socket_options::SECTION_NAME) } - fn get_inetstack_config(&self) -> Result<&Yaml, Fail> { + fn inetstack_config(&self) -> Result<&Yaml, Fail> { Self::get_subsection(&self.0, inetstack_config::SECTION_NAME) } #[cfg(feature = "catnip-libos")] - fn get_dpdk_config(&self) -> Result<&Yaml, Fail> { + fn dpdk_config(&self) -> Result<&Yaml, Fail> { Self::get_subsection(&self.0, dpdk_config::SECTION_NAME) } #[cfg(feature = "catpowder-libos")] - fn get_raw_socket_config(&self) -> Result<&Yaml, Fail> { + fn raw_socket_config(&self) -> Result<&Yaml, Fail> { Self::get_subsection(&self.0, raw_socket_config::SECTION_NAME) } /// Global config: The value from the env var takes precedence over the value from file. pub fn local_ipv4_addr(&self) -> Result { - let local_ipv4_addr: Ipv4Addr = if let Some(addr) = Self::get_typed_env_option(global_config::LOCAL_IPV4_ADDR)? - { - addr + let ip: Ipv4Addr = if let Some(ip) = Self::get_typed_env_option(global_config::LOCAL_IPV4_ADDR)? { + ip } else { - Self::get_typed_str_option( - self.get_global_config()?, - global_config::LOCAL_IPV4_ADDR, - |val: &str| val.parse().ok(), - )? + Self::get_typed_str_option(self.global_config()?, global_config::LOCAL_IPV4_ADDR, |val: &str| { + val.parse().ok() + })? }; - if local_ipv4_addr.is_unspecified() || local_ipv4_addr.is_broadcast() { - let cause: &'static str = "Invalid IPv4 address"; + if ip.is_unspecified() || ip.is_broadcast() { + let cause = "Invalid IPv4 address"; error!("local_ipv4_addr(): {:?}", cause); return Err(Fail::new(libc::EINVAL, cause)); } - Ok(local_ipv4_addr) + Ok(ip) } /// The value from the env var takes precedence over the value from file. pub fn local_link_addr(&self) -> Result { - if let Some(addr) = Self::get_typed_env_option(global_config::LOCAL_LINK_ADDR)? { - Ok(addr) + if let Some(mac) = Self::get_typed_env_option(global_config::LOCAL_LINK_ADDR)? { + Ok(mac) } else { - Self::get_typed_str_option( - self.get_global_config()?, - global_config::LOCAL_LINK_ADDR, - |val: &str| MacAddress::parse_canonical_str(val).ok(), - ) + Self::get_typed_str_option(self.global_config()?, global_config::LOCAL_LINK_ADDR, |val: &str| { + MacAddress::parse_canonical_str(val).ok() + }) } } /// Tcp socket option: Reads TCP keepalive settings as a `tcp_keepalive` structure from "tcp_keepalive" subsection. pub fn tcp_keepalive(&self) -> Result { - let section: &Yaml = Self::get_subsection(self.get_tcp_socket_options()?, tcp_socket_options::KEEP_ALIVE)?; - let onoff: bool = Self::get_bool_option(section, "enabled")?; + let section = Self::get_subsection(self.tcp_socket_options()?, tcp_socket_options::KEEP_ALIVE)?; + let onoff = Self::get_bool_option(section, "enabled")?; #[cfg(target_os = "windows")] // This indicates how long to keep the socket alive. By default, this is 2 hours on Windows. // README: https://learn.microsoft.com/en-us/windows/win32/winsock/sio-keepalive-vals - let keepalivetime: u32 = Self::get_int_option(section, "time_millis")?; + let keepalivetime = Self::get_int_option(section, "time_millis")?; #[cfg(target_os = "windows")] // This indicates how often to send keep alive messages. By default, this is 1 second on Windows. - let keepaliveinterval: u32 = Self::get_int_option(section, "interval")?; + let keepaliveinterval = Self::get_int_option(section, "interval")?; #[cfg(target_os = "linux")] return Ok(onoff); @@ -221,10 +214,10 @@ impl Config { /// Tcp socket option: Reads socket linger settings from "linger" subsection. Returned value is Some(_) if enabled; /// otherwise, None. The linger duration will be no larger than u16::MAX seconds. pub fn linger(&self) -> Result, Fail> { - let linger: u64 = if let Some(linger) = Self::get_typed_env_option(tcp_socket_options::LINGER)? { + let linger = if let Some(linger) = Self::get_typed_env_option(tcp_socket_options::LINGER)? { linger } else { - let section: &Yaml = Self::get_subsection(self.get_tcp_socket_options()?, tcp_socket_options::LINGER)?; + let section = Self::get_subsection(self.tcp_socket_options()?, tcp_socket_options::LINGER)?; if Self::get_bool_option(section, "enabled")? { Self::get_int_option(section, "time_seconds")? } else { @@ -239,14 +232,14 @@ impl Config { if let Some(nodelay) = Self::get_typed_env_option(tcp_socket_options::NO_DELAY)? { Ok(nodelay) } else { - Self::get_bool_option(self.get_tcp_socket_options()?, tcp_socket_options::NO_DELAY) + Self::get_bool_option(self.tcp_socket_options()?, tcp_socket_options::NO_DELAY) } } /// If no ARP table is present, then ARP is disabled. This cannot be passed in as an environment variable. pub fn arp_table(&self) -> Result>, Fail> { - let config = self.get_inetstack_config()?; - let arp_yaml = Self::get_typed_option(config, inetstack_config::ARP_TABLE, |yaml| yaml.as_hash()); + let cfg = self.inetstack_config()?; + let arp_yaml = Self::get_typed_option(cfg, inetstack_config::ARP_TABLE, |yaml| yaml.as_hash()); if arp_yaml.is_err() { return Ok(None); @@ -279,18 +272,17 @@ impl Config { } pub fn arp_cache_ttl(&self) -> Result { - let ttl_secs = self.get_int_env_or_option(inetstack_config::ARP_CACHE_TTL, Self::get_inetstack_config)?; + let ttl_secs = self.int_env_or_option(inetstack_config::ARP_CACHE_TTL, Self::inetstack_config)?; Ok(Duration::from_secs(ttl_secs)) } pub fn arp_request_timeout(&self) -> Result { - let timeout_secs = - self.get_int_env_or_option(inetstack_config::ARP_REQUEST_TIMEOUT, Self::get_inetstack_config)?; + let timeout_secs = self.int_env_or_option(inetstack_config::ARP_REQUEST_TIMEOUT, Self::inetstack_config)?; Ok(Duration::from_secs(timeout_secs)) } pub fn arp_request_retries(&self) -> Result { - self.get_int_env_or_option(inetstack_config::ARP_REQUEST_RETRIES, Self::get_inetstack_config) + self.int_env_or_option(inetstack_config::ARP_REQUEST_RETRIES, Self::inetstack_config) } #[cfg(all(feature = "catpowder-libos", target_os = "linux"))] @@ -298,11 +290,11 @@ impl Config { /// configuration file. pub fn local_interface_name(&self) -> Result { // Parse local MAC address. - if let Some(addr) = Self::get_typed_env_option(raw_socket_config::LOCAL_INTERFACE_NAME)? { - Ok(addr) + if let Some(mac) = Self::get_typed_env_option(raw_socket_config::LOCAL_INTERFACE_NAME)? { + Ok(mac) } else { Self::get_typed_str_option( - self.get_raw_socket_config()?, + self.raw_socket_config()?, raw_socket_config::LOCAL_INTERFACE_NAME, |val: &str| Some(val.to_string()), ) @@ -313,17 +305,15 @@ impl Config { /// Global config: Reads the "local interface index" parameter from the environment variable and then the underlying /// configuration file. pub fn local_interface_index(&self) -> Result { - self.get_int_env_or_option(raw_socket_config::LOCAL_INTERFACE_INDEX, Self::get_raw_socket_config) + self.int_env_or_option(raw_socket_config::LOCAL_INTERFACE_INDEX, Self::raw_socket_config) } #[cfg(all(feature = "catpowder-libos", target_os = "windows"))] /// Global config: Reads the "rx_buffer_count" and "rx_ring_size" parameters from the environment variable and /// then the underlying configuration file. Returns the tuple (buffer count, ring size). pub fn rx_buffer_config(&self) -> Result<(u32, u32), Fail> { - let rx_buffer_count: u32 = - self.get_int_env_or_option(raw_socket_config::RX_BUFFER_COUNT, Self::get_raw_socket_config)?; - let rx_ring_size: u32 = - self.get_int_env_or_option(raw_socket_config::RX_RING_SIZE, Self::get_raw_socket_config)?; + let rx_buffer_count = self.int_env_or_option(raw_socket_config::RX_BUFFER_COUNT, Self::raw_socket_config)?; + let rx_ring_size = self.int_env_or_option(raw_socket_config::RX_RING_SIZE, Self::raw_socket_config)?; Ok((rx_buffer_count, rx_ring_size)) } @@ -331,10 +321,8 @@ impl Config { /// Global config: Reads the "rx_buffer_count" and "rx_ring_size" parameters from the environment variable and /// then the underlying configuration file. Returns the tuple (buffer count, ring size). pub fn tx_buffer_config(&self) -> Result<(u32, u32), Fail> { - let tx_buffer_count: u32 = - self.get_int_env_or_option(raw_socket_config::TX_BUFFER_COUNT, Self::get_raw_socket_config)?; - let tx_ring_size: u32 = - self.get_int_env_or_option(raw_socket_config::TX_RING_SIZE, Self::get_raw_socket_config)?; + let tx_buffer_count = self.int_env_or_option(raw_socket_config::TX_BUFFER_COUNT, Self::raw_socket_config)?; + let tx_ring_size = self.int_env_or_option(raw_socket_config::TX_RING_SIZE, Self::raw_socket_config)?; Ok((tx_buffer_count, tx_ring_size)) } @@ -343,7 +331,7 @@ impl Config { if let Some(always_poke) = Self::get_typed_env_option(raw_socket_config::XDP_ALWAYS_POKE_TX)? { Ok(always_poke) } else { - Self::get_bool_option(self.get_raw_socket_config()?, raw_socket_config::XDP_ALWAYS_POKE_TX) + Self::get_bool_option(self.raw_socket_config()?, raw_socket_config::XDP_ALWAYS_POKE_TX) } } @@ -352,10 +340,7 @@ impl Config { if let Some(addr) = Self::get_typed_env_option(raw_socket_config::LOCAL_VF_INTERFACE_INDEX)? { Ok(addr) } else { - Self::get_int_option( - self.get_raw_socket_config()?, - raw_socket_config::LOCAL_VF_INTERFACE_INDEX, - ) + Self::get_int_option(self.raw_socket_config()?, raw_socket_config::LOCAL_VF_INTERFACE_INDEX) } } @@ -368,7 +353,7 @@ impl Config { if let Some(val) = val.as_bool() { Ok(val) } else { - let cause: String = format!("Invalid value for xdp_always_send_on_vf"); + let cause = format!("Invalid value for xdp_always_send_on_vf"); error!("xdp_always_send_on_vf(): {:?}", cause); Err(Fail::new(libc::EINVAL, &cause)) } @@ -383,7 +368,7 @@ impl Config { if let Some(enabled) = Self::get_typed_env_option(raw_socket_config::XDP_COHOST_MODE)? { Ok(enabled) } else { - Self::get_bool_option(self.get_raw_socket_config()?, raw_socket_config::XDP_COHOST_MODE) + Self::get_bool_option(self.raw_socket_config()?, raw_socket_config::XDP_COHOST_MODE) } } @@ -393,7 +378,7 @@ impl Config { if let Some(ports) = Self::get_env_option(key) { Self::parse_array::(ports.as_str()) } else { - Self::get_typed_option(self.get_raw_socket_config()?, key, Yaml::as_vec)? + Self::get_typed_option(self.raw_socket_config()?, key, Yaml::as_vec)? .iter() .map(|port: &Yaml| { port.as_i64() @@ -406,8 +391,8 @@ impl Config { } }; - let tcp_ports: Vec = parse_ports(raw_socket_config::XDP_TCP_PORTS)?; - let udp_ports: Vec = parse_ports(raw_socket_config::XDP_UDP_PORTS)?; + let tcp_ports = parse_ports(raw_socket_config::XDP_TCP_PORTS)?; + let udp_ports = parse_ports(raw_socket_config::XDP_UDP_PORTS)?; Ok((tcp_ports, udp_ports)) } @@ -416,10 +401,7 @@ impl Config { if let Some(count) = Self::get_typed_env_option(raw_socket_config::XDP_RESERVED_PORT_COUNT)? { Ok(Some(count)) } else { - match Self::get_option( - self.get_raw_socket_config()?, - raw_socket_config::XDP_RESERVED_PORT_COUNT, - ) { + match Self::get_option(self.raw_socket_config()?, raw_socket_config::XDP_RESERVED_PORT_COUNT) { Ok(value) => { if let Some(value) = value.as_i64() { u16::try_from(value) @@ -447,10 +429,9 @@ impl Config { if let Some(protocol) = Self::get_env_option(raw_socket_config::XDP_RESERVED_PORT_PROTOCOL) { parse(&protocol.as_str()).map(Some) } else { - if let Ok(protocol) = Self::get_option( - self.get_raw_socket_config()?, - raw_socket_config::XDP_RESERVED_PORT_PROTOCOL, - ) { + if let Ok(protocol) = + Self::get_option(self.raw_socket_config()?, raw_socket_config::XDP_RESERVED_PORT_PROTOCOL) + { if let Some(value) = protocol.as_str() { parse(value).map(Some) } else { @@ -465,8 +446,8 @@ impl Config { #[cfg(feature = "catnip-libos")] /// DPDK Config: Reads the "DPDK EAL" parameter the underlying configuration file. pub fn eal_init_args(&self) -> Result, Fail> { - let args: &Array = Self::get_typed_option( - self.get_dpdk_config()?, + let args = Self::get_typed_option( + self.dpdk_config()?, dpdk_config::EAL_INIT_ARGS, |yaml: &Yaml| match yaml { Yaml::Array(ref arr) => Some(arr), @@ -474,19 +455,19 @@ impl Config { }, )?; - let mut result: Vec = Vec::::with_capacity(args.len()); + let mut result = Vec::::with_capacity(args.len()); for arg in args { match arg.as_str() { Some(string) => match CString::new(string) { Ok(cstring) => result.push(cstring), Err(e) => { - let cause: String = format!("Non string argument: {:?}", e); + let cause = format!("Non string argument: {:?}", e); error!("eal_init_args(): {}", cause); return Err(Fail::new(libc::EINVAL, &cause)); }, }, None => { - let cause: String = format!("Non string argument"); + let cause = format!("Non string argument"); error!("eal_init_args(): {}", cause); return Err(Fail::new(libc::EINVAL, &cause)); }, @@ -496,23 +477,23 @@ impl Config { } pub fn mtu(&self) -> Result { - self.get_int_env_or_option(inetstack_config::MTU, Self::get_inetstack_config) + self.int_env_or_option(inetstack_config::MTU, Self::inetstack_config) } pub fn mss(&self) -> Result { - self.get_int_env_or_option(inetstack_config::MSS, Self::get_inetstack_config) + self.int_env_or_option(inetstack_config::MSS, Self::inetstack_config) } pub fn tcp_checksum_offload(&self) -> Result { - Self::get_bool_option(self.get_inetstack_config()?, inetstack_config::TCP_CHECKSUM_OFFLOAD) + Self::get_bool_option(self.inetstack_config()?, inetstack_config::TCP_CHECKSUM_OFFLOAD) } pub fn udp_checksum_offload(&self) -> Result { - Self::get_bool_option(self.get_inetstack_config()?, inetstack_config::UDP_CHECKSUM_OFFLOAD) + Self::get_bool_option(self.inetstack_config()?, inetstack_config::UDP_CHECKSUM_OFFLOAD) } pub fn enable_jumbo_frames(&self) -> Result { - Self::get_bool_option(self.get_inetstack_config()?, inetstack_config::ENABLE_JUMBO_FRAMES) + Self::get_bool_option(self.inetstack_config()?, inetstack_config::ENABLE_JUMBO_FRAMES) } //====================================================================================================================== @@ -522,11 +503,11 @@ impl Config { /// Similar to `require_typed_option` using `Yaml::as_hash` receiver. This method returns a `&Yaml` instead of /// yaml::Hash, and Yaml is more natural for indexing. fn get_subsection<'a>(yaml: &'a Yaml, index: &str) -> Result<&'a Yaml, Fail> { - let section: &'a Yaml = Self::get_option(yaml, index)?; + let section = Self::get_option(yaml, index)?; match section { Yaml::Hash(_) => Ok(section), _ => { - let message: String = format!("parameter \"{}\" has unexpected type", index); + let message = format!("parameter \"{}\" has unexpected type", index); Err(Fail::new(libc::EINVAL, message.as_str())) }, } @@ -536,7 +517,7 @@ impl Config { fn get_option<'a>(yaml: &'a Yaml, index: &str) -> Result<&'a Yaml, Fail> { match yaml.index(index) { Yaml::BadValue => { - let message: String = format!("missing configuration option \"{}\"", index); + let message = format!("missing configuration option \"{}\"", index); Err(Fail::new(libc::EINVAL, message.as_str())) }, value => Ok(value), @@ -548,11 +529,11 @@ impl Config { where Fn: FnOnce(&'a Yaml) -> Option, { - let option: &'a Yaml = Self::get_option(yaml, index)?; + let option = Self::get_option(yaml, index)?; match receiver(option) { Some(value) => Ok(value), None => { - let message: String = format!("parameter {} has unexpected type", index); + let message = format!("parameter {} has unexpected type", index); Err(Fail::new(libc::EINVAL, message.as_str())) }, } @@ -563,13 +544,13 @@ impl Config { where Fn: FnOnce(&str) -> Option, { - let option: &Yaml = Self::get_option(yaml, index)?; + let option = Self::get_option(yaml, index)?; if let Some(value) = option.as_str() { if let Some(value) = parser(value) { return Ok(value); } } - let message: String = format!("parameter {} has unexpected type", index); + let message = format!("parameter {} has unexpected type", index); Err(Fail::new(libc::EINVAL, message.as_str())) } @@ -582,7 +563,7 @@ impl Config { Self::get_env_option(index) .map(|val: String| -> Result { val.as_str().parse().map_err(|_| { - let message: String = format!("parameter {} has unexpected type", index); + let message = format!("parameter {} has unexpected type", index); Fail::new(libc::EINVAL, message.as_str()) }) }) @@ -596,13 +577,13 @@ impl Config { match T::try_from(val) { Ok(val) => Ok(val), _ => { - let message: String = format!("parameter \"{}\" is out of range", index); + let message = format!("parameter \"{}\" is out of range", index); Err(Fail::new(libc::ERANGE, message.as_str())) }, } } - fn get_int_env_or_option(&self, index: &str, resolve_yaml: Fn) -> Result + fn int_env_or_option(&self, index: &str, resolve_yaml: Fn) -> Result where T: TryFrom + FromStr, for<'a> Fn: FnOnce(&'a Self) -> Result<&'a Yaml, Fail>, diff --git a/src/demikernel/libos/mod.rs b/src/demikernel/libos/mod.rs index 97e39e78b..34df84aa6 100644 --- a/src/demikernel/libos/mod.rs +++ b/src/demikernel/libos/mod.rs @@ -59,7 +59,7 @@ impl LibOS { pub fn new(libos_name: LibOSName, _perf_callback: Option) -> Result { logging::initialize(); - let config_path: String = match env::var("CONFIG_PATH") { + let config_path = match env::var("CONFIG_PATH") { Ok(config_path) => config_path, Err(_) => { return Err(Fail::new( @@ -74,12 +74,12 @@ impl LibOS { set_callback(callback) }; - let config: Config = Config::new(config_path)?; + let config = Config::new(config_path)?; #[allow(unused_mut)] - let mut runtime: SharedDemiRuntime = SharedDemiRuntime::default(); + let mut runtime = SharedDemiRuntime::default(); // Instantiate LibOS. #[allow(unreachable_patterns)] - let libos: LibOS = match libos_name { + let libos = match libos_name { #[cfg(feature = "catnap-libos")] LibOSName::Catnap => Self::NetworkLibOS(NetworkLibOSWrapper::Catnap(SharedNetworkLibOS::< SharedCatnapTransport, @@ -90,10 +90,9 @@ impl LibOS { #[cfg(feature = "catpowder-libos")] LibOSName::Catpowder => { - let layer1_endpoint: SharedCatpowderRuntime = SharedCatpowderRuntime::new(&config)?; + let layer1_endpoint = SharedCatpowderRuntime::new(&config)?; // This is our transport for Catpowder. - let inetstack: SharedInetStack = - SharedInetStack::new(&config, runtime.clone(), layer1_endpoint).unwrap(); + let inetstack = SharedInetStack::new(&config, runtime.clone(), layer1_endpoint).unwrap(); Self::NetworkLibOS(NetworkLibOSWrapper::Catpowder( SharedNetworkLibOS::::new(runtime, inetstack), )) @@ -101,9 +100,8 @@ impl LibOS { #[cfg(feature = "catnip-libos")] LibOSName::Catnip => { // TODO: Remove some of these clones once we are done merging the libOSes. - let layer1_endpoint: SharedDPDKRuntime = SharedDPDKRuntime::new(&config)?; - let inetstack: SharedInetStack = - SharedInetStack::new(&config, runtime.clone(), layer1_endpoint).unwrap(); + let layer1_endpoint = SharedDPDKRuntime::new(&config)?; + let inetstack = SharedInetStack::new(&config, runtime.clone(), layer1_endpoint).unwrap(); Self::NetworkLibOS(NetworkLibOSWrapper::Catnip(SharedNetworkLibOS::::new( runtime, inetstack, @@ -216,7 +214,7 @@ impl LibOS { if let Some(size) = size { // Check if size is valid. if !((size > 0) && (size <= limits::POP_SIZE_MAX)) { - let cause: String = format!("invalid pop size (size={:?})", size); + let cause = format!("invalid pop size (size={:?})", size); error!("pop(): {:?}", &cause); return Err(Fail::new(libc::EINVAL, &cause)); } diff --git a/src/demikernel/libos/name.rs b/src/demikernel/libos/name.rs index 17e701a13..7686437d5 100644 --- a/src/demikernel/libos/name.rs +++ b/src/demikernel/libos/name.rs @@ -36,7 +36,6 @@ impl LibOSName { // Trait Implementations //====================================================================================================================== -/// Conversion trait implementation for LibOSName. impl From for LibOSName { fn from(str: String) -> Self { match str.to_lowercase().as_str() { diff --git a/src/demikernel/libos/network/libos.rs b/src/demikernel/libos/network/libos.rs index 75a271e13..eeeb3c927 100644 --- a/src/demikernel/libos/network/libos.rs +++ b/src/demikernel/libos/network/libos.rs @@ -108,7 +108,7 @@ impl SharedNetworkLibOS { // We only support the wildcard address for UDP sockets. // FIXME: https://github.com/demikernel/demikernel/issues/189 - if *socket_addrv4.ip() == Ipv4Addr::UNSPECIFIED && self.get_shared_queue(&qd)?.get_qtype() != QType::UdpSocket { + if *socket_addrv4.ip() == Ipv4Addr::UNSPECIFIED && self.get_shared_queue(&qd)?.qtype() != QType::UdpSocket { let cause: String = format!("cannot bind to wildcard address (qd={:?})", qd); error!("bind(): {}", cause); return Err(Fail::new(libc::ENOTSUP, &cause)); @@ -116,7 +116,7 @@ impl SharedNetworkLibOS { // We only support the wildcard address for UDP sockets. // FIXME: https://github.com/demikernel/demikernel/issues/582 - if socket_addr.port() == 0 && self.get_shared_queue(&qd)?.get_qtype() != QType::UdpSocket { + if socket_addr.port() == 0 && self.get_shared_queue(&qd)?.qtype() != QType::UdpSocket { let cause: String = format!("cannot bind to port 0 (qd={:?})", qd); error!("bind(): {}", cause); return Err(Fail::new(libc::ENOTSUP, &cause)); @@ -534,12 +534,10 @@ impl SharedNetworkLibOS { } } - /// Allocates a scatter-gather array. pub fn sgaalloc(&self, size: usize) -> Result { sgaalloc(size, &self.transport) } - /// Releases a scatter-gather array. pub fn sgafree(&self, sga: demi_sgarray_t) -> Result<(), Fail> { sgafree(sga) } @@ -550,13 +548,13 @@ impl SharedNetworkLibOS { self.runtime.get_shared_queue::>(qd) } - /// This exposes the transport for testing purposes. - pub fn get_transport(&self) -> T { + /// For testing only. + pub fn transport(&self) -> T { self.transport.clone() } - /// This exposes the transport for testing purposes. - pub fn get_runtime(&self) -> SharedDemiRuntime { + /// For testing only. + pub fn runtime(&self) -> SharedDemiRuntime { self.runtime.clone() } } diff --git a/src/demikernel/libos/network/mod.rs b/src/demikernel/libos/network/mod.rs index 2648baa1a..e3ac206eb 100644 --- a/src/demikernel/libos/network/mod.rs +++ b/src/demikernel/libos/network/mod.rs @@ -122,11 +122,10 @@ impl NetworkLibOSWrapper { pub fn listen(&mut self, sockqd: QDesc, mut backlog: usize) -> Result<(), Fail> { // Truncate backlog length. if backlog > SOMAXCONN as usize { - let cause: String = format!( - "backlog length is too large, truncating (qd={:?}, backlog={:?})", + debug!( + "listen(): backlog length is too large, truncating (qd={:?}, backlog={:?})", sockqd, backlog ); - debug!("listen(): {}", &cause); backlog = SOMAXCONN as usize; } @@ -223,10 +222,10 @@ impl NetworkLibOSWrapper { trace!("wait(): qt={:?}, timeout={:?}", qt, timeout); // Put the QToken into a single element array. - let qt_array: [QToken; 1] = [qt]; + let qt_array = [qt]; // Call wait_any() to do the real work. - let (offset, qr): (usize, demi_qresult_t) = self.wait_any(&qt_array, timeout)?; + let (offset, qr) = self.wait_any(&qt_array, timeout)?; debug_assert_eq!(offset, 0); Ok(qr) } diff --git a/src/demikernel/libos/network/queue.rs b/src/demikernel/libos/network/queue.rs index e045f9f70..43c3abcef 100644 --- a/src/demikernel/libos/network/queue.rs +++ b/src/demikernel/libos/network/queue.rs @@ -56,14 +56,14 @@ impl SharedNetworkQueue { // This was previously checked in the LibOS layer. debug_assert!(typ == Type::STREAM || typ == Type::DGRAM); - let qtype: QType = match typ { + let qtype = match typ { Type::STREAM => QType::TcpSocket, Type::DGRAM => QType::UdpSocket, // The following statement is unreachable because we have checked this on the libOS layer. _ => unreachable!("Invalid socket type (typ={:?})", typ), }; - let socket: T::SocketDescriptor = transport.socket(domain, typ)?; + let socket = transport.socket(domain, typ)?; Ok(Self(SharedObject::new(NetworkQueue:: { qtype, state_machine: SocketStateMachine::new_unbound(typ), @@ -74,7 +74,7 @@ impl SharedNetworkQueue { pub fn set_socket_option(&mut self, option: SocketOption) -> Result<(), Fail> { if self.state_machine.ensure_not_closing().is_err() { - let cause: &'static str = "cannot set socket-level options when socket is closing"; + let cause = "cannot set socket-level options when socket is closing"; warn!("set_socket_option(): {}", cause); return Err(Fail::new(libc::EBUSY, cause)); } @@ -131,8 +131,8 @@ impl SharedNetworkQueue { pub async fn accept_coroutine(&mut self) -> Result { // 1. Block until either the accept operation completes or the state changes. let (socket, addr) = match { - let mut state_machine: SocketStateMachine = self.state_machine.clone(); - let mut transport: T = self.transport.clone(); + let mut state_machine = self.state_machine.clone(); + let mut transport = self.transport.clone(); let state_tracker = state_machine.while_may_accept().fuse(); let operation = transport.accept(&mut self.socket).fuse(); pin_mut!(state_tracker); @@ -180,9 +180,9 @@ impl SharedNetworkQueue { // 1. Move to a connecting state. self.state_machine.connecting(remote); // 2. Wait until either the connect completes or the socket state changes. - let result: Result<(), Fail> = { - let mut state_machine: SocketStateMachine = self.state_machine.clone(); - let mut transport: T = self.transport.clone(); + let result = { + let mut state_machine = self.state_machine.clone(); + let mut transport = self.transport.clone(); let state_tracker = state_machine.while_open().fuse(); let operation = transport.connect(&mut self.socket, remote).fuse(); pin_mut!(state_tracker); @@ -237,8 +237,8 @@ impl SharedNetworkQueue { /// Block until either the close finishes or some other coroutine closes the connection. async fn wait_for_close(&mut self) { - let mut state_machine: SocketStateMachine = self.state_machine.clone(); - let mut transport: T = self.transport.clone(); + let mut state_machine = self.state_machine.clone(); + let mut transport = self.transport.clone(); let state_tracker = state_machine.while_closing().fuse(); let operation = transport.close(&mut self.socket).fuse(); pin_mut!(state_tracker); @@ -270,8 +270,8 @@ impl SharedNetworkQueue { self.state_machine.may_push()?; let result = { - let mut state_machine: SocketStateMachine = self.state_machine.clone(); - let mut transport: T = self.transport.clone(); + let mut state_machine = self.state_machine.clone(); + let mut transport = self.transport.clone(); let state_tracker = state_machine.while_open().fuse(); let operation = transport.push(&mut self.socket, bufs, addr).fuse(); pin_mut!(state_tracker); @@ -305,8 +305,8 @@ impl SharedNetworkQueue { self.state_machine.may_pop()?; let size: usize = size.unwrap_or(limits::RECVBUF_SIZE_MAX); - let mut state_machine: SocketStateMachine = self.state_machine.clone(); - let mut transport: T = self.transport.clone(); + let mut state_machine = self.state_machine.clone(); + let mut transport = self.transport.clone(); let state_tracker = state_machine.while_open().fuse(); let operation = transport.pop(&mut self.socket, size).fuse(); pin_mut!(state_tracker); @@ -331,7 +331,7 @@ impl SharedNetworkQueue { //====================================================================================================================== impl IoQueue for SharedNetworkQueue { - fn get_qtype(&self) -> crate::QType { + fn qtype(&self) -> crate::QType { self.qtype } diff --git a/src/inetstack/config/arp.rs b/src/inetstack/config/arp.rs index 4645d9b91..81f0fa9a1 100644 --- a/src/inetstack/config/arp.rs +++ b/src/inetstack/config/arp.rs @@ -47,19 +47,19 @@ impl ArpConfig { } } - pub fn get_cache_ttl(&self) -> Duration { + pub fn cache_ttl(&self) -> Duration { self.cache_ttl } - pub fn get_request_timeout(&self) -> Duration { + pub fn request_timeout(&self) -> Duration { self.request_timeout } - pub fn get_retry_count(&self) -> usize { + pub fn retry_count(&self) -> usize { self.retry_count } - pub fn get_initial_values(&self) -> &HashMap { + pub fn initial_values(&self) -> &HashMap { &self.initial_values } @@ -74,7 +74,7 @@ impl ArpConfig { impl Default for ArpConfig { fn default() -> Self { - ArpConfig { + Self { cache_ttl: Duration::from_secs(15), request_timeout: Duration::from_secs(20), retry_count: 5, @@ -97,10 +97,10 @@ mod tests { #[test] fn test_arp_config_default() -> Result<()> { let config: ArpConfig = ArpConfig::default(); - crate::ensure_eq!(config.get_cache_ttl(), Duration::from_secs(15)); - crate::ensure_eq!(config.get_request_timeout(), Duration::from_secs(20)); - crate::ensure_eq!(config.get_retry_count(), 5); - crate::ensure_eq!(config.get_initial_values(), &HashMap::new()); + crate::ensure_eq!(config.cache_ttl(), Duration::from_secs(15)); + crate::ensure_eq!(config.request_timeout(), Duration::from_secs(20)); + crate::ensure_eq!(config.retry_count(), 5); + crate::ensure_eq!(config.initial_values(), &HashMap::new()); crate::ensure_eq!(config.is_enabled(), true); Ok(()) diff --git a/src/inetstack/mod.rs b/src/inetstack/mod.rs index 4db80b214..d9372b4b2 100644 --- a/src/inetstack/mod.rs +++ b/src/inetstack/mod.rs @@ -286,7 +286,7 @@ impl NetworkTransport for SharedInetStack { self.layer4_endpoint.pop(sd, size).await } - fn get_runtime(&self) -> &SharedDemiRuntime { + fn runtime(&self) -> &SharedDemiRuntime { &self.runtime } } diff --git a/src/inetstack/protocols/layer3/arp/header.rs b/src/inetstack/protocols/layer3/arp/header.rs index e15e4adc4..d43370abc 100644 --- a/src/inetstack/protocols/layer3/arp/header.rs +++ b/src/inetstack/protocols/layer3/arp/header.rs @@ -133,19 +133,19 @@ impl ArpHeader { pkt } - pub fn get_operation(&self) -> ArpOperation { + pub fn operation(&self) -> ArpOperation { self.operation } - pub fn get_sender_hardware_addr(&self) -> MacAddress { + pub fn sender_hardware_addr(&self) -> MacAddress { self.sender_hardware_addr } - pub fn get_sender_protocol_addr(&self) -> Ipv4Addr { + pub fn sender_protocol_addr(&self) -> Ipv4Addr { self.sender_protocol_addr } - pub fn get_destination_protocol_addr(&self) -> Ipv4Addr { + pub fn target_protocol_addr(&self) -> Ipv4Addr { self.target_protocol_addr } } diff --git a/src/inetstack/protocols/layer3/arp/peer.rs b/src/inetstack/protocols/layer3/arp/peer.rs index 14bc9ef45..a0ed8cdbf 100644 --- a/src/inetstack/protocols/layer3/arp/peer.rs +++ b/src/inetstack/protocols/layer3/arp/peer.rs @@ -67,9 +67,9 @@ impl SharedArpPeer { ) -> Result { let arp_config = ArpConfig::new(config)?; let cache = ArpCache::new( - runtime.get_now(), - Some(arp_config.get_cache_ttl()), - Some(arp_config.get_initial_values()), + runtime.now(), + Some(arp_config.cache_ttl()), + Some(arp_config.initial_values()), arp_config.is_enabled(), ); @@ -150,32 +150,32 @@ impl SharedArpPeer { // > hardware address field of the entry with the new // > information in the packet and set Merge_flag to true. let merge_flag = { - if self.cache.get(header.get_sender_protocol_addr()).is_some() { + if self.cache.get(header.sender_protocol_addr()).is_some() { trace!( "poll(): updating the arp cache (link_addr={:?}, ipv4_addr={:?})", - header.get_sender_hardware_addr(), - header.get_sender_protocol_addr() + header.sender_hardware_addr(), + header.sender_protocol_addr() ); - self.do_insert(header.get_sender_protocol_addr(), header.get_sender_hardware_addr()); + self.do_insert(header.sender_protocol_addr(), header.sender_hardware_addr()); true } else { trace!( "poll(): arp cache miss (link_addr={:?}, ipv4_addr={:?})", - header.get_sender_hardware_addr(), - header.get_sender_protocol_addr() + header.sender_hardware_addr(), + header.sender_protocol_addr() ); false } }; // from RFC 826: ?Am I the target protocol address? - if header.get_destination_protocol_addr() != self.local_ipv4_addr { + if header.target_protocol_addr() != self.local_ipv4_addr { if !merge_flag { warn!("arp_cache::poll(): unrecognized IP address"); } trace!( "poll(): dropping arp packet (link_addr={:?}, ipv4_addr={:?})", - header.get_sender_hardware_addr(), - header.get_sender_protocol_addr() + header.sender_hardware_addr(), + header.sender_protocol_addr() ); continue; } @@ -186,13 +186,13 @@ impl SharedArpPeer { if !merge_flag { trace!( "poll(): adding entry to the arp cache (link_addr={:?}, ipv4_addr={:?})", - header.get_sender_hardware_addr(), - header.get_sender_protocol_addr() + header.sender_hardware_addr(), + header.sender_protocol_addr() ); - self.do_insert(header.get_sender_protocol_addr(), header.get_sender_hardware_addr()); + self.do_insert(header.sender_protocol_addr(), header.sender_hardware_addr()); } - match header.get_operation() { + match header.operation() { ArpOperation::Request => { // from RFC 826: // > Swap hardware and protocol fields, putting the local @@ -201,14 +201,14 @@ impl SharedArpPeer { ArpOperation::Reply, self.layer2_endpoint.get_local_link_addr(), self.local_ipv4_addr, - header.get_sender_hardware_addr(), - header.get_sender_protocol_addr(), + header.sender_hardware_addr(), + header.sender_protocol_addr(), ); debug!("Responding {:?}", reply_hdr); if let Err(e) = self .layer2_endpoint - .transmit_arp_packet(header.get_sender_hardware_addr(), reply_hdr.create_and_serialize()) + .transmit_arp_packet(header.sender_hardware_addr(), reply_hdr.create_and_serialize()) { // Ignore for now because the other end will retry. // TODO: Implement a retry mechanism so we do not have to wait for the other end to time out. @@ -219,11 +219,11 @@ impl SharedArpPeer { ArpOperation::Reply => { debug!( "reply from `{}/{}`", - header.get_sender_protocol_addr(), - header.get_sender_hardware_addr() + header.sender_protocol_addr(), + header.sender_hardware_addr() ); self.cache - .insert(header.get_sender_protocol_addr(), header.get_sender_hardware_addr()); + .insert(header.sender_protocol_addr(), header.sender_hardware_addr()); }, } } @@ -249,7 +249,7 @@ impl SharedArpPeer { // > The frequency of the ARP request is very close to one per // > second, the maximum suggested by [RFC1122]. let result = { - for i in 0..self.arp_config.get_retry_count() + 1 { + for i in 0..self.arp_config.retry_count() + 1 { if let Err(e) = self .layer2_endpoint .transmit_arp_packet(MacAddress::broadcast(), header.create_and_serialize()) @@ -259,7 +259,7 @@ impl SharedArpPeer { } let arp_response = peer.do_wait_link_addr(ipv4_addr); - match conditional_yield_with_timeout(arp_response, self.arp_config.get_request_timeout()).await { + match conditional_yield_with_timeout(arp_response, self.arp_config.request_timeout()).await { Ok(link_addr) => { debug!("ARP result available ({:?})", link_addr); return Ok(link_addr); diff --git a/src/inetstack/protocols/layer3/arp/tests.rs b/src/inetstack/protocols/layer3/arp/tests.rs index fb98dc53d..53b5d2fef 100644 --- a/src/inetstack/protocols/layer3/arp/tests.rs +++ b/src/inetstack/protocols/layer3/arp/tests.rs @@ -67,10 +67,10 @@ fn arp_immediate_reply() -> Result<()> { // Sanity check ARP header. let arp_header = ArpHeader::parse_and_consume(pkt)?; - crate::ensure_eq!(arp_header.get_operation(), ArpOperation::Reply); - crate::ensure_eq!(arp_header.get_sender_hardware_addr(), local_mac); - crate::ensure_eq!(arp_header.get_sender_protocol_addr(), local_ipv4); - crate::ensure_eq!(arp_header.get_destination_protocol_addr(), remote_ipv4); + crate::ensure_eq!(arp_header.operation(), ArpOperation::Reply); + crate::ensure_eq!(arp_header.sender_hardware_addr(), local_mac); + crate::ensure_eq!(arp_header.sender_protocol_addr(), local_ipv4); + crate::ensure_eq!(arp_header.target_protocol_addr(), remote_ipv4); Ok(()) } @@ -123,7 +123,7 @@ fn arp_cache_update() -> Result<()> { engine.get_runtime().run_background_tasks(); // Check if the ARP cache has been updated. - let cache = engine.get_transport().export_arp_cache(); + let cache = engine.transport().export_arp_cache(); crate::ensure_eq!(cache.get(&other_remote_ipv4), Some(&other_remote_mac)); // Check if the ARP cache outputs a reply message. @@ -139,10 +139,10 @@ fn arp_cache_update() -> Result<()> { // Sanity check ARP header. let arp_header = ArpHeader::parse_and_consume(first_pkt)?; - crate::ensure_eq!(arp_header.get_operation(), ArpOperation::Reply); - crate::ensure_eq!(arp_header.get_sender_hardware_addr(), local_mac); - crate::ensure_eq!(arp_header.get_sender_protocol_addr(), local_ipv4); - crate::ensure_eq!(arp_header.get_destination_protocol_addr(), other_remote_ipv4); + crate::ensure_eq!(arp_header.operation(), ArpOperation::Reply); + crate::ensure_eq!(arp_header.sender_hardware_addr(), local_mac); + crate::ensure_eq!(arp_header.sender_protocol_addr(), local_ipv4); + crate::ensure_eq!(arp_header.target_protocol_addr(), other_remote_ipv4); Ok(()) } @@ -152,12 +152,9 @@ fn arp_cache_timeout() -> Result<()> { let mut now = Instant::now(); let other_remote_ipv4 = test_helpers::CARRIE_IPV4; let mut engine = new_engine(now, test_helpers::ALICE_CONFIG_PATH)?; - let mut inetstack = engine.get_transport(); + let mut inetstack = engine.transport(); let coroutine = Box::pin(async move { inetstack.arp_query(other_remote_ipv4).await }.fuse()); - let _qt = engine - .get_runtime() - .clone() - .schedule_coroutine("arp query", coroutine)?; + let _qt = engine.runtime().clone().schedule_coroutine("arp query", coroutine)?; for _ in 0..(ARP_RETRY_COUNT + 1) { engine.get_runtime().run_foreground_tasks(); diff --git a/src/inetstack/protocols/layer3/icmpv4/peer.rs b/src/inetstack/protocols/layer3/icmpv4/peer.rs index 0285b6f49..e258a1a1c 100644 --- a/src/inetstack/protocols/layer3/icmpv4/peer.rs +++ b/src/inetstack/protocols/layer3/icmpv4/peer.rs @@ -125,7 +125,7 @@ impl SharedIcmpv4Peer { match icmpv4_hdr.get_protocol() { Icmpv4Type2::EchoRequest { id, seq_num } => { if let Err(e) = self - .send_packet(Icmpv4Type2::EchoReply { id, seq_num }, header.get_src_addr(), buffer) + .send_packet(Icmpv4Type2::EchoReply { id, seq_num }, header.src_addr(), buffer) .await { warn!("Could not send packet: {:?}", e); @@ -184,7 +184,7 @@ impl SharedIcmpv4Peer { let seq_num = self.make_seq_num(); let echo_request = Icmpv4Type2::EchoRequest { id, seq_num }; - let t0 = self.runtime.get_now(); + let t0 = self.runtime.now(); let pkt = DemiBuffer::new_with_headroom( ICMPV4_ECHO_REQUEST_MESSAGE_SIZE, (ICMPV4_HEADER_SIZE + IPV4_HEADER_MIN_SIZE as usize + ETHERNET2_HEADER_SIZE) as u16, @@ -218,7 +218,7 @@ impl SharedIcmpv4Peer { { Ok(_) => { self.inflight.remove(&(id, seq_num)); - Ok(self.runtime.get_now() - t0) + Ok(self.runtime.now() - t0) }, Err(_) => { let message = "timer expired"; diff --git a/src/inetstack/protocols/layer3/ipv4/header.rs b/src/inetstack/protocols/layer3/ipv4/header.rs index 594efe01b..0c2931d68 100644 --- a/src/inetstack/protocols/layer3/ipv4/header.rs +++ b/src/inetstack/protocols/layer3/ipv4/header.rs @@ -265,15 +265,15 @@ impl Ipv4Header { buf[10..12].copy_from_slice(&checksum.to_be_bytes()); } - pub fn get_src_addr(&self) -> Ipv4Addr { + pub fn src_addr(&self) -> Ipv4Addr { self.src_addr } - pub fn get_dest_addr(&self) -> Ipv4Addr { + pub fn dst_addr(&self) -> Ipv4Addr { self.dst_addr } - pub fn get_protocol(&self) -> IpProtocol { + pub fn protocol(&self) -> IpProtocol { self.protocol } diff --git a/src/inetstack/protocols/layer3/ipv4/tests.rs b/src/inetstack/protocols/layer3/ipv4/tests.rs index a6d67435d..5cee4e98c 100644 --- a/src/inetstack/protocols/layer3/ipv4/tests.rs +++ b/src/inetstack/protocols/layer3/ipv4/tests.rs @@ -117,9 +117,9 @@ fn test_ipv4_header_parse_good() -> Result<()> { match Ipv4Header::parse_and_strip(&mut buffer) { Ok(ipv4_hdr) => { - assert_eq!(ipv4_hdr.get_src_addr(), ALICE_IPV4); - assert_eq!(ipv4_hdr.get_dest_addr(), BOB_IPV4); - assert_eq!(ipv4_hdr.get_protocol(), IpProtocol::UDP); + assert_eq!(ipv4_hdr.src_addr(), ALICE_IPV4); + assert_eq!(ipv4_hdr.dst_addr(), BOB_IPV4); + assert_eq!(ipv4_hdr.protocol(), IpProtocol::UDP); assert_eq!(buffer.len(), PAYLOAD_SIZE); assert_eq!(buffer[..], data_bytes[..]); }, diff --git a/src/inetstack/protocols/layer3/mod.rs b/src/inetstack/protocols/layer3/mod.rs index 5859416e6..b6f5a7de7 100644 --- a/src/inetstack/protocols/layer3/mod.rs +++ b/src/inetstack/protocols/layer3/mod.rs @@ -92,17 +92,17 @@ impl SharedLayer3Endpoint { } if bad_src(header) { - warn!("dropping packet: Invalid source addr ({})", header.get_src_addr()); + warn!("dropping packet: Invalid source addr ({})", header.src_addr()); continue; } - let protocol = header.get_protocol(); + let protocol = header.protocol(); match protocol { IpProtocol::ICMPv4 => { self.icmpv4.receive(header, packet); continue; }, - _ => batch.push((header.get_src_addr(), protocol, packet)), + _ => batch.push((header.src_addr(), protocol, packet)), } }, EtherType2::Ipv6 => warn!("Ipv6 not supported yet"), // Ignore for now. @@ -112,7 +112,7 @@ impl SharedLayer3Endpoint { } fn is_for_us(&mut self, header: Ipv4Header) -> bool { - let dst = header.get_dest_addr(); + let dst = header.dst_addr(); dst == self.local_ip || dst.is_broadcast() } @@ -169,7 +169,7 @@ impl SharedLayer3Endpoint { } fn bad_src(hdr: Ipv4Header) -> bool { - let src = hdr.get_src_addr(); + let src = hdr.src_addr(); src.is_broadcast() || src.is_multicast() || src.is_unspecified() } diff --git a/src/inetstack/protocols/layer4/tcp/established/mod.rs b/src/inetstack/protocols/layer4/tcp/established/mod.rs index bf4df3940..cedff8257 100644 --- a/src/inetstack/protocols/layer4/tcp/established/mod.rs +++ b/src/inetstack/protocols/layer4/tcp/established/mod.rs @@ -188,7 +188,7 @@ impl SharedEstablishedSocket { tcp_hdr, ); - let now = self.runtime.get_now(); + let now = self.runtime.now(); let mut layer3_endpoint = self.layer3_endpoint.clone(); Receiver::receive(&mut self.control_block, &mut layer3_endpoint, tcp_hdr, buf, now); } diff --git a/src/inetstack/protocols/layer4/tcp/established/receiver.rs b/src/inetstack/protocols/layer4/tcp/established/receiver.rs index 4347316f1..e61833711 100644 --- a/src/inetstack/protocols/layer4/tcp/established/receiver.rs +++ b/src/inetstack/protocols/layer4/tcp/established/receiver.rs @@ -281,7 +281,7 @@ impl Receiver { Ok(()) } - pub fn get_receive_window_size(&self) -> u32 { + pub fn receive_window_size(&self) -> u32 { let bytes_unread: u32 = (self.receive_next_seq_no - self.reader_next_seq_no).into(); // The window should be less than 1GB or 64KB without scaling. debug_assert!( @@ -296,7 +296,7 @@ impl Receiver { } pub fn hdr_window_size(&self) -> u16 { - let window_size = self.get_receive_window_size(); + let window_size = self.receive_window_size(); let hdr_window_size = expect_ok!( (window_size >> self.window_scale_shift_bits).try_into(), "Window size overflow" @@ -399,7 +399,7 @@ impl Receiver { let receive_next = cb.receiver.receive_next_seq_no; - let after_receive_window = receive_next + SeqNumber::from(cb.receiver.get_receive_window_size()); + let after_receive_window = receive_next + SeqNumber::from(cb.receiver.receive_window_size()); // Check if this segment fits in our receive window. // In the optimal case it starts at RCV.NXT, so we check for that first. diff --git a/src/inetstack/protocols/layer4/tcp/established/sender.rs b/src/inetstack/protocols/layer4/tcp/established/sender.rs index 874d320ea..79e73c029 100644 --- a/src/inetstack/protocols/layer4/tcp/established/sender.rs +++ b/src/inetstack/protocols/layer4/tcp/established/sender.rs @@ -195,7 +195,7 @@ impl Sender { } fn update_retransmit_deadline(&mut self, now: Instant) -> Option { - match self.unacked_queue.get_front() { + match self.unacked_queue.front() { Some(UnackedSegment { bytes: _, initial_tx: Some(initial_tx), @@ -250,12 +250,12 @@ impl Sender { // We can always send the FIN immediately. cb.sender.fin_seq_no = Some(cb.sender.unsent_next_seq_no); cb.sender.unsent_next_seq_no = cb.sender.unsent_next_seq_no + 1.into(); - Self::send_fin(cb, layer3_endpoint, runtime.get_now())?; + Self::send_fin(cb, layer3_endpoint, runtime.now())?; } else { for mut buf in bufs.into_iter() { cb.sender.unsent_next_seq_no = cb.sender.unsent_next_seq_no + (buf.len() as u32).into(); if cb.sender.send_window.get() > 0 { - Self::send_segment(cb, layer3_endpoint, runtime.get_now(), &mut buf); + Self::send_segment(cb, layer3_endpoint, runtime.now(), &mut buf); if !buf.is_empty() { cb.sender.unsent_queue.push(buf); @@ -286,7 +286,7 @@ impl Sender { loop { // Get next bit of unsent data. let buffer = cb.sender.unsent_queue.pop(None).await?; - Self::send_buffer(cb, layer3_endpoint, runtime.get_now(), buffer).await?; + Self::send_buffer(cb, layer3_endpoint, runtime.now(), buffer).await?; } } @@ -565,7 +565,7 @@ impl Sender { cb.sender.rto_calculator.back_off(); // RFC 6298 Section 5.6: Restart the retransmission timer with the new RTO. - let deadline = runtime.get_now() + cb.sender.rto_calculator.rto(); + let deadline = runtime.now() + cb.sender.rto_calculator.rto(); cb.sender.retransmit_deadline_time_secs.set(Some(deadline)); }, Err(_) => { @@ -579,7 +579,7 @@ impl Sender { /// Retransmits the earliest segment that has not (yet) been acknowledged by our peer. pub fn retransmit(cb: &mut ControlBlock, layer3_endpoint: &mut SharedLayer3Endpoint) { - if let Some(segment) = cb.sender.unacked_queue.get_front_mut() { + if let Some(segment) = cb.sender.unacked_queue.front_mut() { // We're retransmitting this, so we can no longer use an ACK for it as an RTT measurement (as we can't tell // if the ACK is for the original or the retransmission). Remove the transmission timestamp from the entry. segment.initial_tx.take(); diff --git a/src/inetstack/protocols/layer4/tcp/passive_open.rs b/src/inetstack/protocols/layer4/tcp/passive_open.rs index 9191563c8..271390f02 100644 --- a/src/inetstack/protocols/layer4/tcp/passive_open.rs +++ b/src/inetstack/protocols/layer4/tcp/passive_open.rs @@ -128,7 +128,7 @@ impl SharedPassiveSocket { } // See if this packet is for an already established but not accepted socket. - if let Some((_, socket)) = self.ready.get_values().find(|(addr, _)| *addr == remote) { + if let Some((_, socket)) = self.ready.values().find(|(addr, _)| *addr == remote) { if let Ok(socket) = socket { socket.clone().receive(tcp_hdr, buf); } diff --git a/src/inetstack/protocols/layer4/tcp/tests/simulator.rs b/src/inetstack/protocols/layer4/tcp/tests/simulator.rs index d5c274937..88fb8f28e 100644 --- a/src/inetstack/protocols/layer4/tcp/tests/simulator.rs +++ b/src/inetstack/protocols/layer4/tcp/tests/simulator.rs @@ -803,9 +803,9 @@ impl Simulation { } fn check_ipv4_header(&self, header: &Ipv4Header, protocol: IpProtocol) -> Result<()> { - ensure_eq!(header.get_src_addr(), self.local_sockaddr.ip().to_owned()); - ensure_eq!(header.get_dest_addr(), self.remote_sockaddr.ip().to_owned()); - ensure_eq!(header.get_protocol(), protocol); + ensure_eq!(header.src_addr(), self.local_sockaddr.ip().to_owned()); + ensure_eq!(header.dst_addr(), self.remote_sockaddr.ip().to_owned()); + ensure_eq!(header.protocol(), protocol); Ok(()) } @@ -891,7 +891,7 @@ impl Simulation { let header = Ipv4Header::parse_and_strip(buffer)?; self.check_ipv4_header(&header, IpProtocol::TCP)?; - let header = TcpHeader::parse_and_strip(&header.get_src_addr(), &header.get_dest_addr(), buffer, true)?; + let header = TcpHeader::parse_and_strip(&header.src_addr(), &header.dst_addr(), buffer, true)?; ensure_eq!(tcp_packet.seqnum.win as usize, buffer.len()); self.check_tcp_header(&header, tcp_packet)?; diff --git a/src/inetstack/test_helpers/engine.rs b/src/inetstack/test_helpers/engine.rs index 8d50f99d0..f6456666f 100644 --- a/src/inetstack/test_helpers/engine.rs +++ b/src/inetstack/test_helpers/engine.rs @@ -79,7 +79,7 @@ impl SharedEngine { } pub fn advance_clock(&mut self, now: Instant) { - self.libos.get_runtime().advance_clock(now) + self.libos.runtime().advance_clock(now) } pub fn push_frame(&mut self, bytes: DemiBuffer) { @@ -89,7 +89,7 @@ impl SharedEngine { } pub async fn ipv4_ping(&mut self, dest_ipv4_addr: Ipv4Addr, timeout: Option) -> Result { - self.libos.get_transport().ping(dest_ipv4_addr, timeout).await + self.libos.transport().ping(dest_ipv4_addr, timeout).await } pub fn udp_pushto(&mut self, qd: QDesc, buf: DemiBuffer, to: SocketAddrV4) -> Result { @@ -156,16 +156,16 @@ impl SharedEngine { } pub async fn arp_query(self, ipv4_addr: Ipv4Addr) -> Result { - self.libos.get_transport().arp_query(ipv4_addr).await + self.libos.transport().arp_query(ipv4_addr).await } pub fn export_arp_cache(&self) -> HashMap { - self.libos.get_transport().export_arp_cache() + self.libos.transport().export_arp_cache() } pub fn wait(&self, qt: QToken) -> Result<(QDesc, OperationResult), Fail> { for _ in 0..MAX_LOOP_ITERATIONS { - match self.get_runtime().wait(qt, Duration::ZERO) { + match self.runtime().wait(qt, Duration::ZERO) { Ok(result) => return Ok(result), Err(e) if e.errno == libc::ETIMEDOUT => continue, Err(e) => return Err(e), @@ -174,16 +174,16 @@ impl SharedEngine { Err(Fail::new(libc::ETIMEDOUT, "Should have returned a completed task")) } - pub fn get_runtime(&self) -> SharedDemiRuntime { - self.libos.get_runtime().clone() + pub fn runtime(&self) -> SharedDemiRuntime { + self.libos.runtime().clone() } - pub fn get_transport(&self) -> SharedInetStack { - self.libos.get_transport().clone() + pub fn transport(&self) -> SharedInetStack { + self.libos.transport().clone() } fn run_scheduler(&mut self) { - match self.get_runtime().wait_any(&[], Duration::ZERO) { + match self.runtime().wait_any(&[], Duration::ZERO) { Ok(_) => unreachable!("Should not have completed a task without qtokens passed in"), Err(e) => assert_eq!(e.errno, libc::ETIMEDOUT), }; diff --git a/src/inetstack/test_helpers/physical_layer.rs b/src/inetstack/test_helpers/physical_layer.rs index ee7508501..42ca82a78 100644 --- a/src/inetstack/test_helpers/physical_layer.rs +++ b/src/inetstack/test_helpers/physical_layer.rs @@ -68,8 +68,7 @@ impl SharedTestPhysicalLayer { self.incoming.push_back(pkt); } - /// Get the underlying DemiRuntime. - pub fn get_runtime(&self) -> SharedDemiRuntime { + pub fn runtime(&self) -> SharedDemiRuntime { self.runtime.clone() } } diff --git a/src/runtime/mod.rs b/src/runtime/mod.rs index ee0fbf047..b3b3c623c 100644 --- a/src/runtime/mod.rs +++ b/src/runtime/mod.rs @@ -273,7 +273,7 @@ impl SharedDemiRuntime { mut acceptor: Acceptor, timeout: Duration, ) -> Result<(), Fail> { - let deadline_time = self.get_now() + timeout; + let deadline_time = self.now() + timeout; loop { if self.completed_tasks.is_empty() { self.run_scheduler(); @@ -287,7 +287,7 @@ impl SharedDemiRuntime { return Ok(()); } } - if self.get_now() >= deadline_time { + if self.now() >= deadline_time { break; } else { self.advance_clock_to_now(); @@ -354,8 +354,7 @@ impl SharedDemiRuntime { self.ts_iters = (self.ts_iters + 1) % TIMER_RESOLUTION; } - /// Gets the current time according to our internal timer. - pub fn get_now(&self) -> Instant { + pub fn now(&self) -> Instant { timer::global_get_time() } @@ -373,13 +372,11 @@ impl SharedDemiRuntime { } } - /// Inserts a mapping and returns the previously mapped queue descriptor if it exists. pub fn insert_socket_id_to_qd(&mut self, id: SocketId, qd: QDesc) -> Option { trace!("Insert socket id to queue descriptor mapping: {:?} -> {:?}", id, qd); self.socket_id_to_qdesc_map.insert(id, qd) } - /// Removes a mapping and returns the mapped queue descriptor. pub fn remove_socket_id_to_qd(&mut self, id: &SocketId) -> Option { match self.socket_id_to_qdesc_map.remove(id) { Some(qd) => { @@ -397,7 +394,7 @@ impl SharedDemiRuntime { } pub fn is_addr_in_use(&self, socket_addrv4: SocketAddrV4) -> bool { - trace!("Check address in use: {:?}", socket_addrv4); + trace!("is_addr_in_use: checking: {:?}", socket_addrv4); self.socket_id_to_qdesc_map.is_in_use(socket_addrv4) } diff --git a/src/runtime/network/transport.rs b/src/runtime/network/transport.rs index 78388eacb..3cd13094f 100644 --- a/src/runtime/network/transport.rs +++ b/src/runtime/network/transport.rs @@ -86,5 +86,5 @@ pub trait NetworkTransport: Clone + 'static + DemiMemoryAllocator { fn close(&mut self, sd: &mut Self::SocketDescriptor) -> impl std::future::Future>; /// Pull the common runtime out of the transport. We only need this because traits do not support members. - fn get_runtime(&self) -> &SharedDemiRuntime; + fn runtime(&self) -> &SharedDemiRuntime; } diff --git a/src/runtime/queue/mod.rs b/src/runtime/queue/mod.rs index 486b6e874..f8cff7e23 100644 --- a/src/runtime/queue/mod.rs +++ b/src/runtime/queue/mod.rs @@ -37,7 +37,7 @@ pub type BackgroundTask = TaskWithResult<()>; struct InternalId(usize); pub trait IoQueue: Any { - fn get_qtype(&self) -> QType; + fn qtype(&self) -> QType; fn as_any_ref(&self) -> &dyn Any; fn as_any_mut(&mut self) -> &mut dyn Any; fn as_any(self: Box) -> Box; @@ -70,17 +70,17 @@ impl IoQueueTable { } pub fn get_type(&self, qd: &QDesc) -> Result { - Ok(self.get_queue_ref(qd)?.get_qtype()) + Ok(self.queue_ref(qd)?.qtype()) } /// Gets/borrows a reference to the queue metadata associated with an I/O queue descriptor. pub fn get<'a, T: IoQueue>(&'a self, qd: &QDesc) -> Result<&'a T, Fail> { - downcast_queue_ptr::(self.get_queue_ref(qd)?) + downcast_queue_ptr::(self.queue_ref(qd)?) } /// Gets/borrows a mutable reference to the queue metadata associated with an I/O queue descriptor pub fn get_mut<'a, T: IoQueue>(&'a mut self, qd: &QDesc) -> Result<&'a mut T, Fail> { - downcast_mut_ptr::(self.get_mut_queue_ref(qd)?) + downcast_mut_ptr::(self.queue_ref_mut(qd)?) } /// Releases the entry associated with an I/O queue descriptor. @@ -96,8 +96,7 @@ impl IoQueueTable { downcast_queue::(self.table.remove(internal_id.into())) } - /// Gets an iterator over all registered queues. - pub fn get_values(&self) -> Iter<'_, Box> { + pub fn values(&self) -> Iter<'_, Box> { self.table.iter() } @@ -106,7 +105,7 @@ impl IoQueueTable { } /// Gets the index in the I/O queue descriptors table to which a given I/O queue descriptor refers to. - fn get_queue_ref(&self, qd: &QDesc) -> Result<&Box, Fail> { + fn queue_ref(&self, qd: &QDesc) -> Result<&Box, Fail> { if let Some(internal_id) = self.qd_to_offset.get(qd) { if let Some(queue) = self.table.get(internal_id.into()) { return Ok(queue); @@ -118,7 +117,7 @@ impl IoQueueTable { Err(Fail::new(libc::EBADF, &cause)) } - fn get_mut_queue_ref(&mut self, qd: &QDesc) -> Result<&mut Box, Fail> { + fn queue_ref_mut(&mut self, qd: &QDesc) -> Result<&mut Box, Fail> { if let Some(internal_id) = self.qd_to_offset.get(qd) { if let Some(queue) = self.table.get_mut(internal_id.into()) { return Ok(queue); @@ -242,7 +241,7 @@ mod tests { pub struct TestQueue {} impl IoQueue for TestQueue { - fn get_qtype(&self) -> QType { + fn qtype(&self) -> QType { QType::TestQueue } diff --git a/tests/rust/common/libos.rs b/tests/rust/common/libos.rs index ce9523dd9..6c23160df 100644 --- a/tests/rust/common/libos.rs +++ b/tests/rust/common/libos.rs @@ -61,7 +61,7 @@ impl DummyLibOS { } pub fn wait(&mut self, qt: QToken, timeout: Duration) -> Result<(QDesc, OperationResult), Fail> { - self.get_runtime().wait(qt, timeout) + self.runtime().wait(qt, timeout) } } diff --git a/tests/rust/udp-tests/args.rs b/tests/rust/udp-tests/args.rs index 11c507f6d..1fccb7197 100644 --- a/tests/rust/udp-tests/args.rs +++ b/tests/rust/udp-tests/args.rs @@ -51,7 +51,7 @@ impl ProgramArguments { }) } - pub fn get_local_socket_addr(&self) -> SocketAddr { + pub fn local_socket_addr(&self) -> SocketAddr { self.local_socket_addr } diff --git a/tests/rust/udp-tests/main.rs b/tests/rust/udp-tests/main.rs index ab7892eb5..3e47e4a5d 100644 --- a/tests/rust/udp-tests/main.rs +++ b/tests/rust/udp-tests/main.rs @@ -43,12 +43,12 @@ fn main() -> Result<()> { append_test_result!( test_results, - bind::run_tests(&mut libos, &args.get_local_socket_addr().ip()) + bind::run_tests(&mut libos, &args.local_socket_addr().ip()) ); append_test_result!( test_results, - close::run_tests(&mut libos, &args.get_local_socket_addr().ip()) + close::run_tests(&mut libos, &args.local_socket_addr().ip()) ); for (test_name, test_status, test_result) in test_results { From a6a14d5937aeab113cd3dd50641506e0af479f71 Mon Sep 17 00:00:00 2001 From: Anand Bonde Date: Fri, 11 Jul 2025 14:32:21 -0700 Subject: [PATCH 2/2] examples: more cleanup: remove type annotations and better names Reduced syntactic clutter and used better names. --- examples/rust/tcp-dump.rs | 64 +++++++------- examples/rust/tcp-ping-pong.rs | 67 ++++++++------- examples/rust/tcp-pktgen.rs | 69 ++++++++------- examples/rust/tcp-push-pop.rs | 58 ++++++------- examples/rust/udp-dump.rs | 48 +++++------ examples/rust/udp-echo.rs | 94 ++++++++++----------- examples/rust/udp-ping-pong.rs | 82 +++++++++--------- examples/rust/udp-pktgen.rs | 92 ++++++++++---------- examples/rust/udp-push-pop.rs | 56 ++++++------ examples/rust/udp-relay.rs | 76 ++++++++--------- examples/tcp-close/client.rs | 70 ++++++++------- examples/tcp-close/server.rs | 50 +++++------ src/catnap/win/transport.rs | 2 +- src/inetstack/protocols/layer3/arp/tests.rs | 6 +- tests/rust/udp-tests/args.rs | 34 ++++---- tests/rust/udp-tests/main.rs | 32 +++---- 16 files changed, 431 insertions(+), 469 deletions(-) diff --git a/examples/rust/tcp-dump.rs b/examples/rust/tcp-dump.rs index 294b515c9..6df773e0b 100644 --- a/examples/rust/tcp-dump.rs +++ b/examples/rust/tcp-dump.rs @@ -8,12 +8,8 @@ //====================================================================================================================== use ::anyhow::Result; -use ::clap::{Arg, ArgMatches, Command}; -use ::demikernel::{ - demi_sgarray_t, - runtime::types::{demi_opcode_t, demi_qresult_t}, - LibOS, LibOSName, QDesc, QToken, -}; +use ::clap::{Arg, Command}; +use ::demikernel::{runtime::types::demi_opcode_t, LibOS, LibOSName, QDesc}; use ::std::{ net::SocketAddr, str::FromStr, @@ -34,14 +30,14 @@ pub const SOCK_STREAM: i32 = libc::SOCK_STREAM; #[derive(Debug)] pub struct ProgramArguments { - local_socket_addr: SocketAddr, + local_addr: SocketAddr, } impl ProgramArguments { const DEFAULT_LOCAL_IPV4_ADDR: &'static str = "127.0.0.1:12345"; pub fn new() -> Result { - let matches: ArgMatches = Command::new("tcp-dump") + let matches = Command::new("tcp-dump") .arg( Arg::new("local") .long("local") @@ -52,23 +48,23 @@ impl ProgramArguments { ) .get_matches(); - let mut args: ProgramArguments = ProgramArguments { - local_socket_addr: SocketAddr::from_str(Self::DEFAULT_LOCAL_IPV4_ADDR)?, + let mut args = ProgramArguments { + local_addr: SocketAddr::from_str(Self::DEFAULT_LOCAL_IPV4_ADDR)?, }; if let Some(addr) = matches.get_one::("local") { - args.set_local_socket_addr(addr)?; + args.set_local_addr(addr)?; } Ok(args) } - pub fn local_socket_addr(&self) -> SocketAddr { - self.local_socket_addr + pub fn local_addr(&self) -> SocketAddr { + self.local_addr } - fn set_local_socket_addr(&mut self, addr: &str) -> Result<()> { - self.local_socket_addr = SocketAddr::from_str(addr)?; + fn set_local_addr(&mut self, addr: &str) -> Result<()> { + self.local_addr = SocketAddr::from_str(addr)?; Ok(()) } } @@ -82,13 +78,13 @@ impl Application { const LOG_INTERVAL_SECONDS: u64 = 5; pub fn new(mut libos: LibOS, args: &ProgramArguments) -> Result { - let local_socket_addr: SocketAddr = args.local_socket_addr(); - let sockqd: QDesc = match libos.socket(AF_INET, SOCK_STREAM, 0) { + let addr = args.local_addr(); + let sockqd = match libos.socket(AF_INET, SOCK_STREAM, 0) { Ok(sockqd) => sockqd, Err(e) => anyhow::bail!("failed to create socket: {:?}", e), }; - match libos.bind(sockqd, local_socket_addr) { + match libos.bind(sockqd, addr) { Ok(()) => (), Err(e) => { // If error, close socket. @@ -112,18 +108,18 @@ impl Application { }, } - println!("Local Address: {:?}", local_socket_addr); + println!("Local Address: {:?}", addr); Ok(Self { libos, sockqd }) } pub fn run(&mut self) -> Result<()> { - let start_time: Instant = Instant::now(); - let mut num_clients: usize = 0; - let mut num_bytes: usize = 0; - let mut qtokens: Vec = Vec::new(); - let mut last_log_time: Instant = Instant::now(); - let mut client_qds: Vec = Vec::default(); + let start_time = Instant::now(); + let mut num_clients = 0; + let mut num_bytes = 0; + let mut qtokens = Vec::new(); + let mut last_log_time = Instant::now(); + let mut client_qds = Vec::default(); // Accept first connection. match self.libos.accept(self.sockqd) { @@ -134,7 +130,7 @@ impl Application { loop { // Dump statistics. if last_log_time.elapsed() > Duration::from_secs(Self::LOG_INTERVAL_SECONDS) { - let elapsed_time: Duration = Instant::now() - start_time; + let elapsed_time = Instant::now() - start_time; println!( "nclients={:?} / {:?} B / {:?} us", num_clients, @@ -144,7 +140,7 @@ impl Application { last_log_time = Instant::now(); } - let qr: demi_qresult_t = match self.libos.wait_any(&qtokens, None) { + let qr = match self.libos.wait_any(&qtokens, None) { Ok((i, qr)) => { qtokens.swap_remove(i); qr @@ -158,7 +154,7 @@ impl Application { num_clients += 1; // Pop first packet from this connection. - let sockqd: QDesc = unsafe { qr.qr_value.ares.qd.into() }; + let sockqd = unsafe { qr.qr_value.ares.qd.into() }; client_qds.push(sockqd); match self.libos.pop(sockqd, None) { Ok(qt) => qtokens.push(qt), @@ -173,8 +169,8 @@ impl Application { }, // Pop completed. demi_opcode_t::DEMI_OPC_POP => { - let sockqd: QDesc = qr.qr_qd.into(); - let sga: demi_sgarray_t = unsafe { qr.qr_value.sga }; + let sockqd = qr.qr_qd.into(); + let sga = unsafe { qr.qr_value.sga }; num_bytes += sga.segments[0].data_len_bytes as usize; @@ -184,7 +180,7 @@ impl Application { } // Pop another packet. - let qt: QToken = match self.libos.pop(sockqd, None) { + let qt = match self.libos.pop(sockqd, None) { Ok(qt) => qt, Err(e) => anyhow::bail!("failed to pop data from socket: {:?}", e), }; @@ -212,12 +208,12 @@ impl Drop for Application { } fn main() -> Result<()> { - let args: ProgramArguments = ProgramArguments::new()?; - let libos_name: LibOSName = match LibOSName::from_env() { + let args = ProgramArguments::new()?; + let libos_name = match LibOSName::from_env() { Ok(libos_name) => libos_name.into(), Err(e) => anyhow::bail!("{:?}", e), }; - let libos: LibOS = match LibOS::new(libos_name, None) { + let libos = match LibOS::new(libos_name, None) { Ok(libos) => libos, Err(e) => anyhow::bail!("failed to initialize libos: {:?}", e.cause), }; diff --git a/examples/rust/tcp-ping-pong.rs b/examples/rust/tcp-ping-pong.rs index 4fbc80724..836eaf1b8 100644 --- a/examples/rust/tcp-ping-pong.rs +++ b/examples/rust/tcp-ping-pong.rs @@ -8,7 +8,7 @@ // Imports //====================================================================================================================== use ::anyhow::Result; -use ::demikernel::{demi_sgarray_t, runtime::types::demi_opcode_t, LibOS, LibOSName, QDesc, QToken}; +use ::demikernel::{demi_sgarray_t, runtime::types::demi_opcode_t, LibOS, LibOSName, QDesc}; use ::std::{env, net::SocketAddr, slice, str::FromStr, time::Duration, u8}; use log::{error, warn}; @@ -33,7 +33,7 @@ const NUM_PING_PONG_ROUNDS: usize = 1024; const TIMEOUT_SECONDS: Duration = Duration::from_secs(256); fn mksga(libos: &mut LibOS, size: usize, value: u8) -> Result { - let sga: demi_sgarray_t = match libos.sgaalloc(size) { + let sga = match libos.sgaalloc(size) { Ok(sga) => sga, Err(e) => anyhow::bail!("failed to allocate scatter-gather array: {:?}", e), }; @@ -41,7 +41,7 @@ fn mksga(libos: &mut LibOS, size: usize, value: u8) -> Result { // Ensure that allocated the array has the requested size. if sga.segments[0].data_len_bytes as usize != size { freesga(libos, sga); - let seglen: usize = sga.segments[0].data_len_bytes as usize; + let seglen = sga.segments[0].data_len_bytes as usize; anyhow::bail!( "failed to allocate scatter-gather array: expected size={:?} allocated size={:?}", size, @@ -50,10 +50,10 @@ fn mksga(libos: &mut LibOS, size: usize, value: u8) -> Result { } // Fill in the array. - let ptr: *mut u8 = sga.segments[0].data_buf_ptr as *mut u8; - let len: usize = sga.segments[0].data_len_bytes as usize; - let slice: &mut [u8] = unsafe { slice::from_raw_parts_mut(ptr, len) }; - let mut fill: u8 = value; + let ptr = sga.segments[0].data_buf_ptr as *mut u8; + let len = sga.segments[0].data_len_bytes as usize; + let slice = unsafe { slice::from_raw_parts_mut(ptr, len) }; + let mut fill = value; for x in slice { *x = fill; fill = (fill % (u8::MAX - 1) + 1) as u8; @@ -70,7 +70,7 @@ fn freesga(libos: &mut LibOS, sga: demi_sgarray_t) { } fn accept_and_wait(libos: &mut LibOS, sockqd: QDesc) -> Result { - let qt: QToken = match libos.accept(sockqd) { + let qt = match libos.accept(sockqd) { Ok(qt) => qt, Err(e) => anyhow::bail!("accept failed: {:?}", e), }; @@ -81,8 +81,8 @@ fn accept_and_wait(libos: &mut LibOS, sockqd: QDesc) -> Result { } } -fn connect_and_wait(libos: &mut LibOS, sockqd: QDesc, remote_socket_addr: SocketAddr) -> Result<()> { - let qt: QToken = match libos.connect(sockqd, remote_socket_addr) { +fn connect_and_wait(libos: &mut LibOS, sockqd: QDesc, remote_addr: SocketAddr) -> Result<()> { + let qt = match libos.connect(sockqd, remote_addr) { Ok(qt) => qt, Err(e) => anyhow::bail!("connect failed: {:?}", e), }; @@ -96,7 +96,7 @@ fn connect_and_wait(libos: &mut LibOS, sockqd: QDesc, remote_socket_addr: Socket } fn push_and_wait(libos: &mut LibOS, sockqd: QDesc, sga: &demi_sgarray_t) -> Result<()> { - let qt: QToken = match libos.push(sockqd, sga) { + let qt = match libos.push(sockqd, sga) { Ok(qt) => qt, Err(e) => anyhow::bail!("push failed: {:?}", e), }; @@ -110,23 +110,23 @@ fn push_and_wait(libos: &mut LibOS, sockqd: QDesc, sga: &demi_sgarray_t) -> Resu } fn pop_and_wait(libos: &mut LibOS, sockqd: QDesc, recvbuf: &mut [u8]) -> Result<()> { - let mut index: usize = 0; + let mut index = 0; while index < recvbuf.len() { - let qt: QToken = match libos.pop(sockqd, None) { + let qt = match libos.pop(sockqd, None) { Ok(qt) => qt, Err(e) => anyhow::bail!("pop failed: {:?}", e), }; - let sga: demi_sgarray_t = match libos.wait(qt, Some(TIMEOUT_SECONDS)) { + let sga = match libos.wait(qt, Some(TIMEOUT_SECONDS)) { Ok(qr) if qr.qr_opcode == demi_opcode_t::DEMI_OPC_POP => unsafe { qr.qr_value.sga }, Ok(_) => anyhow::bail!("unexpected result"), Err(e) => anyhow::bail!("operation failed: {:?}", e), }; // Copy data. - let ptr: *mut u8 = sga.segments[0].data_buf_ptr as *mut u8; - let len: usize = sga.segments[0].data_len_bytes as usize; - let slice: &mut [u8] = unsafe { slice::from_raw_parts_mut(ptr, len) }; + let ptr = sga.segments[0].data_buf_ptr as *mut u8; + let len = sga.segments[0].data_len_bytes as usize; + let slice = unsafe { slice::from_raw_parts_mut(ptr, len) }; for x in slice { recvbuf[index] = *x; index += 1; @@ -156,7 +156,7 @@ pub struct TcpServer { impl TcpServer { pub fn new(mut libos: LibOS) -> Result { - let sockqd: QDesc = match libos.socket(AF_INET, SOCK_STREAM, 0) { + let sockqd = match libos.socket(AF_INET, SOCK_STREAM, 0) { Ok(sockqd) => sockqd, Err(e) => anyhow::bail!("failed to create socket: {:?}", e), }; @@ -169,8 +169,8 @@ impl TcpServer { }); } - pub fn run(&mut self, local_socket_addr: SocketAddr, num_rounds: usize) -> Result<()> { - if let Err(e) = self.libos.bind(self.listening_sockqd, local_socket_addr) { + pub fn run(&mut self, local_addr: SocketAddr, num_rounds: usize) -> Result<()> { + if let Err(e) = self.libos.bind(self.listening_sockqd, local_addr) { anyhow::bail!("bind failed: {:?}", e) }; @@ -185,11 +185,11 @@ impl TcpServer { // Perform multiple ping-pong rounds. for i in 0..num_rounds { - let mut fill_char: u8 = (i % (u8::MAX as usize - 1) + 1) as u8; + let mut fill_char = (i % (u8::MAX as usize - 1) + 1) as u8; // Pop data, and sanity check it. { - let mut recvbuf: [u8; BUFSIZE_BYTES] = [0; BUFSIZE_BYTES]; + let mut recvbuf = [0; BUFSIZE_BYTES]; if let Err(e) = pop_and_wait( &mut self.libos, self.accepted_sockqd.expect("should be a valid queue descriptor"), @@ -257,7 +257,7 @@ pub struct TcpClient { impl TcpClient { pub fn new(mut libos: LibOS) -> Result { - let sockqd: QDesc = match libos.socket(AF_INET, SOCK_STREAM, 0) { + let sockqd = match libos.socket(AF_INET, SOCK_STREAM, 0) { Ok(sockqd) => sockqd, Err(e) => anyhow::bail!("failed to create socket: {:?}", e), }; @@ -269,14 +269,14 @@ impl TcpClient { }); } - fn run(&mut self, remote_socket_addr: SocketAddr, num_rounds: usize) -> Result<()> { - if let Err(e) = connect_and_wait(&mut self.libos, self.sockqd, remote_socket_addr) { + fn run(&mut self, remote_addr: SocketAddr, num_rounds: usize) -> Result<()> { + if let Err(e) = connect_and_wait(&mut self.libos, self.sockqd, remote_addr) { anyhow::bail!("connect and wait failed: {:?}", e); } // Perform multiple ping-pong rounds. for i in 0..num_rounds { - let fill_char: u8 = (i % (u8::MAX as usize - 1) + 1) as u8; + let fill_char = (i % (u8::MAX as usize - 1) + 1) as u8; // Push data. { @@ -293,11 +293,11 @@ impl TcpClient { } } - let mut fill_check: u8 = (i % (u8::MAX as usize - 1) + 1) as u8; + let mut fill_check = (i % (u8::MAX as usize - 1) + 1) as u8; // Pop data, and sanity check it. { - let mut recvbuf: [u8; BUFSIZE_BYTES] = [0; BUFSIZE_BYTES]; + let mut recvbuf = [0; BUFSIZE_BYTES]; if let Err(e) = pop_and_wait(&mut self.libos, self.sockqd, &mut recvbuf) { anyhow::bail!("pop and wait failed: {:?}", e); } @@ -339,26 +339,25 @@ pub fn main() -> Result<()> { let args: Vec = env::args().collect(); if args.len() >= 3 { - let libos_name: LibOSName = match LibOSName::from_env() { + let libos_name = match LibOSName::from_env() { Ok(libos_name) => libos_name.into(), Err(e) => anyhow::bail!("{:?}", e), }; - let libos: LibOS = match LibOS::new(libos_name, None) { + let libos = match LibOS::new(libos_name, None) { Ok(libos) => libos, Err(e) => anyhow::bail!("failed to initialize libos: {:?}", e), }; - let sockaddr: SocketAddr = SocketAddr::from_str(&args[2])?; + let sockaddr = SocketAddr::from_str(&args[2])?; if args[1] == "--server" { - let mut server: TcpServer = TcpServer::new(libos)?; + let mut server = TcpServer::new(libos)?; return server.run(sockaddr, NUM_PING_PONG_ROUNDS); } else if args[1] == "--client" { - let mut client: TcpClient = TcpClient::new(libos)?; + let mut client = TcpClient::new(libos)?; return client.run(sockaddr, NUM_PING_PONG_ROUNDS); } } usage(&args[0]); - Ok(()) } diff --git a/examples/rust/tcp-pktgen.rs b/examples/rust/tcp-pktgen.rs index 3f8fbb141..e996b04c5 100644 --- a/examples/rust/tcp-pktgen.rs +++ b/examples/rust/tcp-pktgen.rs @@ -10,8 +10,8 @@ //====================================================================================================================== use ::anyhow::Result; -use ::clap::{Arg, ArgMatches, Command}; -use ::demikernel::{demi_sgarray_t, runtime::types::demi_opcode_t, LibOS, LibOSName, QDesc, QToken}; +use ::clap::{Arg, Command}; +use ::demikernel::{demi_sgarray_t, runtime::types::demi_opcode_t, LibOS, LibOSName, QDesc}; use ::std::{ net::SocketAddr, slice, @@ -33,7 +33,7 @@ pub const SOCK_STREAM: i32 = libc::SOCK_STREAM; #[derive(Debug)] pub struct ProgramArguments { - remote_socket_addr: SocketAddr, + remote_addr: SocketAddr, bufsize_bytes: usize, injection_rate_microseconds: u64, } @@ -44,7 +44,7 @@ impl ProgramArguments { const DEFAULT_REMOTE_ADDR: &'static str = "127.0.0.1:23456"; pub fn new() -> Result { - let matches: ArgMatches = Command::new("tcp-pktgen") + let matches = Command::new("tcp-pktgen") .arg( Arg::new("remote") .long("remote") @@ -71,14 +71,14 @@ impl ProgramArguments { ) .get_matches(); - let mut args: ProgramArguments = ProgramArguments { - remote_socket_addr: SocketAddr::from_str(Self::DEFAULT_REMOTE_ADDR)?, + let mut args = ProgramArguments { + remote_addr: SocketAddr::from_str(Self::DEFAULT_REMOTE_ADDR)?, bufsize_bytes: Self::DEFAULT_BUFSIZE_BYTES, injection_rate_microseconds: Self::DEFAULT_INJECTION_RATE_MICROSECONDS, }; if let Some(addr) = matches.get_one::("remote") { - args.set_remote_socket_addr(addr)?; + args.set_remote_addr(addr)?; } if let Some(bufsize_bytes) = matches.get_one::("bufsize") { @@ -92,8 +92,8 @@ impl ProgramArguments { Ok(args) } - pub fn remote_socket_addr(&self) -> SocketAddr { - self.remote_socket_addr + pub fn remote_addr(&self) -> SocketAddr { + self.remote_addr } pub fn bufsize(&self) -> usize { @@ -104,13 +104,13 @@ impl ProgramArguments { self.injection_rate_microseconds } - fn set_remote_socket_addr(&mut self, addr: &str) -> Result<()> { - self.remote_socket_addr = SocketAddr::from_str(addr)?; + fn set_remote_addr(&mut self, addr: &str) -> Result<()> { + self.remote_addr = SocketAddr::from_str(addr)?; Ok(()) } fn set_bufsize(&mut self, bufsize_bytes: &str) -> Result<()> { - let bufsize_bytes: usize = bufsize_bytes.parse()?; + let bufsize_bytes = bufsize_bytes.parse()?; if bufsize_bytes > 0 { self.bufsize_bytes = bufsize_bytes; Ok(()) @@ -120,7 +120,7 @@ impl ProgramArguments { } fn set_injection_rate(&mut self, injection_rate_microseconds: &str) -> Result<()> { - let injection_rate_microseconds: u64 = injection_rate_microseconds.parse()?; + let injection_rate_microseconds = injection_rate_microseconds.parse()?; if injection_rate_microseconds > 0 { self.injection_rate_microseconds = injection_rate_microseconds; Ok(()) @@ -141,18 +141,17 @@ impl Application { const LOG_INTERVAL_SECONDS: u64 = 5; pub fn new(mut libos: LibOS, args: &ProgramArguments) -> Result { - let remote_socket_addr: SocketAddr = args.remote_socket_addr(); - let bufsize_bytes: usize = args.bufsize(); - let injection_rate_microseconds: u64 = args.injection_rate(); - - let sockqd: QDesc = match libos.socket(AF_INET, SOCK_STREAM, 0) { + let remote_addr = args.remote_addr(); + let bufsize_bytes = args.bufsize(); + let injection_rate_microseconds = args.injection_rate(); + let sockqd = match libos.socket(AF_INET, SOCK_STREAM, 0) { Ok(sockqd) => sockqd, Err(e) => { anyhow::bail!("failed to create socket: {:?}", e) }, }; - let qt: QToken = match libos.connect(sockqd, remote_socket_addr) { + let qt = match libos.connect(sockqd, remote_addr) { Ok(qt) => qt, Err(e) => { // If error, free socket. @@ -184,7 +183,7 @@ impl Application { }, } - println!("Remote Address: {:?}", remote_socket_addr); + println!("Remote Address: {:?}", remote_addr); Ok(Self { libos, @@ -195,23 +194,23 @@ impl Application { } pub fn run(&mut self) -> Result<()> { - let mut num_bytes: usize = 0; - let start_time: Instant = Instant::now(); - let mut last_push_time: Instant = Instant::now(); - let mut last_log_time: Instant = Instant::now(); + let mut num_bytes = 0; + let start_time = Instant::now(); + let mut last_push_time = Instant::now(); + let mut last_log_time = Instant::now(); loop { // Dump statistics. if last_log_time.elapsed() > Duration::from_secs(Self::LOG_INTERVAL_SECONDS) { - let elapsed_time: Duration = Instant::now() - start_time; + let elapsed_time = Instant::now() - start_time; println!("{:?} B / {:?} us", num_bytes, elapsed_time.as_micros()); last_log_time = Instant::now(); } if last_push_time.elapsed() > Duration::from_micros(self.injection_rate_microseconds) { - let sga: demi_sgarray_t = self.mksga(self.bufsize_bytes, 0x65)?; + let sga = self.mksga(self.bufsize_bytes, 0x65)?; - let qt: QToken = match self.libos.push(self.sockqd, &sga) { + let qt = match self.libos.push(self.sockqd, &sga) { Ok(qt) => qt, Err(e) => { if let Err(e) = self.libos.sgafree(sga) { @@ -251,7 +250,7 @@ impl Application { } fn mksga(&mut self, size: usize, value: u8) -> Result { - let sga: demi_sgarray_t = match self.libos.sgaalloc(size) { + let sga = match self.libos.sgaalloc(size) { Ok(sga) => sga, Err(e) => anyhow::bail!("failed to allocate scatter-gather array: {:?}", e), }; @@ -262,7 +261,7 @@ impl Application { println!("ERROR: sgafree() failed (error={:?})", e); println!("WARN: leaking sga"); } - let seglen: usize = sga.segments[0].data_len_bytes as usize; + let seglen = sga.segments[0].data_len_bytes as usize; anyhow::bail!( "failed to allocate scatter-gather array: expected size={:?} allocated size={:?}", size, @@ -271,9 +270,9 @@ impl Application { } // Fill in the array. - let ptr: *mut u8 = sga.segments[0].data_buf_ptr as *mut u8; - let len: usize = sga.segments[0].data_len_bytes as usize; - let slice: &mut [u8] = unsafe { slice::from_raw_parts_mut(ptr, len) }; + let ptr = sga.segments[0].data_buf_ptr as *mut u8; + let len = sga.segments[0].data_len_bytes as usize; + let slice = unsafe { slice::from_raw_parts_mut(ptr, len) }; slice.fill(value); Ok(sga) @@ -294,12 +293,12 @@ impl Drop for Application { } fn main() -> Result<()> { - let args: ProgramArguments = ProgramArguments::new()?; - let libos_name: LibOSName = match LibOSName::from_env() { + let args = ProgramArguments::new()?; + let libos_name = match LibOSName::from_env() { Ok(libos_name) => libos_name.into(), Err(e) => anyhow::bail!("{:?}", e), }; - let libos: LibOS = match LibOS::new(libos_name, None) { + let libos = match LibOS::new(libos_name, None) { Ok(libos) => libos, Err(e) => anyhow::bail!("failed to initialize libos: {:?}", e), }; diff --git a/examples/rust/tcp-push-pop.rs b/examples/rust/tcp-push-pop.rs index 9f63b33aa..f38c87c0a 100644 --- a/examples/rust/tcp-push-pop.rs +++ b/examples/rust/tcp-push-pop.rs @@ -9,7 +9,7 @@ // Imports //====================================================================================================================== use ::anyhow::Result; -use ::demikernel::{demi_sgarray_t, runtime::types::demi_opcode_t, LibOS, LibOSName, QDesc, QToken}; +use ::demikernel::{demi_sgarray_t, runtime::types::demi_opcode_t, LibOS, LibOSName, QDesc}; use ::std::{env, net::SocketAddr, slice, str::FromStr, time::Duration}; use log::{error, warn}; @@ -34,17 +34,17 @@ const ITERATIONS: usize = u8::MAX as usize; const TIMEOUT_SECONDS: Duration = Duration::from_secs(256); fn mksga(libos: &mut LibOS, value: u8) -> Result { - let sga: demi_sgarray_t = match libos.sgaalloc(BUF_SIZE_BYTES) { + let sga = match libos.sgaalloc(BUF_SIZE_BYTES) { Ok(sga) => sga, Err(e) => anyhow::bail!("failed to allocate scatter-gather array: {:?}", e), }; // Create pointer for filling the array. - let ptr: *mut u8 = sga.segments[0].data_buf_ptr as *mut u8; + let ptr = sga.segments[0].data_buf_ptr as *mut u8; // Ensure that allocated array has the requested size. if sga.segments[0].data_len_bytes as usize != BUF_SIZE_BYTES || ptr.is_null() { freesga(libos, sga); - let seglen: usize = sga.segments[0].data_len_bytes as usize; + let seglen = sga.segments[0].data_len_bytes as usize; anyhow::bail!( "failed to allocate scatter-gather array: expected size={:?} allocated size={:?}", BUF_SIZE_BYTES, @@ -52,7 +52,7 @@ fn mksga(libos: &mut LibOS, value: u8) -> Result { ); } - let slice: &mut [u8] = unsafe { slice::from_raw_parts_mut(ptr, BUF_SIZE_BYTES) }; + let slice = unsafe { slice::from_raw_parts_mut(ptr, BUF_SIZE_BYTES) }; // Fill in the array. for x in slice { @@ -83,7 +83,7 @@ pub struct TcpServer { impl TcpServer { pub fn new(mut libos: LibOS) -> Result { - let sockqd: QDesc = match libos.socket(AF_INET, SOCK_STREAM, 0) { + let sockqd = match libos.socket(AF_INET, SOCK_STREAM, 0) { Ok(sockqd) => sockqd, Err(e) => anyhow::bail!("failed to create socket: {:?}", e), }; @@ -98,7 +98,7 @@ impl TcpServer { fn pop_rounds(&mut self) -> Result<()> { for i in 0..ITERATIONS { // Pop data. - let qt: QToken = match self.libos.pop( + let qt = match self.libos.pop( self.accepted_sockqd.expect("should be a valid queue descriptor"), Some(BUF_SIZE_BYTES), ) { @@ -106,7 +106,7 @@ impl TcpServer { Err(e) => anyhow::bail!("pop failed: {:?}", e.cause), }; - let sga: demi_sgarray_t = match self.libos.wait(qt, Some(TIMEOUT_SECONDS)) { + let sga = match self.libos.wait(qt, Some(TIMEOUT_SECONDS)) { Ok(qr) if qr.qr_opcode == demi_opcode_t::DEMI_OPC_POP => unsafe { qr.qr_value.sga }, Ok(qr) if qr.qr_opcode == demi_opcode_t::DEMI_OPC_FAILED => anyhow::bail!("pop failed: {}", qr.qr_ret), Ok(qr) => anyhow::bail!("unexpected opcode: {:?}", qr.qr_opcode), @@ -119,13 +119,13 @@ impl TcpServer { }; // Sanity check received data. - let ptr: *mut u8 = sga.segments[0].data_buf_ptr as *mut u8; - let bytes: usize = sga.segments[0].data_len_bytes as usize; + let ptr = sga.segments[0].data_buf_ptr as *mut u8; + let bytes = sga.segments[0].data_len_bytes as usize; debug_assert_eq!(bytes, BUF_SIZE_BYTES); debug_assert!(ptr.is_aligned()); debug_assert_eq!(ptr.is_null(), false); - let slice: &mut [u8] = unsafe { slice::from_raw_parts_mut(ptr, BUF_SIZE_BYTES) }; + let slice = unsafe { slice::from_raw_parts_mut(ptr, BUF_SIZE_BYTES) }; for x in slice { demikernel::ensure_eq!(*x, i as u8); @@ -137,8 +137,8 @@ impl TcpServer { Ok(()) } - pub fn run(&mut self, local_socket_addr: SocketAddr) -> Result<()> { - if let Err(e) = self.libos.bind(self.listening_sockqd, local_socket_addr) { + pub fn run(&mut self, local_addr: SocketAddr) -> Result<()> { + if let Err(e) = self.libos.bind(self.listening_sockqd, local_addr) { anyhow::bail!("bind failed: {:?}", e.cause) }; @@ -146,7 +146,7 @@ impl TcpServer { anyhow::bail!("listen failed: {:?}", e.cause) }; - let qt: QToken = match self.libos.accept(self.listening_sockqd) { + let qt = match self.libos.accept(self.listening_sockqd) { Ok(qt) => qt, Err(e) => anyhow::bail!("accept failed: {:?}", e.cause), }; @@ -184,7 +184,7 @@ pub struct TcpClient { impl TcpClient { pub fn new(mut libos: LibOS) -> Result { - let sockqd: QDesc = match libos.socket(AF_INET, SOCK_STREAM, 0) { + let sockqd = match libos.socket(AF_INET, SOCK_STREAM, 0) { Ok(sockqd) => sockqd, Err(e) => anyhow::bail!("failed to create socket: {:?}", e.cause), }; @@ -192,8 +192,8 @@ impl TcpClient { return Ok(Self { libos, sockqd }); } - pub fn run(&mut self, remote_socket_addr: SocketAddr) -> Result<()> { - let qt: QToken = match self.libos.connect(self.sockqd, remote_socket_addr) { + pub fn run(&mut self, remote_addr: SocketAddr) -> Result<()> { + let qt = match self.libos.connect(self.sockqd, remote_addr) { Ok(qt) => qt, Err(e) => anyhow::bail!("connect failed: {:?}", e.cause), }; @@ -207,8 +207,8 @@ impl TcpClient { // Perform multiple blocking push rounds. for i in 0..ITERATIONS { - let sga: demi_sgarray_t = mksga(&mut self.libos, i as u8)?; - let qt: QToken = match self.libos.push(self.sockqd, &sga) { + let sga = mksga(&mut self.libos, i as u8)?; + let qt = match self.libos.push(self.sockqd, &sga) { Ok(qt) => qt, Err(e) => { freesga(&mut self.libos, sga); @@ -225,11 +225,11 @@ impl TcpClient { } // Perform multiple non-blocking push rounds. - let mut qts: Vec = Vec::with_capacity(ITERATIONS); - let mut sgas: Vec = Vec::with_capacity(ITERATIONS); + let mut qts = Vec::with_capacity(ITERATIONS); + let mut sgas = Vec::with_capacity(ITERATIONS); for i in 0..ITERATIONS { // Create scatter-gather array. - let sga: demi_sgarray_t = mksga(&mut self.libos, i as u8)?; + let sga = mksga(&mut self.libos, i as u8)?; // Push data. qts.push(match self.libos.push(self.sockqd, &sga) { @@ -246,9 +246,9 @@ impl TcpClient { for i in 0..ITERATIONS { match self.libos.wait_any(&qts, Some(TIMEOUT_SECONDS)) { Ok((i, qr)) if qr.qr_opcode == demi_opcode_t::DEMI_OPC_PUSH => { - let qt: QToken = qts.remove(i); + let qt = qts.remove(i); debug_assert_eq!(qt, qr.qr_qt.into()); - let sga: demi_sgarray_t = sgas.remove(i); + let sga = sgas.remove(i); self.libos.sgafree(sga)?; }, Ok((_, qr)) if qr.qr_opcode == demi_opcode_t::DEMI_OPC_FAILED => { @@ -281,21 +281,21 @@ pub fn main() -> Result<()> { let args: Vec = env::args().collect(); if args.len() >= 3 { - let libos_name: LibOSName = match LibOSName::from_env() { + let libos_name = match LibOSName::from_env() { Ok(libos_name) => libos_name.into(), Err(e) => anyhow::bail!("{:?}", e), }; - let libos: LibOS = match LibOS::new(libos_name, None) { + let libos = match LibOS::new(libos_name, None) { Ok(libos) => libos, Err(e) => anyhow::bail!("failed to initialize libos: {:?}", e.cause), }; - let sockaddr: SocketAddr = SocketAddr::from_str(&args[2])?; + let sockaddr = SocketAddr::from_str(&args[2])?; if args[1] == "--server" { - let mut server: TcpServer = TcpServer::new(libos)?; + let mut server = TcpServer::new(libos)?; return server.run(sockaddr); } else if args[1] == "--client" { - let mut client: TcpClient = TcpClient::new(libos)?; + let mut client = TcpClient::new(libos)?; return client.run(sockaddr); } } diff --git a/examples/rust/udp-dump.rs b/examples/rust/udp-dump.rs index fd1b4a5ca..99eb57baf 100644 --- a/examples/rust/udp-dump.rs +++ b/examples/rust/udp-dump.rs @@ -8,8 +8,8 @@ //====================================================================================================================== use ::anyhow::Result; -use ::clap::{Arg, ArgMatches, Command}; -use ::demikernel::{demi_sgarray_t, runtime::types::demi_opcode_t, LibOS, LibOSName, QDesc, QToken}; +use ::clap::{Arg, Command}; +use ::demikernel::{runtime::types::demi_opcode_t, LibOS, LibOSName, QDesc}; use ::std::{ net::SocketAddr, str::FromStr, @@ -30,14 +30,14 @@ pub const SOCK_DGRAM: i32 = libc::SOCK_DGRAM; #[derive(Debug)] struct ProgramArguments { - local_socket_addr: SocketAddr, + local_addr: SocketAddr, } impl ProgramArguments { const DEFAULT_LOCAL_IPV4_ADDR: &'static str = "127.0.0.1:12345"; pub fn new() -> Result { - let matches: ArgMatches = Command::new("udp-dump") + let matches = Command::new("udp-dump") .arg( Arg::new("local") .long("local") @@ -48,23 +48,23 @@ impl ProgramArguments { ) .get_matches(); - let mut args: ProgramArguments = ProgramArguments { - local_socket_addr: SocketAddr::from_str(Self::DEFAULT_LOCAL_IPV4_ADDR)?, + let mut args = ProgramArguments { + local_addr: SocketAddr::from_str(Self::DEFAULT_LOCAL_IPV4_ADDR)?, }; if let Some(addr) = matches.get_one::("local") { - args.set_local_socket_addr(addr)?; + args.set_local_addr(addr)?; } Ok(args) } - pub fn local_socket_addr(&self) -> SocketAddr { - self.local_socket_addr + pub fn local_addr(&self) -> SocketAddr { + self.local_addr } - fn set_local_socket_addr(&mut self, addr: &str) -> Result<()> { - self.local_socket_addr = SocketAddr::from_str(addr)?; + fn set_local_addr(&mut self, addr: &str) -> Result<()> { + self.local_addr = SocketAddr::from_str(addr)?; Ok(()) } } @@ -78,13 +78,13 @@ impl Application { const LOG_INTERVAL_SECONDS: u64 = 5; pub fn new(mut libos: LibOS, args: &ProgramArguments) -> Result { - let local_socket_addr: SocketAddr = args.local_socket_addr(); - let sockqd: QDesc = match libos.socket(AF_INET, SOCK_DGRAM, 0) { + let addr = args.local_addr(); + let sockqd = match libos.socket(AF_INET, SOCK_DGRAM, 0) { Ok(sockqd) => sockqd, Err(e) => anyhow::bail!("failed to create socket: {:?}", e), }; - match libos.bind(sockqd, local_socket_addr) { + match libos.bind(sockqd, addr) { Ok(()) => (), Err(e) => { // If error, close socket. @@ -96,32 +96,32 @@ impl Application { }, }; - println!("Local Address: {:?}", local_socket_addr); + println!("Local Address: {:?}", addr); Ok(Self { libos, sockqd }) } pub fn run(&mut self) -> Result<()> { - let start_time: Instant = Instant::now(); - let mut num_bytes: usize = 0; - let mut last_log_time: Instant = Instant::now(); + let start_time = Instant::now(); + let mut num_bytes = 0; + let mut last_log_time = Instant::now(); loop { // Dump statistics. if last_log_time.elapsed() > Duration::from_secs(Self::LOG_INTERVAL_SECONDS) { - let elapsed_time: Duration = Instant::now() - start_time; + let elapsed_time = Instant::now() - start_time; println!("{:?} B / {:?} us", num_bytes, elapsed_time.as_micros()); last_log_time = Instant::now(); } // Drain packets. - let qt: QToken = match self.libos.pop(self.sockqd, None) { + let qt = match self.libos.pop(self.sockqd, None) { Ok(qt) => qt, Err(e) => anyhow::bail!("failed to pop data from socket: {:?}", e), }; match self.libos.wait(qt, None) { Ok(qr) if qr.qr_opcode == demi_opcode_t::DEMI_OPC_POP => { - let sga: demi_sgarray_t = unsafe { qr.qr_value.sga }; + let sga = unsafe { qr.qr_value.sga }; num_bytes += sga.segments[0].data_len_bytes as usize; if let Err(e) = self.libos.sgafree(sga) { println!("ERROR: sgafree() failed (error={:?})", e); @@ -149,12 +149,12 @@ impl Drop for Application { } fn main() -> Result<()> { - let args: ProgramArguments = ProgramArguments::new()?; - let libos_name: LibOSName = match LibOSName::from_env() { + let args = ProgramArguments::new()?; + let libos_name = match LibOSName::from_env() { Ok(libos_name) => libos_name.into(), Err(e) => panic!("{:?}", e), }; - let libos: LibOS = match LibOS::new(libos_name, None) { + let libos = match LibOS::new(libos_name, None) { Ok(libos) => libos, Err(e) => panic!("failed to initialize libos: {:?}", e), }; diff --git a/examples/rust/udp-echo.rs b/examples/rust/udp-echo.rs index 4a4a8b62c..d8923b487 100644 --- a/examples/rust/udp-echo.rs +++ b/examples/rust/udp-echo.rs @@ -8,8 +8,8 @@ //====================================================================================================================== use ::anyhow::Result; -use ::clap::{Arg, ArgMatches, Command}; -use ::demikernel::{demi_sgarray_t, runtime::types::demi_opcode_t, LibOS, LibOSName, QDesc, QToken}; +use ::clap::{Arg, Command}; +use ::demikernel::{runtime::types::demi_opcode_t, LibOS, LibOSName, QDesc}; #[cfg(target_os = "linux")] use ::std::mem; use ::std::{ @@ -44,14 +44,14 @@ const TIMEOUT_SECONDS: Duration = Duration::from_secs(256); #[derive(Debug)] pub struct ProgramArguments { - local_socket_addr: SocketAddr, + local_addr: SocketAddr, } impl ProgramArguments { const DEFAULT_LOCAL_IPV4_ADDR: &'static str = "127.0.0.1:12345"; pub fn new() -> Result { - let matches: ArgMatches = Command::new("udp-echo") + let matches = Command::new("udp-echo") .arg( Arg::new("local") .long("local") @@ -62,23 +62,23 @@ impl ProgramArguments { ) .get_matches(); - let mut args: ProgramArguments = ProgramArguments { - local_socket_addr: SocketAddr::from_str(Self::DEFAULT_LOCAL_IPV4_ADDR)?, + let mut args = ProgramArguments { + local_addr: SocketAddr::from_str(Self::DEFAULT_LOCAL_IPV4_ADDR)?, }; if let Some(addr) = matches.get_one::("local") { - args.set_local_socket_addr(addr)?; + args.set_local_addr(addr)?; } Ok(args) } - pub fn local_socket_addr(&self) -> SocketAddr { - self.local_socket_addr + pub fn local_addr(&self) -> SocketAddr { + self.local_addr } - fn set_local_socket_addr(&mut self, addr: &str) -> Result<()> { - self.local_socket_addr = SocketAddr::from_str(addr)?; + fn set_local_addr(&mut self, addr: &str) -> Result<()> { + self.local_addr = SocketAddr::from_str(addr)?; Ok(()) } } @@ -92,13 +92,13 @@ impl Application { const LOG_INTERVAL_SECONDS: u64 = 5; pub fn new(mut libos: LibOS, args: &ProgramArguments) -> Result { - let local_socket_addr: SocketAddr = args.local_socket_addr(); - let sockqd: QDesc = match libos.socket(AF_INET_VALUE, SOCK_DGRAM, 0) { + let local_addr = args.local_addr(); + let sockqd = match libos.socket(AF_INET_VALUE, SOCK_DGRAM, 0) { Ok(sockqd) => sockqd, Err(e) => anyhow::bail!("failed to create socket: {:?}", e), }; - match libos.bind(sockqd, local_socket_addr) { + match libos.bind(sockqd, local_addr) { Ok(()) => (), Err(e) => { // If error, close socket. @@ -110,19 +110,19 @@ impl Application { }, }; - println!("Local Address: {:?}", local_socket_addr); + println!("Local Address: {:?}", local_addr); Ok(Self { libos, sockqd }) } pub fn run(&mut self) -> Result<()> { - let mut num_bytes: usize = 0; - let start_time: Instant = Instant::now(); - let mut qtokens: Vec = Vec::new(); - let mut last_log_time: Instant = Instant::now(); + let mut num_bytes = 0; + let start_time = Instant::now(); + let mut qtokens = Vec::new(); + let mut last_log_time = Instant::now(); // Pop first packet. - let qt: QToken = match self.libos.pop(self.sockqd, None) { + let qt = match self.libos.pop(self.sockqd, None) { Ok(qt) => qt, Err(e) => anyhow::bail!("failed to pop data from socket: {:?}", e), }; @@ -131,7 +131,7 @@ impl Application { loop { // Dump statistics. if last_log_time.elapsed() > Duration::from_secs(Self::LOG_INTERVAL_SECONDS) { - let elapsed: Duration = Instant::now() - start_time; + let elapsed = Instant::now() - start_time; println!("{:?} B / {:?} us", num_bytes, elapsed.as_micros()); last_log_time = Instant::now(); } @@ -146,23 +146,22 @@ impl Application { match qr.qr_opcode { // Pop completed. demi_opcode_t::DEMI_OPC_POP => { - let sockqd: QDesc = qr.qr_qd.into(); - let sga: demi_sgarray_t = unsafe { qr.qr_value.sga }; - let saddr: SocketAddr = - match Self::sockaddr_to_socketaddrv4(&unsafe { qr.qr_value.sga.sockaddr_src }) { - Ok(saddr) => SocketAddr::from(saddr), - Err(e) => { - // If error, free scatter-gather array. - if let Err(e) = self.libos.sgafree(sga) { - println!("ERROR: sgafree() failed (error={:?})", e); - println!("WARN: leaking sga"); - }; - anyhow::bail!("could not parse sockaddr: {}", e) - }, - }; + let sockqd = qr.qr_qd.into(); + let sga = unsafe { qr.qr_value.sga }; + let saddr = match Self::sockaddr_to_socketaddrv4(&unsafe { qr.qr_value.sga.sockaddr_src }) { + Ok(saddr) => SocketAddr::from(saddr), + Err(e) => { + // If error, free scatter-gather array. + if let Err(e) = self.libos.sgafree(sga) { + println!("ERROR: sgafree() failed (error={:?})", e); + println!("WARN: leaking sga"); + }; + anyhow::bail!("could not parse sockaddr: {}", e) + }, + }; num_bytes += sga.segments[0].data_len_bytes as usize; // Push packet back. - let qt: QToken = match self.libos.pushto(sockqd, &sga, saddr) { + let qt = match self.libos.pushto(sockqd, &sga, saddr) { Ok(qt) => qt, Err(e) => { // If error, free scatter-gather array. @@ -182,8 +181,8 @@ impl Application { // Push completed. demi_opcode_t::DEMI_OPC_PUSH => { // Pop another packet. - let sockqd: QDesc = qr.qr_qd.into(); - let qt: QToken = match self.libos.pop(sockqd, None) { + let sockqd = qr.qr_qd.into(); + let qt = match self.libos.pop(sockqd, None) { Ok(qt) => qt, Err(e) => anyhow::bail!("failed to pop data from socket: {:?}", e), }; @@ -198,13 +197,12 @@ impl Application { #[cfg(target_os = "linux")] pub fn sockaddr_to_socketaddrv4(saddr: *const libc::sockaddr) -> Result { // TODO: Change the logic below and rename this function once we support V6 addresses as well. - let sin: libc::sockaddr_in = - unsafe { *mem::transmute::<*const libc::sockaddr, *const libc::sockaddr_in>(saddr) }; + let sin = unsafe { *mem::transmute::<*const libc::sockaddr, *const libc::sockaddr_in>(saddr) }; if sin.sin_family != libc::AF_INET as u16 { anyhow::bail!("communication domain not supported"); }; - let addr: Ipv4Addr = Ipv4Addr::from(u32::from_be(sin.sin_addr.s_addr)); - let port: u16 = u16::from_be(sin.sin_port); + let addr = Ipv4Addr::from(u32::from_be(sin.sin_addr.s_addr)); + let port = u16::from_be(sin.sin_port); Ok(SocketAddrV4::new(addr, port)) } @@ -212,12 +210,12 @@ impl Application { pub fn sockaddr_to_socketaddrv4(saddr: *const libc::sockaddr) -> Result { // TODO: Change the logic below and rename this function once we support V6 addresses as well. - let sin: SOCKADDR_IN = unsafe { *(saddr as *const SOCKADDR_IN) }; + let sin = unsafe { *(saddr as *const SOCKADDR_IN) }; if sin.sin_family != AF_INET { anyhow::bail!("communication domain not supported"); }; - let addr: Ipv4Addr = Ipv4Addr::from(u32::from_be(unsafe { sin.sin_addr.S_un.S_addr })); - let port: u16 = u16::from_be(sin.sin_port); + let addr = Ipv4Addr::from(u32::from_be(unsafe { sin.sin_addr.S_un.S_addr })); + let port = u16::from_be(sin.sin_port); Ok(SocketAddrV4::new(addr, port)) } } @@ -236,12 +234,12 @@ impl Drop for Application { } fn main() -> Result<()> { - let args: ProgramArguments = ProgramArguments::new()?; - let libos_name: LibOSName = match LibOSName::from_env() { + let args = ProgramArguments::new()?; + let libos_name = match LibOSName::from_env() { Ok(libos_name) => libos_name.into(), Err(e) => panic!("{:?}", e), }; - let libos: LibOS = match LibOS::new(libos_name, None) { + let libos = match LibOS::new(libos_name, None) { Ok(libos) => libos, Err(e) => panic!("failed to initialize libos: {:?}", e), }; diff --git a/examples/rust/udp-ping-pong.rs b/examples/rust/udp-ping-pong.rs index 6f09b4cbe..218ed93a2 100644 --- a/examples/rust/udp-ping-pong.rs +++ b/examples/rust/udp-ping-pong.rs @@ -6,7 +6,7 @@ //====================================================================================================================== use ::anyhow::Result; -use ::demikernel::{demi_sgarray_t, runtime::types::demi_opcode_t, LibOS, LibOSName, QDesc, QToken}; +use ::demikernel::{demi_sgarray_t, runtime::types::demi_opcode_t, LibOS, LibOSName, QDesc}; use ::std::{env, net::SocketAddr, slice, str::FromStr, time::Duration}; #[cfg(target_os = "windows")] @@ -32,7 +32,7 @@ const TIMEOUT_SECONDS: Duration = Duration::from_secs(60); const RETRY_TIMEOUT_SECONDS: Duration = Duration::from_secs(1); fn mksga(libos: &mut LibOS, size: usize, value: u8) -> Result { - let sga: demi_sgarray_t = match libos.sgaalloc(size) { + let sga = match libos.sgaalloc(size) { Ok(sga) => sga, Err(e) => anyhow::bail!("failed to allocate scatter-gather array: {:?}", e), }; @@ -40,7 +40,7 @@ fn mksga(libos: &mut LibOS, size: usize, value: u8) -> Result { // Ensure that allocated array has the requested size. if sga.segments[0].data_len_bytes as usize != size { freesga(libos, sga); - let seglen: usize = sga.segments[0].data_len_bytes as usize; + let seglen = sga.segments[0].data_len_bytes as usize; anyhow::bail!( "failed to allocate scatter-gather array: expected size={:?} allocated size={:?}", size, @@ -48,9 +48,9 @@ fn mksga(libos: &mut LibOS, size: usize, value: u8) -> Result { ); } // Fill in the array. - let ptr: *mut u8 = sga.segments[0].data_buf_ptr as *mut u8; - let len: usize = sga.segments[0].data_len_bytes as usize; - let slice: &mut [u8] = unsafe { slice::from_raw_parts_mut(ptr, len) }; + let ptr = sga.segments[0].data_buf_ptr as *mut u8; + let len = sga.segments[0].data_len_bytes as usize; + let slice = unsafe { slice::from_raw_parts_mut(ptr, len) }; slice.fill(value); Ok(sga) @@ -70,8 +70,8 @@ fn close(libos: &mut LibOS, sockqd: QDesc) { } } -fn issue_pushto(libos: &mut LibOS, sockqd: QDesc, remote_socket_addr: SocketAddr, sga: &demi_sgarray_t) -> Result<()> { - let qt: QToken = match libos.pushto(sockqd, sga, remote_socket_addr) { +fn issue_pushto(libos: &mut LibOS, sockqd: QDesc, remote_addr: SocketAddr, sga: &demi_sgarray_t) -> Result<()> { + let qt = match libos.pushto(sockqd, sga, remote_addr) { Ok(qt) => qt, Err(e) => anyhow::bail!("push failed: {:?}", e), }; @@ -91,26 +91,26 @@ pub struct UdpServer { impl UdpServer { pub fn new(mut libos: LibOS) -> Result { - let sockqd: QDesc = match libos.socket(AF_INET, SOCK_DGRAM, 0) { + let sockqd = match libos.socket(AF_INET, SOCK_DGRAM, 0) { Ok(sockqd) => sockqd, Err(e) => anyhow::bail!("failed to create socket: {:?}", e), }; return Ok(Self { libos, sockqd }); } - pub fn run(&mut self, local_socket_addr: SocketAddr, remote_socket_addr: SocketAddr, fill_char: u8) -> Result<()> { - if let Err(e) = self.libos.bind(self.sockqd, local_socket_addr) { + pub fn run(&mut self, local_addr: SocketAddr, remote_addr: SocketAddr, fill_char: u8) -> Result<()> { + if let Err(e) = self.libos.bind(self.sockqd, local_addr) { anyhow::bail!("bind failed: {:?}", e) }; - let mut received_responses: usize = 0; + let mut received_responses = 0; loop { - let qt: QToken = match self.libos.pop(self.sockqd, None) { + let qt = match self.libos.pop(self.sockqd, None) { Ok(qt) => qt, Err(e) => anyhow::bail!("pop failed: {:?}", e), }; - let sga: demi_sgarray_t = match self.libos.wait(qt, Some(TIMEOUT_SECONDS)) { + let sga = match self.libos.wait(qt, Some(TIMEOUT_SECONDS)) { Ok(qr) if qr.qr_opcode == demi_opcode_t::DEMI_OPC_POP => unsafe { qr.qr_value.sga }, Ok(_) => anyhow::bail!("unexpected result"), // If we haven't received a message in the last 60 seconds, we can assume that the client is done. @@ -119,15 +119,15 @@ impl UdpServer { }; // Sanity check received data. - let ptr: *mut u8 = sga.segments[0].data_buf_ptr as *mut u8; - let len: usize = sga.segments[0].data_len_bytes as usize; - let slice: &mut [u8] = unsafe { slice::from_raw_parts_mut(ptr, len) }; + let ptr = sga.segments[0].data_buf_ptr as *mut u8; + let len = sga.segments[0].data_len_bytes as usize; + let slice = unsafe { slice::from_raw_parts_mut(ptr, len) }; for x in slice { if *x != fill_char { anyhow::bail!("fill check failed: expected={:?} received={:?}", fill_char, *x); } } - issue_pushto(&mut self.libos, self.sockqd, remote_socket_addr, &sga)?; + issue_pushto(&mut self.libos, self.sockqd, remote_addr, &sga)?; self.libos.sgafree(sga)?; received_responses += 1; println!("pong {:?}", received_responses); @@ -150,7 +150,7 @@ pub struct UdpClient { impl UdpClient { pub fn new(mut libos: LibOS) -> Result { - let sockqd: QDesc = match libos.socket(AF_INET, SOCK_DGRAM, 0) { + let sockqd = match libos.socket(AF_INET, SOCK_DGRAM, 0) { Ok(sockqd) => sockqd, Err(e) => anyhow::bail!("failed to create socket: {:?}", e), }; @@ -160,25 +160,25 @@ impl UdpClient { pub fn run( &mut self, - local_socket_addr: SocketAddr, - remote_socket_addr: SocketAddr, + local_addr: SocketAddr, + remote_addr: SocketAddr, fill_char: u8, bufsize_bytes: usize, num_pings: usize, ) -> Result<()> { - if let Err(e) = self.libos.bind(self.sockqd, local_socket_addr) { + if let Err(e) = self.libos.bind(self.sockqd, local_addr) { anyhow::bail!("bind failed: {:?}", e) }; - let mut received_responses: usize = 0; + let mut received_responses = 0; while received_responses < num_pings { - let sga: demi_sgarray_t = mksga(&mut self.libos, bufsize_bytes, fill_char)?; + let sga = mksga(&mut self.libos, bufsize_bytes, fill_char)?; // Send packet and wait for response. - let returned_sga: demi_sgarray_t = loop { - issue_pushto(&mut self.libos, self.sockqd, remote_socket_addr, &sga)?; + let returned_sga = loop { + issue_pushto(&mut self.libos, self.sockqd, remote_addr, &sga)?; // Wait for the response. - let qt: QToken = match self.libos.pop(self.sockqd, None) { + let qt = match self.libos.pop(self.sockqd, None) { Ok(qt) => qt, Err(e) => anyhow::bail!("pop failed: {:?}", e), }; @@ -197,9 +197,9 @@ impl UdpClient { // Free the sent sga. self.libos.sgafree(sga)?; // Sanity check received data. - let ptr: *mut u8 = returned_sga.segments[0].data_buf_ptr as *mut u8; - let len: usize = returned_sga.segments[0].data_len_bytes as usize; - let slice: &mut [u8] = unsafe { slice::from_raw_parts_mut(ptr, len) }; + let ptr = returned_sga.segments[0].data_buf_ptr as *mut u8; + let len = returned_sga.segments[0].data_len_bytes as usize; + let slice = unsafe { slice::from_raw_parts_mut(ptr, len) }; for x in slice { if *x != fill_char { anyhow::bail!("fill check failed: expected={:?} received={:?}", fill_char, *x); @@ -232,30 +232,24 @@ pub fn main() -> Result<()> { let args: Vec = env::args().collect(); if args.len() >= 4 { - let libos_name: LibOSName = match LibOSName::from_env() { + let libos_name = match LibOSName::from_env() { Ok(libos_name) => libos_name.into(), Err(e) => anyhow::bail!("{:?}", e), }; - let libos: LibOS = match LibOS::new(libos_name, None) { + let libos = match LibOS::new(libos_name, None) { Ok(libos) => libos, Err(e) => anyhow::bail!("failed to initialize libos: {:?}", e), }; - let local_socket_addr: SocketAddr = SocketAddr::from_str(&args[2])?; - let remote_socket_addr: SocketAddr = SocketAddr::from_str(&args[3])?; + let local_addr = SocketAddr::from_str(&args[2])?; + let remote_addr = SocketAddr::from_str(&args[3])?; if args[1] == "--server" { - let mut server: UdpServer = UdpServer::new(libos)?; - return server.run(local_socket_addr, remote_socket_addr, FILL_CHAR); + let mut server = UdpServer::new(libos)?; + return server.run(local_addr, remote_addr, FILL_CHAR); } else if args[1] == "--client" { - let mut client: UdpClient = UdpClient::new(libos)?; - return client.run( - local_socket_addr, - remote_socket_addr, - FILL_CHAR, - BUFSIZE_BYTES, - NUM_PINGS, - ); + let mut client = UdpClient::new(libos)?; + return client.run(local_addr, remote_addr, FILL_CHAR, BUFSIZE_BYTES, NUM_PINGS); } } diff --git a/examples/rust/udp-pktgen.rs b/examples/rust/udp-pktgen.rs index a5d1b4562..d4af61b62 100644 --- a/examples/rust/udp-pktgen.rs +++ b/examples/rust/udp-pktgen.rs @@ -8,8 +8,8 @@ //====================================================================================================================== use ::anyhow::Result; -use ::clap::{Arg, ArgMatches, Command}; -use ::demikernel::{demi_sgarray_t, runtime::types::demi_opcode_t, LibOS, LibOSName, QDesc, QToken}; +use ::clap::{Arg, Command}; +use ::demikernel::{demi_sgarray_t, runtime::types::demi_opcode_t, LibOS, LibOSName, QDesc}; use ::std::{ net::SocketAddr, slice, @@ -31,8 +31,8 @@ pub const SOCK_DGRAM: i32 = libc::SOCK_DGRAM; #[derive(Debug)] pub struct ProgramArguments { - local_socket_addr: SocketAddr, - remote_socket_addr: SocketAddr, + local_addr: SocketAddr, + remote_addr: SocketAddr, bufsize_bytes: usize, injection_rate_microseconds: u64, } @@ -44,7 +44,7 @@ impl ProgramArguments { const DEFAULT_REMOTE_ADDR: &'static str = "127.0.0.1:23456"; pub fn new() -> Result { - let matches: ArgMatches = Command::new("udp-pktgen") + let matches = Command::new("udp-pktgen") .arg( Arg::new("local") .long("local") @@ -79,19 +79,19 @@ impl ProgramArguments { ) .get_matches(); - let mut args: ProgramArguments = ProgramArguments { - local_socket_addr: SocketAddr::from_str(Self::DEFAULT_LOCAL_ADDR)?, - remote_socket_addr: SocketAddr::from_str(Self::DEFAULT_REMOTE_ADDR)?, + let mut args = ProgramArguments { + local_addr: SocketAddr::from_str(Self::DEFAULT_LOCAL_ADDR)?, + remote_addr: SocketAddr::from_str(Self::DEFAULT_REMOTE_ADDR)?, bufsize_bytes: Self::DEFAULT_BUFSIZE_BYTES, injection_rate_microseconds: Self::DEFAULT_INJECTION_RATE_MICROSECONDS, }; if let Some(addr) = matches.get_one::("local") { - args.set_local_socket_addr(addr)?; + args.set_local_addr(addr)?; } if let Some(addr) = matches.get_one::("remote") { - args.set_remote_socket_addr(addr)?; + args.set_remote_addr(addr)?; } if let Some(bufsize_bytes) = matches.get_one::("bufsize") { @@ -105,12 +105,12 @@ impl ProgramArguments { Ok(args) } - pub fn local_socket_addr(&self) -> SocketAddr { - self.local_socket_addr + pub fn local_addr(&self) -> SocketAddr { + self.local_addr } - pub fn remote_socket_addr(&self) -> SocketAddr { - self.remote_socket_addr + pub fn remote_addr(&self) -> SocketAddr { + self.remote_addr } pub fn bufsize(&self) -> usize { @@ -121,18 +121,18 @@ impl ProgramArguments { self.injection_rate_microseconds } - fn set_local_socket_addr(&mut self, addr: &str) -> Result<()> { - self.local_socket_addr = SocketAddr::from_str(addr)?; + fn set_local_addr(&mut self, addr: &str) -> Result<()> { + self.local_addr = SocketAddr::from_str(addr)?; Ok(()) } - fn set_remote_socket_addr(&mut self, addr: &str) -> Result<()> { - self.remote_socket_addr = SocketAddr::from_str(addr)?; + fn set_remote_addr(&mut self, addr: &str) -> Result<()> { + self.remote_addr = SocketAddr::from_str(addr)?; Ok(()) } fn set_bufsize(&mut self, bufsize_str: &str) -> Result<()> { - let bufsize: usize = bufsize_str.parse()?; + let bufsize = bufsize_str.parse()?; if bufsize > 0 { self.bufsize_bytes = bufsize; Ok(()) @@ -142,7 +142,7 @@ impl ProgramArguments { } fn set_injection_rate(&mut self, injection_rate_microseconds: &str) -> Result<()> { - let injection_rate_microseconds: u64 = injection_rate_microseconds.parse()?; + let injection_rate_microseconds = injection_rate_microseconds.parse()?; if injection_rate_microseconds > 0 { self.injection_rate_microseconds = injection_rate_microseconds; Ok(()) @@ -155,7 +155,7 @@ impl ProgramArguments { struct Application { libos: LibOS, sockqd: QDesc, - remote_socket_addr: SocketAddr, + remote_addr: SocketAddr, bufsize_bytes: usize, injection_rate_microseconds: u64, } @@ -164,17 +164,17 @@ impl Application { const LOG_INTERVAL_SECONDS: u64 = 5; pub fn new(mut libos: LibOS, args: &ProgramArguments) -> Result { - let local_socket_addr: SocketAddr = args.local_socket_addr(); - let remote_socket_addr: SocketAddr = args.remote_socket_addr(); - let bufsize_byes: usize = args.bufsize(); - let injection_rate_microseconds: u64 = args.injection_rate(); + let local_addr = args.local_addr(); + let remote_addr = args.remote_addr(); + let bufsize_bytes = args.bufsize(); + let injection_rate_microseconds = args.injection_rate(); - let sockqd: QDesc = match libos.socket(AF_INET, SOCK_DGRAM, 1) { + let sockqd = match libos.socket(AF_INET, SOCK_DGRAM, 1) { Ok(sockqd) => sockqd, Err(e) => anyhow::bail!("failed to create socket: {:?}", e), }; - match libos.bind(sockqd, local_socket_addr) { + match libos.bind(sockqd, local_addr) { Ok(()) => (), Err(e) => { // If error, close socket. @@ -186,37 +186,37 @@ impl Application { }, }; - println!("Local Address: {:?}", local_socket_addr); - println!("Remote Address: {:?}", remote_socket_addr); + println!("Local Address: {:?}", local_addr); + println!("Remote Address: {:?}", remote_addr); Ok(Self { libos, sockqd, - remote_socket_addr, - bufsize_bytes: bufsize_byes, + remote_addr, + bufsize_bytes, injection_rate_microseconds, }) } pub fn run(&mut self) -> Result<()> { - let mut num_bytes: usize = 0; - let start_time: Instant = Instant::now(); - let mut last_push_time: Instant = Instant::now(); - let mut last_log_time: Instant = Instant::now(); + let mut num_bytes = 0; + let start_time = Instant::now(); + let mut last_push_time = Instant::now(); + let mut last_log_time = Instant::now(); loop { // Dump statistics. if last_log_time.elapsed() > Duration::from_secs(Self::LOG_INTERVAL_SECONDS) { - let elapsed_time: Duration = Instant::now() - start_time; + let elapsed_time = Instant::now() - start_time; println!("{:?} B / {:?} us", num_bytes, elapsed_time.as_micros()); last_log_time = Instant::now(); } // Push packet. if last_push_time.elapsed() > Duration::from_nanos(self.injection_rate_microseconds) { - let sga: demi_sgarray_t = self.mksga(self.bufsize_bytes, 0x65)?; + let sga = self.mksga(self.bufsize_bytes, 0x65)?; - let qt: QToken = match self.libos.pushto(self.sockqd, &sga, self.remote_socket_addr) { + let qt = match self.libos.pushto(self.sockqd, &sga, self.remote_addr) { Ok(qt) => qt, Err(e) => { // If error, free scatter-gather array. @@ -260,7 +260,7 @@ impl Application { } fn mksga(&mut self, size: usize, value: u8) -> Result { - let sga: demi_sgarray_t = match self.libos.sgaalloc(size) { + let sga = match self.libos.sgaalloc(size) { Ok(sga) => sga, Err(e) => anyhow::bail!("failed to allocate scatter-gather array: {:?}", e), }; @@ -271,7 +271,7 @@ impl Application { println!("ERROR: sgafree() failed (error={:?})", e); println!("WARN: leaking sga"); }; - let seglen: usize = sga.segments[0].data_len_bytes as usize; + let seglen = sga.segments[0].data_len_bytes as usize; anyhow::bail!( "failed to allocate scatter-gather array: expected size={:?} allocated size={:?}", size, @@ -279,9 +279,9 @@ impl Application { ); } // Fill in the array. - let ptr: *mut u8 = sga.segments[0].data_buf_ptr as *mut u8; - let len: usize = sga.segments[0].data_len_bytes as usize; - let slice: &mut [u8] = unsafe { slice::from_raw_parts_mut(ptr, len) }; + let ptr = sga.segments[0].data_buf_ptr as *mut u8; + let len = sga.segments[0].data_len_bytes as usize; + let slice = unsafe { slice::from_raw_parts_mut(ptr, len) }; slice.fill(value); Ok(sga) @@ -302,12 +302,12 @@ impl Drop for Application { } fn main() -> Result<()> { - let args: ProgramArguments = ProgramArguments::new()?; - let libos_name: LibOSName = match LibOSName::from_env() { + let args = ProgramArguments::new()?; + let libos_name = match LibOSName::from_env() { Ok(libos_name) => libos_name.into(), Err(e) => panic!("{:?}", e), }; - let libos: LibOS = match LibOS::new(libos_name, None) { + let libos = match LibOS::new(libos_name, None) { Ok(libos) => libos, Err(e) => panic!("failed to initialize libos: {:?}", e), }; diff --git a/examples/rust/udp-push-pop.rs b/examples/rust/udp-push-pop.rs index 4c6e069dd..38a8d55d1 100644 --- a/examples/rust/udp-push-pop.rs +++ b/examples/rust/udp-push-pop.rs @@ -6,7 +6,7 @@ //====================================================================================================================== use ::anyhow::Result; -use ::demikernel::{demi_sgarray_t, runtime::types::demi_opcode_t, LibOS, LibOSName, QDesc, QToken}; +use ::demikernel::{demi_sgarray_t, runtime::types::demi_opcode_t, LibOS, LibOSName, QDesc}; use ::std::{env, net::SocketAddr, slice, str::FromStr, time::Duration}; use log::{error, warn}; @@ -32,7 +32,7 @@ const NUM_SENDS: usize = 1024; const TIMEOUT_SECONDS: Duration = Duration::from_secs(256); fn mksga(libos: &mut LibOS, size: usize, value: u8) -> Result { - let sga: demi_sgarray_t = match libos.sgaalloc(size) { + let sga = match libos.sgaalloc(size) { Ok(sga) => sga, Err(e) => panic!("failed to allocate scatter-gather array: {:?}", e), }; @@ -40,7 +40,7 @@ fn mksga(libos: &mut LibOS, size: usize, value: u8) -> Result { // Ensure that allocated array has the requested size. if sga.segments[0].data_len_bytes as usize != size { freesga(libos, sga); - let seglen: usize = sga.segments[0].data_len_bytes as usize; + let seglen = sga.segments[0].data_len_bytes as usize; anyhow::bail!( "failed to allocate scatter-gather array: expected size={:?} allocated size={:?}", size, @@ -49,9 +49,9 @@ fn mksga(libos: &mut LibOS, size: usize, value: u8) -> Result { } // Fill in the array. - let ptr: *mut u8 = sga.segments[0].data_buf_ptr as *mut u8; - let len: usize = sga.segments[0].data_len_bytes as usize; - let slice: &mut [u8] = unsafe { slice::from_raw_parts_mut(ptr, len) }; + let ptr = sga.segments[0].data_buf_ptr as *mut u8; + let len = sga.segments[0].data_len_bytes as usize; + let slice = unsafe { slice::from_raw_parts_mut(ptr, len) }; slice.fill(value); Ok(sga) @@ -79,7 +79,7 @@ pub struct UdpServer { impl UdpServer { pub fn new(mut libos: LibOS) -> Result { - let sockqd: QDesc = match libos.socket(AF_INET, SOCK_DGRAM, 0) { + let sockqd = match libos.socket(AF_INET, SOCK_DGRAM, 0) { Ok(sockqd) => sockqd, Err(e) => anyhow::bail!("failed to create socket: {:?}", e), }; @@ -92,7 +92,7 @@ impl UdpServer { fn run(&mut self, local: SocketAddr, fill_char: u8, num_sends: usize) -> Result<()> { // Wait for half the packets that we sent. We chose this number randomly to account for lost packets. - let num_receives: usize = num_sends / 2; + let num_receives = num_sends / 2; match self.libos.bind(self.sockqd, local) { Ok(()) => (), @@ -100,7 +100,7 @@ impl UdpServer { }; for i in 0..num_receives { - let qt: QToken = match self.libos.pop(self.sockqd, None) { + let qt = match self.libos.pop(self.sockqd, None) { Ok(qt) => qt, Err(e) => anyhow::bail!("pop failed: {:?}", e), }; @@ -112,9 +112,9 @@ impl UdpServer { if let Some(sga) = self.sga { // Sanity check received data. - let ptr: *mut u8 = sga.segments[0].data_buf_ptr as *mut u8; - let len: usize = sga.segments[0].data_len_bytes as usize; - let slice: &mut [u8] = unsafe { slice::from_raw_parts_mut(ptr, len) }; + let ptr = sga.segments[0].data_buf_ptr as *mut u8; + let len = sga.segments[0].data_len_bytes as usize; + let slice = unsafe { slice::from_raw_parts_mut(ptr, len) }; for x in slice { demikernel::ensure_eq!(*x, fill_char); } @@ -150,7 +150,7 @@ pub struct UdpClient { impl UdpClient { pub fn new(mut libos: LibOS) -> Result { - let sockqd: QDesc = match libos.socket(AF_INET, SOCK_DGRAM, 0) { + let sockqd = match libos.socket(AF_INET, SOCK_DGRAM, 0) { Ok(sockqd) => sockqd, Err(e) => anyhow::bail!("failed to create socket: {:?}", e), }; @@ -164,13 +164,13 @@ impl UdpClient { fn run( &mut self, - local_socket_addr: SocketAddr, - remote_socket_addr: SocketAddr, + local_addr: SocketAddr, + remote_addr: SocketAddr, fill_char: u8, bufsize_bytes: usize, num_sends: usize, ) -> Result<()> { - match self.libos.bind(self.sockqd, local_socket_addr) { + match self.libos.bind(self.sockqd, local_addr) { Ok(()) => (), Err(e) => anyhow::bail!("bind failed: {:?}", e), }; @@ -182,7 +182,7 @@ impl UdpClient { }; if let Some(sga) = self.sga { - let qt: QToken = match self.libos.pushto(self.sockqd, &sga, remote_socket_addr) { + let qt = match self.libos.pushto(self.sockqd, &sga, remote_addr) { Ok(qt) => qt, Err(e) => anyhow::bail!("push failed: {:?}", e), }; @@ -225,29 +225,23 @@ pub fn main() -> Result<()> { let args: Vec = env::args().collect(); if args.len() >= 3 { - let libos_name: LibOSName = match LibOSName::from_env() { + let libos_name = match LibOSName::from_env() { Ok(libos_name) => libos_name.into(), Err(e) => anyhow::bail!("{:?}", e), }; - let libos: LibOS = match LibOS::new(libos_name, None) { + let libos = match LibOS::new(libos_name, None) { Ok(libos) => libos, Err(e) => anyhow::bail!("failed to initialize libos: {:?}", e), }; - let local_socket_addr: SocketAddr = SocketAddr::from_str(&args[2])?; + let local_addr = SocketAddr::from_str(&args[2])?; if args[1] == "--server" { - let mut server: UdpServer = UdpServer::new(libos)?; - return server.run(local_socket_addr, FILL_CHAR, NUM_SENDS); + let mut server = UdpServer::new(libos)?; + return server.run(local_addr, FILL_CHAR, NUM_SENDS); } else if args[1] == "--client" && args.len() == 4 { - let remote_socket_addr: SocketAddr = SocketAddr::from_str(&args[3])?; - let mut client: UdpClient = UdpClient::new(libos)?; - return client.run( - local_socket_addr, - remote_socket_addr, - FILL_CHAR, - BUFSIZE_BYTES, - NUM_SENDS, - ); + let remote_addr = SocketAddr::from_str(&args[3])?; + let mut client = UdpClient::new(libos)?; + return client.run(local_addr, remote_addr, FILL_CHAR, BUFSIZE_BYTES, NUM_SENDS); } } diff --git a/examples/rust/udp-relay.rs b/examples/rust/udp-relay.rs index 2e09abc77..a2b29c54c 100644 --- a/examples/rust/udp-relay.rs +++ b/examples/rust/udp-relay.rs @@ -8,8 +8,8 @@ //====================================================================================================================== use ::anyhow::Result; -use ::clap::{Arg, ArgMatches, Command}; -use ::demikernel::{demi_sgarray_t, runtime::types::demi_opcode_t, LibOS, LibOSName, QDesc, QToken}; +use ::clap::{Arg, Command}; +use ::demikernel::{runtime::types::demi_opcode_t, LibOS, LibOSName, QDesc}; use ::std::{ net::SocketAddr, str::FromStr, @@ -30,8 +30,8 @@ pub const SOCK_DGRAM: i32 = libc::SOCK_DGRAM; #[derive(Debug)] pub struct ProgramArguments { - local_socket_addr: SocketAddr, - remote_socket_addr: SocketAddr, + local_addr: SocketAddr, + remote_addr: SocketAddr, } impl ProgramArguments { @@ -39,7 +39,7 @@ impl ProgramArguments { const DEFAULT_REMOTE_ADDR: &'static str = "127.0.0.1:23456"; pub fn new() -> Result { - let matches: ArgMatches = Command::new("udp-relay") + let matches = Command::new("udp-relay") .arg( Arg::new("local") .long("local") @@ -58,37 +58,37 @@ impl ProgramArguments { ) .get_matches(); - let mut args: ProgramArguments = ProgramArguments { - local_socket_addr: SocketAddr::from_str(Self::DEFAULT_LOCAL_ADDR)?, - remote_socket_addr: SocketAddr::from_str(Self::DEFAULT_REMOTE_ADDR)?, + let mut args = ProgramArguments { + local_addr: SocketAddr::from_str(Self::DEFAULT_LOCAL_ADDR)?, + remote_addr: SocketAddr::from_str(Self::DEFAULT_REMOTE_ADDR)?, }; if let Some(addr) = matches.get_one::("local") { - args.set_local_socket_addr(addr)?; + args.set_local_addr(addr)?; } if let Some(addr) = matches.get_one::("remote") { - args.set_remote_socket_addr(addr)?; + args.set_remote_addr(addr)?; } Ok(args) } - pub fn local_socket_addr(&self) -> SocketAddr { - self.local_socket_addr + pub fn local_addr(&self) -> SocketAddr { + self.local_addr } - pub fn remote_socket_addr(&self) -> SocketAddr { - self.remote_socket_addr + pub fn remote_addr(&self) -> SocketAddr { + self.remote_addr } - fn set_local_socket_addr(&mut self, addr: &str) -> Result<()> { - self.local_socket_addr = SocketAddr::from_str(addr)?; + fn set_local_addr(&mut self, addr: &str) -> Result<()> { + self.local_addr = SocketAddr::from_str(addr)?; Ok(()) } - fn set_remote_socket_addr(&mut self, addr: &str) -> Result<()> { - self.remote_socket_addr = SocketAddr::from_str(addr)?; + fn set_remote_addr(&mut self, addr: &str) -> Result<()> { + self.remote_addr = SocketAddr::from_str(addr)?; Ok(()) } } @@ -96,22 +96,22 @@ impl ProgramArguments { struct Application { libos: LibOS, sockqd: QDesc, - remote_socket_addr: SocketAddr, + remote_addr: SocketAddr, } impl Application { const LOG_INTERVAL_SECONDS: u64 = 5; pub fn new(mut libos: LibOS, args: &ProgramArguments) -> Result { - let local_socket_addr: SocketAddr = args.local_socket_addr(); - let remote_socket_addr: SocketAddr = args.remote_socket_addr(); + let local_addr = args.local_addr(); + let remote_addr = args.remote_addr(); - let sockqd: QDesc = match libos.socket(AF_INET, SOCK_DGRAM, 0) { + let sockqd = match libos.socket(AF_INET, SOCK_DGRAM, 0) { Ok(sockqd) => sockqd, Err(e) => anyhow::bail!("failed to create socket: {:?}", e), }; - match libos.bind(sockqd, local_socket_addr) { + match libos.bind(sockqd, local_addr) { Ok(()) => (), Err(e) => { // If error, close socket. @@ -123,24 +123,24 @@ impl Application { }, }; - println!("Local Address: {:?}", local_socket_addr); - println!("Remote Address: {:?}", remote_socket_addr); + println!("Local Address: {:?}", local_addr); + println!("Remote Address: {:?}", remote_addr); Ok(Self { libos, sockqd, - remote_socket_addr, + remote_addr, }) } pub fn run(&mut self) -> Result<()> { - let start_time: Instant = Instant::now(); - let mut num_bytes: usize = 0; - let mut qtokens: Vec = Vec::new(); - let mut last_log_time: Instant = Instant::now(); + let start_time = Instant::now(); + let mut num_bytes = 0; + let mut qtokens = Vec::new(); + let mut last_log_time = Instant::now(); // Pop first packet. - let qt: QToken = match self.libos.pop(self.sockqd, None) { + let qt = match self.libos.pop(self.sockqd, None) { Ok(qt) => qt, Err(e) => anyhow::bail!("failed to pop data from socket: {:?}", e), }; @@ -149,7 +149,7 @@ impl Application { loop { // Dump statistics. if last_log_time.elapsed() > Duration::from_secs(Self::LOG_INTERVAL_SECONDS) { - let elapsed: Duration = Instant::now() - start_time; + let elapsed = Instant::now() - start_time; println!("{:?} B / {:?} us", num_bytes, elapsed.as_micros()); last_log_time = Instant::now(); } @@ -164,11 +164,11 @@ impl Application { match qr.qr_opcode { // Pop completed. demi_opcode_t::DEMI_OPC_POP => { - let sga: demi_sgarray_t = unsafe { qr.qr_value.sga }; + let sga = unsafe { qr.qr_value.sga }; num_bytes += sga.segments[0].data_len_bytes as usize; - let qt: QToken = match self.libos.pushto(self.sockqd, &sga, self.remote_socket_addr) { + let qt = match self.libos.pushto(self.sockqd, &sga, self.remote_addr) { Ok(qt) => qt, Err(e) => { // If error, free scatter-gather array. @@ -190,7 +190,7 @@ impl Application { // Push completed. demi_opcode_t::DEMI_OPC_PUSH => { // Pop another packet. - let qt: QToken = match self.libos.pop(self.sockqd, None) { + let qt = match self.libos.pop(self.sockqd, None) { Ok(qt) => qt, Err(e) => anyhow::bail!("failed to pop data from socket: {:?}", e), }; @@ -217,12 +217,12 @@ impl Drop for Application { } fn main() -> Result<()> { - let args: ProgramArguments = ProgramArguments::new()?; - let libos_name: LibOSName = match LibOSName::from_env() { + let args = ProgramArguments::new()?; + let libos_name = match LibOSName::from_env() { Ok(libos_name) => libos_name.into(), Err(e) => panic!("{:?}", e), }; - let libos: LibOS = match LibOS::new(libos_name, None) { + let libos = match LibOS::new(libos_name, None) { Ok(libos) => libos, Err(e) => panic!("failed to initialize libos: {:?}", e), }; diff --git a/examples/tcp-close/client.rs b/examples/tcp-close/client.rs index d5ca357a2..353efb4a6 100644 --- a/examples/tcp-close/client.rs +++ b/examples/tcp-close/client.rs @@ -11,11 +11,7 @@ use crate::{helper_functions, TIMEOUT_SECONDS}; use anyhow::Result; -use demikernel::{ - demi_sgarray_t, - runtime::types::{demi_opcode_t, demi_qresult_t}, - LibOS, QDesc, QToken, -}; +use demikernel::{runtime::types::demi_opcode_t, LibOS, QDesc}; use std::{collections::HashSet, net::SocketAddr}; //====================================================================================================================== @@ -40,7 +36,7 @@ pub const SOCK_STREAM: i32 = libc::SOCK_STREAM; pub struct TcpClient { libos: LibOS, - remote_socket_addr: SocketAddr, + remote_addr: SocketAddr, open_qds: HashSet, num_connected_clients: usize, num_closed_clients: usize, @@ -51,11 +47,11 @@ pub struct TcpClient { //====================================================================================================================== impl TcpClient { - pub fn new(libos: LibOS, remote_socket_addr: SocketAddr) -> Result { - println!("Connecting to: {:?}", remote_socket_addr); + pub fn new(libos: LibOS, remote_addr: SocketAddr) -> Result { + println!("Connecting to: {:?}", remote_addr); Ok(Self { libos, - remote_socket_addr, + remote_addr, open_qds: HashSet::::default(), num_connected_clients: 0, num_closed_clients: 0, @@ -64,9 +60,9 @@ impl TcpClient { pub fn run_sequential(&mut self, num_clients: usize) -> Result<()> { for i in 0..num_clients { - let qd: QDesc = self.create_and_register_socket()?; - let qt: QToken = self.libos.connect(qd, self.remote_socket_addr)?; - let qr: demi_qresult_t = self.libos.wait(qt, Some(TIMEOUT_SECONDS))?; + let qd = self.create_and_register_socket()?; + let qt = self.libos.connect(qd, self.remote_addr)?; + let qr = self.libos.wait(qt, Some(TIMEOUT_SECONDS))?; match qr.qr_opcode { demi_opcode_t::DEMI_OPC_CONNECT => { @@ -87,11 +83,11 @@ impl TcpClient { } pub fn run_concurrent(&mut self, num_clients: usize) -> Result<()> { - let mut qtokens: Vec = Vec::default(); + let mut qtokens = Vec::default(); for _ in 0..num_clients { - let qd: QDesc = self.create_and_register_socket()?; - let qt: QToken = self.libos.connect(qd, self.remote_socket_addr)?; + let qd = self.create_and_register_socket()?; + let qt = self.libos.connect(qd, self.remote_addr)?; qtokens.push(qt); } @@ -103,15 +99,15 @@ impl TcpClient { break; } - let qr: demi_qresult_t = { - let (index, qr): (usize, demi_qresult_t) = self.libos.wait_any(&qtokens, Some(TIMEOUT_SECONDS))?; + let qr = { + let (index, qr) = self.libos.wait_any(&qtokens, Some(TIMEOUT_SECONDS))?; qtokens.remove(index); qr }; match qr.qr_opcode { demi_opcode_t::DEMI_OPC_CONNECT => { - let qd: QDesc = qr.qr_qd.into(); + let qd = qr.qr_qd.into(); self.num_connected_clients += 1; println!("{} clients connected", self.num_connected_clients); @@ -133,22 +129,22 @@ impl TcpClient { pub fn run_sequential_expecting_server_to_close_sockets(&mut self, num_clients: usize) -> Result<()> { for i in 0..num_clients { - let qd: QDesc = self.create_and_register_socket()?; - let qt: QToken = self.libos.connect(qd, self.remote_socket_addr)?; - let qr: demi_qresult_t = self.libos.wait(qt, Some(TIMEOUT_SECONDS))?; + let qd = self.create_and_register_socket()?; + let qt = self.libos.connect(qd, self.remote_addr)?; + let qr = self.libos.wait(qt, Some(TIMEOUT_SECONDS))?; match qr.qr_opcode { demi_opcode_t::DEMI_OPC_CONNECT => { println!("{} clients connected", i + 1); // Pop immediately after connect and wait. - let pop_qt: QToken = self.libos.pop(qd, None)?; - let pop_qr: demi_qresult_t = self.libos.wait(pop_qt, Some(TIMEOUT_SECONDS))?; + let pop_qt = self.libos.pop(qd, None)?; + let pop_qr = self.libos.wait(pop_qt, Some(TIMEOUT_SECONDS))?; match pop_qr.qr_opcode { demi_opcode_t::DEMI_OPC_POP => { - let sga: demi_sgarray_t = unsafe { pop_qr.qr_value.sga }; - let received_len: u32 = sga.segments[0].data_len_bytes; + let sga = unsafe { pop_qr.qr_value.sga }; + let received_len = sga.segments[0].data_len_bytes; self.libos.sgafree(sga)?; // 0 len pop represents socket closed from other side. demikernel::ensure_eq!( @@ -184,11 +180,11 @@ impl TcpClient { } pub fn run_concurrent_expecting_server_to_close_sockets(&mut self, num_clients: usize) -> Result<()> { - let mut qts: Vec = Vec::default(); + let mut qts = Vec::default(); for _i in 0..num_clients { - let qd: QDesc = self.create_and_register_socket()?; - let qt: QToken = self.libos.connect(qd, self.remote_socket_addr)?; + let qd = self.create_and_register_socket()?; + let qt = self.libos.connect(qd, self.remote_addr)?; qts.push(qt); } @@ -199,24 +195,24 @@ impl TcpClient { break; } - let qr: demi_qresult_t = { - let (index, qr): (usize, demi_qresult_t) = self.libos.wait_any(&qts, Some(TIMEOUT_SECONDS))?; - let _qt: QToken = qts.remove(index); + let qr = { + let (index, qr) = self.libos.wait_any(&qts, Some(TIMEOUT_SECONDS))?; + let _qt = qts.remove(index); qr }; match qr.qr_opcode { demi_opcode_t::DEMI_OPC_CONNECT => { - let qd: QDesc = qr.qr_qd.into(); + let qd = qr.qr_qd.into(); self.num_connected_clients += 1; println!("{} clients connected", self.num_connected_clients); // pop immediately after connect. - let pop_qt: QToken = self.libos.pop(qd, None)?; + let pop_qt = self.libos.pop(qd, None)?; qts.push(pop_qt); }, demi_opcode_t::DEMI_OPC_POP => { - let sga: demi_sgarray_t = unsafe { qr.qr_value.sga }; - let received_len: u32 = sga.segments[0].data_len_bytes; + let sga = unsafe { qr.qr_value.sga }; + let received_len = sga.segments[0].data_len_bytes; self.libos.sgafree(sga)?; // 0 len pop represents socket closed from other side. @@ -230,7 +226,7 @@ impl TcpClient { self.issue_close_and_deregister_qd(qr.qr_qd.into())?; }, demi_opcode_t::DEMI_OPC_FAILED => { - let errno: i64 = qr.qr_ret; + let errno = qr.qr_ret; assert_eq!( errno, libc::ECONNRESET as i64, @@ -251,7 +247,7 @@ impl TcpClient { /// Issues an open socket() operation and registers the queue descriptor for cleanup. fn create_and_register_socket(&mut self) -> Result { - let qd: QDesc = self.libos.socket(AF_INET, SOCK_STREAM, 0)?; + let qd = self.libos.socket(AF_INET, SOCK_STREAM, 0)?; self.open_qds.insert(qd); Ok(qd) } diff --git a/examples/tcp-close/server.rs b/examples/tcp-close/server.rs index 8a8837540..5cd486edf 100644 --- a/examples/tcp-close/server.rs +++ b/examples/tcp-close/server.rs @@ -13,11 +13,7 @@ use crate::{helper_functions, TIMEOUT_SECONDS}; use anyhow::Result; -use demikernel::{ - demi_sgarray_t, - runtime::types::{demi_opcode_t, demi_qresult_t}, - LibOS, QDesc, QToken, -}; +use demikernel::{runtime::types::demi_opcode_t, LibOS, QDesc, QToken}; use std::{collections::HashSet, net::SocketAddr}; //====================================================================================================================== @@ -56,12 +52,12 @@ pub struct TcpServer { //====================================================================================================================== impl TcpServer { - pub fn new(mut libos: LibOS, local_socket_addr: SocketAddr) -> Result { - let sockqd: QDesc = libos.socket(AF_INET, SOCK_STREAM, 0)?; + pub fn new(mut libos: LibOS, local_addr: SocketAddr) -> Result { + let sockqd = libos.socket(AF_INET, SOCK_STREAM, 0)?; - libos.bind(sockqd, local_socket_addr)?; + libos.bind(sockqd, local_addr)?; - println!("Listening to: {:?}", local_socket_addr); + println!("Listening to: {:?}", local_addr); return Ok(Self { libos, @@ -94,36 +90,34 @@ impl TcpServer { } } - let qr: demi_qresult_t = { - let (index, qr): (usize, demi_qresult_t) = - self.libos.wait_any(&self.pending_qtokens, Some(TIMEOUT_SECONDS))?; - self.mark_completed_operation(index)?; + let qr = { + let (idx, qr) = self.libos.wait_any(&self.pending_qtokens, Some(TIMEOUT_SECONDS))?; + self.mark_completed_operation(idx)?; qr }; match qr.qr_opcode { // Accept completed. demi_opcode_t::DEMI_OPC_ACCEPT => { - let qd: QDesc = unsafe { qr.qr_value.ares.qd.into() }; + let qd = unsafe { qr.qr_value.ares.qd.into() }; self.handle_accept_completion(qd)?; // Accept more connections. self.issue_accept()?; }, // Pop completed. demi_opcode_t::DEMI_OPC_POP => { - let qd: QDesc = qr.qr_qd.into(); - let sga: demi_sgarray_t = unsafe { qr.qr_value.sga }; - let seglen: usize = sga.segments[0].data_len_bytes as usize; + let qd = qr.qr_qd.into(); + let sga = unsafe { qr.qr_value.sga }; + let seglen = sga.segments[0].data_len_bytes as usize; // Ensure that client has closed the connection. assert_eq!(seglen, 0, "client must have had closed the connection, but it has not"); self.libos.sgafree(sga)?; - self.handle_connection_termination(qd)?; }, demi_opcode_t::DEMI_OPC_FAILED => { - let qd: QDesc = qr.qr_qd.into(); + let qd = qr.qr_qd.into(); // Ensure that this error was triggered because the client has terminated the connection. if !helper_functions::is_closed(qr.qr_ret) { @@ -161,22 +155,24 @@ impl TcpServer { if let Some(nclients) = nclients { if self.num_closed_clients >= nclients { // Sanity check that all connections have been closed. - const ERR_MSG: &str = "there should be no clients connected, but there are"; - assert_eq!(self.connected_client_qds.len(), 0, "{}", ERR_MSG); + assert_eq!( + self.connected_client_qds.len(), + 0, + "there should be no clients connected" + ); break; } } - let qr: demi_qresult_t = { - let (index, qr): (usize, demi_qresult_t) = - self.libos.wait_any(&self.pending_qtokens, Some(TIMEOUT_SECONDS))?; + let qr = { + let (index, qr) = self.libos.wait_any(&self.pending_qtokens, Some(TIMEOUT_SECONDS))?; self.mark_completed_operation(index)?; qr }; match qr.qr_opcode { demi_opcode_t::DEMI_OPC_ACCEPT => { - let qd: QDesc = unsafe { qr.qr_value.ares.qd.into() }; + let qd = unsafe { qr.qr_value.ares.qd.into() }; self.num_accepted_clients += 1; println!("{} clients accepted, closing socket", self.num_accepted_clients); helper_functions::close_and_wait(&mut self.libos, qd)?; @@ -209,13 +205,13 @@ impl TcpServer { } fn issue_accept(&mut self) -> Result<()> { - let qt: QToken = self.libos.accept(self.sockqd)?; + let qt = self.libos.accept(self.sockqd)?; self.pending_qtokens.push(qt); Ok(()) } fn issue_pop(&mut self, qd: QDesc) -> Result<()> { - let qt: QToken = self.libos.pop(qd, None)?; + let qt = self.libos.pop(qd, None)?; self.pending_qtokens.push(qt); Ok(()) } diff --git a/src/catnap/win/transport.rs b/src/catnap/win/transport.rs index bce9e145b..c482bf048 100644 --- a/src/catnap/win/transport.rs +++ b/src/catnap/win/transport.rs @@ -316,7 +316,7 @@ impl NetworkTransport for SharedCatnapTransport { Ok(()) } - fn get_runtime(&self) -> &SharedDemiRuntime { + fn runtime(&self) -> &SharedDemiRuntime { &self.0.runtime } } diff --git a/src/inetstack/protocols/layer3/arp/tests.rs b/src/inetstack/protocols/layer3/arp/tests.rs index 53b5d2fef..bdfad0ebc 100644 --- a/src/inetstack/protocols/layer3/arp/tests.rs +++ b/src/inetstack/protocols/layer3/arp/tests.rs @@ -52,7 +52,7 @@ fn arp_immediate_reply() -> Result<()> { // Move clock forward and poll the engine. now += Duration::from_micros(1); engine.advance_clock(now); - engine.get_runtime().run_background_tasks(); + engine.runtime().run_background_tasks(); // Check if the ARP cache outputs a reply message. let mut buffers = engine.pop_expected_frames(1); @@ -120,7 +120,7 @@ fn arp_cache_update() -> Result<()> { // Move clock forward and poll the engine. now += Duration::from_micros(1); engine.advance_clock(now); - engine.get_runtime().run_background_tasks(); + engine.runtime().run_background_tasks(); // Check if the ARP cache has been updated. let cache = engine.transport().export_arp_cache(); @@ -157,7 +157,7 @@ fn arp_cache_timeout() -> Result<()> { let _qt = engine.runtime().clone().schedule_coroutine("arp query", coroutine)?; for _ in 0..(ARP_RETRY_COUNT + 1) { - engine.get_runtime().run_foreground_tasks(); + engine.runtime().run_foreground_tasks(); // Check if the ARP cache outputs a reply message. let buffers = engine.pop_expected_frames(1); crate::ensure_eq!(buffers.len(), 1); diff --git a/tests/rust/udp-tests/args.rs b/tests/rust/udp-tests/args.rs index 1fccb7197..2817a0b8a 100644 --- a/tests/rust/udp-tests/args.rs +++ b/tests/rust/udp-tests/args.rs @@ -2,7 +2,7 @@ // Licensed under the MIT license. use anyhow::Result; -use clap::{Arg, ArgMatches, Command}; +use clap::{Arg, Command}; use std::{ net::{SocketAddr, SocketAddrV4}, str::FromStr, @@ -10,13 +10,13 @@ use std::{ #[derive(Debug)] pub struct ProgramArguments { - local_socket_addr: SocketAddr, - remote_socket_addr: SocketAddr, + local_addr: SocketAddr, + remote_addr: SocketAddr, } impl ProgramArguments { pub fn new() -> Result { - let matches: ArgMatches = Command::new("udp-tests") + let matches = Command::new("udp-tests") .arg( Arg::new("local") .long("local-address") @@ -35,29 +35,29 @@ impl ProgramArguments { ) .get_matches(); - let local_socket_addr: SocketAddr = SocketAddr::V4({ - let local_socket_addr: &String = matches.get_one::("local").expect("missing address"); - SocketAddrV4::from_str(local_socket_addr)? + let local_addr = SocketAddr::V4({ + let addr = matches.get_one::("local").expect("missing address"); + SocketAddrV4::from_str(addr)? }); - let remote_socket_addr: SocketAddr = SocketAddr::V4({ - let remote_socket_addr: &String = matches.get_one::("remote").expect("missing address"); - SocketAddrV4::from_str(remote_socket_addr)? + let remote_addr = SocketAddr::V4({ + let addr = matches.get_one::("remote").expect("missing address"); + SocketAddrV4::from_str(addr)? }); Ok(Self { - local_socket_addr, - remote_socket_addr, + local_addr, + remote_addr, }) } - pub fn local_socket_addr(&self) -> SocketAddr { - self.local_socket_addr + pub fn local_addr(&self) -> SocketAddr { + self.local_addr } - // ToDo: Remove this `unused` annotation after remote_socket_addr is used (when new tests are added to this file). + // ToDo: Remove this `unused` annotation after remote_addr is used (when new tests are added to this file). #[allow(unused)] - pub fn get_remote_socket_addr(&self) -> SocketAddr { - self.remote_socket_addr + pub fn get_remote_addr(&self) -> SocketAddr { + self.remote_addr } } diff --git a/tests/rust/udp-tests/main.rs b/tests/rust/udp-tests/main.rs index 3e47e4a5d..0c0552046 100644 --- a/tests/rust/udp-tests/main.rs +++ b/tests/rust/udp-tests/main.rs @@ -33,34 +33,24 @@ macro_rules! append_test_result { } fn main() -> Result<()> { - let args: ProgramArguments = ProgramArguments::new()?; - let mut libos: LibOS = { - let libos_name: LibOSName = LibOSName::from_env()?.into(); - LibOS::new(libos_name, None)? - }; - let mut num_failed_tests: usize = 0; - let mut test_results: Vec<(String, String, Result<(), anyhow::Error>)> = Vec::new(); - - append_test_result!( - test_results, - bind::run_tests(&mut libos, &args.local_socket_addr().ip()) - ); + let args = ProgramArguments::new()?; + let mut libos = LibOS::new(LibOSName::from_env()?.into(), None)?; + let mut num_failed = 0; + let mut results = Vec::new(); - append_test_result!( - test_results, - close::run_tests(&mut libos, &args.local_socket_addr().ip()) - ); + append_test_result!(results, bind::run_tests(&mut libos, &args.local_addr().ip())); + append_test_result!(results, close::run_tests(&mut libos, &args.local_addr().ip())); - for (test_name, test_status, test_result) in test_results { - println!("[{}] {}", test_status, test_name); + for (name, status, test_result) in results { + println!("[{}] {}", status, name); if let Err(e) = test_result { - num_failed_tests += 1; + num_failed += 1; println!(" {}", e); } } - if num_failed_tests > 0 { - anyhow::bail!("{} tests failed", num_failed_tests); + if num_failed > 0 { + anyhow::bail!("{} tests failed", num_failed); } println!("all tests passed");