From 4949d55cf785b53485989019489033bda6523ff6 Mon Sep 17 00:00:00 2001 From: kiron1 Date: Sun, 31 Dec 2023 17:30:00 +0800 Subject: [PATCH] Simplified resolve domain function --- paclib/src/dns.rs | 17 ++++++----------- paclib/src/engine.rs | 34 ++++++++++++++++++---------------- 2 files changed, 24 insertions(+), 27 deletions(-) diff --git a/paclib/src/dns.rs b/paclib/src/dns.rs index 062cb01a..2e0dbff8 100644 --- a/paclib/src/dns.rs +++ b/paclib/src/dns.rs @@ -80,15 +80,10 @@ impl Class for DnsCache { pub(crate) fn resolve(host: &str) -> Option { use std::net::ToSocketAddrs; - let host_port = (host, 0u16); - if let Ok(mut addrs) = host_port.to_socket_addrs() { - if let Some(addr) = addrs.next() { - let ip = addr.ip(); - Some(ip.to_string()) - } else { - None - } - } else { - None - } + (host, 0u16) + .to_socket_addrs() + .ok() + .and_then(|mut a| a.next()) + .map(|a| a.ip()) + .map(|ip| ip.to_string()) } diff --git a/paclib/src/engine.rs b/paclib/src/engine.rs index 0c26ae9d..0b14e988 100644 --- a/paclib/src/engine.rs +++ b/paclib/src/engine.rs @@ -1,4 +1,4 @@ -use boa_engine::{Context, JsResult, JsString, JsValue, NativeFunction, Source}; +use boa_engine::{Context, JsNativeError, JsResult, JsString, JsValue, NativeFunction, Source}; use http::Uri; use std::result::Result; use std::time::Instant; @@ -121,9 +121,9 @@ fn alert(_this: &JsValue, args: &[JsValue], _ctx: &mut Context) -> JsResult JsResult { - let global = ctx.global_object(); - let dns_cache = global.get("_dnsCache", ctx).expect("_dnsCache"); +fn dns_resolve(_this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { + let global = context.global_object(); + let dns_cache = global.get("_dnsCache", context).expect("_dnsCache"); let dns_cache = dns_cache.as_object(); let mut dns_cache = dns_cache .and_then(|obj| obj.try_borrow_mut().ok()) @@ -132,18 +132,20 @@ fn dns_resolve(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult .downcast_mut::() .expect("downcast_mut"); - let value = if let Some(host) = args.first() { - if let Ok(host) = host.to_string(ctx) { - let resolved = dns_cache.lookup(&host.to_std_string_escaped()); - match resolved { - Some(ip) => JsValue::from(JsString::from(ip)), - None => JsValue::undefined(), - } - } else { - JsValue::undefined() - } - } else { - JsValue::undefined() + let Some(host) = args.first() else { + return Err(JsNativeError::typ() + .with_message("first argument is missing") + .into()); + }; + let Ok(host) = host.to_string(context) else { + return Err(JsNativeError::typ() + .with_message("first argument must be string") + .into()); + }; + let resolved = dns_cache.lookup(&host.to_std_string_escaped()); + let value = match resolved { + Some(ip) => JsValue::from(JsString::from(ip)), + None => JsValue::null(), }; Ok(value)