Collect all query results into one Vec
authorMegaBrutal <megabrutal+github@megabrutal.com>
Sat, 18 Feb 2023 21:00:00 +0000 (22:00 +0100)
committerMegaBrutal <megabrutal+github@megabrutal.com>
Sat, 18 Feb 2023 21:00:00 +0000 (22:00 +0100)
src/main.rs

index c62bc7f78f71e3bd830e57ec0260d8d2e4646dca..90d51c37b78752d8f4625bb2fc44fe45118c0000 100644 (file)
@@ -5,7 +5,7 @@ use std::env::args;
 use std::net::{SocketAddr, SocketAddrV4, ToSocketAddrs};
 use serde::{Serialize, Serializer};
 use a2s::A2SClient;
-use crate::HLQueryError::A2SError;
+use crate::HLQueryError::{IOError,A2SError};
 
 #[derive(Debug, Serialize)]
 struct HLQueryResult {
@@ -28,12 +28,14 @@ impl HLQueryResult {
 
 #[derive(Debug)]
 enum HLQueryError {
+    IOError(std::io::Error),
     A2SError(a2s::errors::Error)
 }
 
 impl Display for HLQueryError {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
         match self {
+            IOError(e) => write!(f, "{}", e),
             A2SError(e) => write!(f, "{}", e)
         }
     }
@@ -50,6 +52,12 @@ impl Serialize for HLQueryError {
     }
 }
 
+impl From<std::io::Error> for HLQueryError {
+    fn from(e: std::io::Error) -> Self {
+        Self::IOError(e)
+    }
+}
+
 impl From<a2s::errors::Error> for HLQueryError {
     fn from(e: a2s::errors::Error) -> Self {
         Self::A2SError(e)
@@ -59,24 +67,22 @@ impl From<a2s::errors::Error> for HLQueryError {
 
 fn main() {
     let client = A2SClient::new().unwrap();
-    let addresses = args().skip(1)
+    let query_results: Vec<Result<Vec<HLQueryResult>, HLQueryError>> = args().skip(1)
         .map(|arg| arg.to_socket_addrs())
         .map(|lookup_result| match lookup_result {
             Ok(iter_addr) => {
-                Ok(iter_addr.flat_map(|sa| match sa {
+                Ok(iter_addr.filter_map(|sa| match sa {
                     SocketAddr::V4(sa4) => Some(sa4),
                     _ => None
                 }))
             },
+            Err(e) => Err(HLQueryError::IOError(e))
+        })
+        .map(|addresses| match addresses {
+            Ok(iter_addr) => Ok(iter_addr.map(|addr| HLQueryResult::new(&client, addr)).collect()),
             Err(e) => Err(e)
-        });
-
-    for address in addresses {
+        })
+        .collect();
 
-        println!("Querying address: {:?}", address);
-
-        let result = HLQueryResult::new(&client, address.unwrap().next().unwrap());
-        println!("{}\n", serde_json::to_string_pretty(&result).unwrap());
-
-    }
+    println!("{}\n", serde_json::to_string_pretty(&query_results).unwrap());
 }