Skip to content

Commit

Permalink
Simplified resolve domain function
Browse files Browse the repository at this point in the history
  • Loading branch information
kiron1 committed Dec 31, 2023
1 parent 187699a commit 4949d55
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 27 deletions.
17 changes: 6 additions & 11 deletions paclib/src/dns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,15 +80,10 @@ impl Class for DnsCache {
pub(crate) fn resolve(host: &str) -> Option<String> {
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())
}
34 changes: 18 additions & 16 deletions paclib/src/engine.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -121,9 +121,9 @@ fn alert(_this: &JsValue, args: &[JsValue], _ctx: &mut Context) -> JsResult<JsVa
Ok(JsValue::undefined())
}

fn dns_resolve(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
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<JsValue> {
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())
Expand All @@ -132,18 +132,20 @@ fn dns_resolve(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult
.downcast_mut::<DnsCache>()
.expect("downcast_mut<DnsCache>");

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)
Expand Down

0 comments on commit 4949d55

Please sign in to comment.