Skip to content

Commit

Permalink
refactor(rust): avoid unnecessary clone on external (#1092)
Browse files Browse the repository at this point in the history
  • Loading branch information
hyf0 committed May 11, 2024
1 parent a5340a3 commit bd851a9
Show file tree
Hide file tree
Showing 8 changed files with 79 additions and 56 deletions.
9 changes: 4 additions & 5 deletions crates/rolldown/src/module_loader/normal_module_task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,8 +217,8 @@ impl NormalModuleTask {
options: HookResolveIdExtraOptions,
) -> anyhow::Result<Result<ResolvedRequestInfo, ResolveError>> {
// Check external with unresolved path
if let Some(external) = input_options.external.as_ref() {
if external.call(specifier.to_string(), Some(importer.to_string()), false).await? {
if let Some(is_external) = input_options.external.as_ref() {
if is_external(specifier, Some(importer), false).await? {
return Ok(Ok(ResolvedRequestInfo {
path: specifier.to_string().into(),
module_type: ModuleType::Unknown,
Expand All @@ -234,9 +234,8 @@ impl NormalModuleTask {
Ok(mut resolved_id) => {
if !resolved_id.is_external {
// Check external with resolved path
if let Some(external) = input_options.external.as_ref() {
resolved_id.is_external =
external.call(specifier.to_string(), Some(importer.to_string()), true).await?;
if let Some(is_external) = input_options.external.as_ref() {
resolved_id.is_external = is_external(specifier, Some(importer), true).await?;
}
}
Ok(Ok(resolved_id))
Expand Down
13 changes: 9 additions & 4 deletions crates/rolldown_binding/src/utils/normalize_binding_options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::{
types::{binding_rendered_chunk::RenderedChunk, js_callback::MaybeAsyncJsCallbackExt},
worker_manager::WorkerManager,
};
use rolldown::{AddonOutputOption, BundlerOptions, Platform};
use rolldown::{AddonOutputOption, BundlerOptions, IsExternal, Platform};
use rolldown_plugin::BoxPlugin;
use std::path::PathBuf;
#[cfg(not(target_family = "wasm"))]
Expand Down Expand Up @@ -43,12 +43,17 @@ pub fn normalize_binding_options(
let cwd = PathBuf::from(input_options.cwd);

let external = input_options.external.map(|ts_fn| {
rolldown::External::Fn(Box::new(move |source, importer, is_resolved| {
IsExternal::from_closure(move |source, importer, is_resolved| {
let source = source.to_string();
let importer = importer.map(ToString::to_string);
let ts_fn = ts_fn.clone();
Box::pin(async move {
ts_fn.call_async((source, importer, is_resolved)).await.map_err(anyhow::Error::from)
ts_fn
.call_async((source.to_string(), importer.map(|v| v.to_string()), is_resolved))
.await
.map_err(anyhow::Error::from)
})
}))
})
});

let sourcemap_ignore_list = output_options.sourcemap_ignore_list.map(|ts_fn| {
Expand Down
8 changes: 4 additions & 4 deletions crates/rolldown_common/src/inner_bundler_options/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use serde::{Deserialize, Deserializer};
use crate::SourceMapIgnoreList;

use self::types::{
external::External, input_item::InputItem, output_format::OutputFormat,
input_item::InputItem, is_external::IsExternal, output_format::OutputFormat,
output_option::AddonOutputOption, platform::Platform, resolve_options::ResolveOptions,
source_map_type::SourceMapType, sourcemap_path_transform::SourceMapPathTransform,
};
Expand All @@ -30,7 +30,7 @@ pub struct BundlerOptions {
serde(default, deserialize_with = "deserialize_external"),
schemars(with = "Option<Vec<String>>")
)]
pub external: Option<External>,
pub external: Option<IsExternal>,
pub treeshake: Option<bool>,
pub platform: Option<Platform>,
pub shim_missing_exports: Option<bool>,
Expand Down Expand Up @@ -69,12 +69,12 @@ pub struct BundlerOptions {
}

#[cfg(feature = "deserialize_bundler_options")]
fn deserialize_external<'de, D>(deserializer: D) -> Result<Option<External>, D::Error>
fn deserialize_external<'de, D>(deserializer: D) -> Result<Option<IsExternal>, D::Error>
where
D: Deserializer<'de>,
{
let deserialized = Option::<Vec<String>>::deserialize(deserializer)?;
Ok(deserialized.map(External::ArrayString))
Ok(deserialized.map(IsExternal::from_vec))
}

#[cfg(feature = "deserialize_bundler_options")]
Expand Down
39 changes: 0 additions & 39 deletions crates/rolldown_common/src/inner_bundler_options/types/external.rs

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
use std::fmt::Debug;
use std::future::Future;
use std::ops::Deref;
use std::pin::Pin;

type Inner = dyn Fn(
&str, // specifier
Option<&str>, // importer
bool, // is_resolved
) -> Pin<Box<(dyn Future<Output = anyhow::Result<bool>> + Send + 'static)>>
+ Send
+ Sync
+ 'static;

pub struct IsExternal(Box<Inner>);

impl Deref for IsExternal {
type Target = Inner;

fn deref(&self) -> &Self::Target {
&*self.0
}
}

impl IsExternal {
pub fn from_closure<F>(f: F) -> Self
where
F: Fn(
&str, // specifier
Option<&str>, // importer
bool, // is_resolved
) -> Pin<Box<(dyn Future<Output = anyhow::Result<bool>> + Send + 'static)>>
+ Send
+ Sync
+ 'static,
{
Self(Box::new(f))
}

pub fn from_vec(value: Vec<String>) -> Self {
Self::from_closure(move |source, _, _| {
let result = value.iter().any(|item| item == source);
Box::pin(async move { Ok(result) })
})
}
}

impl From<Vec<String>> for IsExternal {
fn from(value: Vec<String>) -> Self {
IsExternal::from_vec(value)
}
}

impl Debug for IsExternal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "IsExternal(...)")
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pub mod external;
pub mod file_name_template;
pub mod input_item;
pub mod is_external;
pub mod normalized_bundler_options;
pub mod output_format;
pub mod output_option;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
use std::path::PathBuf;

use super::{
external::External, file_name_template::FilenameTemplate, input_item::InputItem,
file_name_template::FilenameTemplate, input_item::InputItem, is_external::IsExternal,
output_format::OutputFormat, output_option::AddonOutputOption, platform::Platform,
source_map_type::SourceMapType, sourcemap_ignore_list::SourceMapIgnoreList,
sourcemap_path_transform::SourceMapPathTransform,
Expand All @@ -15,7 +15,7 @@ pub struct NormalizedBundlerOptions {
// --- Input
pub input: Vec<InputItem>,
pub cwd: PathBuf,
pub external: Option<External>,
pub external: Option<IsExternal>,
pub treeshake: bool,
pub platform: Platform,
pub shim_missing_exports: bool,
Expand Down
2 changes: 1 addition & 1 deletion crates/rolldown_common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ mod types;
pub mod bundler_options {
pub use crate::inner_bundler_options::{
types::{
external::External,
file_name_template::{FileNameRenderOptions, FilenameTemplate},
input_item::InputItem,
is_external::IsExternal,
normalized_bundler_options::NormalizedBundlerOptions,
output_format::OutputFormat,
output_option::{AddonFunction, AddonOutputOption},
Expand Down

0 comments on commit bd851a9

Please sign in to comment.