From cd962e5451eda64d6808e07b1695ad73e4fddd79 Mon Sep 17 00:00:00 2001 From: dalaoshu Date: Tue, 3 Sep 2024 21:18:56 +0800 Subject: [PATCH] perf: use itoa for integer to string conversion (#7762) --- Cargo.lock | 5 +-- Cargo.toml | 6 ++-- crates/rspack_binding_values/src/stats.rs | 7 ++-- .../src/build_chunk_graph/code_splitter.rs | 12 ++++--- .../rspack_core/src/compiler/compilation.rs | 3 +- crates/rspack_core/src/concatenated_module.rs | 8 ++--- crates/rspack_core/src/context_module.rs | 3 +- .../src/utils/concatenation_scope.rs | 3 +- crates/rspack_ids/src/id_helpers.rs | 9 ++--- crates/rspack_loader_swc/src/compiler.rs | 5 ++- crates/rspack_plugin_css/src/utils.rs | 3 +- .../src/css_module.rs | 5 +-- .../src/parser_and_generator/mod.rs | 17 +++++++--- .../src/parser_plugin/compatibility_plugin.rs | 10 ++++-- .../src/parser_plugin/define_plugin/mod.rs | 3 +- .../src/plugin/module_concatenation_plugin.rs | 33 ++++++++++--------- .../src/json_exports_dependency.rs | 4 +-- crates/rspack_plugin_json/src/lib.rs | 3 +- .../container/container_reference_plugin.rs | 3 +- .../src/container/fallback_module.rs | 4 +-- .../src/module_chunk_format.rs | 9 +++-- .../src/runtime_module/get_chunk_filename.rs | 6 ++-- .../src/parser_and_generator.rs | 3 +- crates/rspack_plugin_wasm/src/runtime.rs | 3 +- crates/rspack_util/Cargo.toml | 1 + crates/rspack_util/src/itoa.rs | 8 +++++ crates/rspack_util/src/lib.rs | 1 + 27 files changed, 112 insertions(+), 65 deletions(-) create mode 100644 crates/rspack_util/src/itoa.rs diff --git a/Cargo.lock b/Cargo.lock index b0b6376c242..9e2293c7c17 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1713,9 +1713,9 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.8" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b02a5381cc465bd3041d84623d0fa3b66738b52b8e2fc3bab8ad63ab032f4a" +checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" [[package]] name = "js-sys" @@ -4097,6 +4097,7 @@ dependencies = [ "concat-string", "dashmap 5.5.3", "indexmap 2.2.6", + "itoa", "regex", "rspack_regex", "rustc-hash 1.1.0", diff --git a/Cargo.toml b/Cargo.toml index 018994c87a4..d200b13b800 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,8 +21,8 @@ async-scoped = { version = "0.9.0" } async-trait = { version = "0.1.79" } bitflags = { version = "2.5.0" } camino = { version = "1.1.8" } -concat-string = "1.0.1" -css-module-lexer = "0.0.14" +concat-string = { version = "1.0.1" } +css-module-lexer = { version = "0.0.14" } dashmap = { version = "5.5.3" } derivative = { version = "2.2.0" } futures = { version = "0.3.30" } @@ -39,7 +39,7 @@ linked_hash_set = { version = "0.1.4" } mimalloc = { version = "0.1.43" } mime_guess = { version = "2.0.4" } once_cell = { version = "1.19.0" } -parcel_sourcemap = "2.1.1" +parcel_sourcemap = { version = "2.1.1" } paste = { version = "1.0" } path-clean = { version = "1.0.1" } pathdiff = { version = "0.2.1" } diff --git a/crates/rspack_binding_values/src/stats.rs b/crates/rspack_binding_values/src/stats.rs index a5c817f55f4..0ae03bd0459 100644 --- a/crates/rspack_binding_values/src/stats.rs +++ b/crates/rspack_binding_values/src/stats.rs @@ -12,6 +12,7 @@ use rspack_napi::{ }, Ref, }; +use rspack_util::itoa; use rustc_hash::FxHashMap as HashMap; use super::ToJsCompatSource; @@ -328,7 +329,7 @@ impl From<(String, rspack_core::LogType)> for JsStatsLogging { args: Some(vec![format!( "{}: {} ms", label, - secs * 1000 + subsec_nanos as u64 / 1000000 + itoa!(secs * 1000 + subsec_nanos as u64 / 1000000) )]), trace: None, }, @@ -355,8 +356,8 @@ impl From<(String, rspack_core::LogType)> for JsStatsLogging { } else { hit as f32 / total as f32 * 100_f32 }, - hit, - total, + itoa!(hit), + itoa!(total), )]), trace: None, }, diff --git a/crates/rspack_core/src/build_chunk_graph/code_splitter.rs b/crates/rspack_core/src/build_chunk_graph/code_splitter.rs index a3f9d665d8c..28ebdd9c692 100644 --- a/crates/rspack_core/src/build_chunk_graph/code_splitter.rs +++ b/crates/rspack_core/src/build_chunk_graph/code_splitter.rs @@ -11,6 +11,7 @@ use rspack_collections::{ }; use rspack_collections::{IdentifierIndexSet, IdentifierMap}; use rspack_error::{error, Diagnostic, Error, Result}; +use rspack_util::itoa; use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet, FxHasher}; use crate::dependencies_block::AsyncDependenciesToInitialChunkError; @@ -857,19 +858,22 @@ Or do you want to use the entrypoints '{name}' and '{runtime}' independently on logger.log(format!( "{} queue items processed ({} blocks)", - self.stat_processed_queue_items, self.stat_processed_blocks + itoa!(self.stat_processed_queue_items), + itoa!(self.stat_processed_blocks) )); logger.log(format!( "{} chunk groups connected", - self.stat_connected_chunk_groups, + itoa!(self.stat_connected_chunk_groups), )); logger.log(format!( "{} chunk groups processed for merging ({} module sets)", - self.stat_processed_chunk_groups_for_merging, self.stat_merged_available_module_sets, + itoa!(self.stat_processed_chunk_groups_for_merging), + itoa!(self.stat_merged_available_module_sets), )); logger.log(format!( "{} chunk group info updated ({} already connected chunk groups reconnected)", - self.stat_chunk_group_info_updated, self.stat_child_chunk_groups_reconnected, + itoa!(self.stat_chunk_group_info_updated), + itoa!(self.stat_child_chunk_groups_reconnected), )); Ok(()) diff --git a/crates/rspack_core/src/compiler/compilation.rs b/crates/rspack_core/src/compiler/compilation.rs index 3515132b658..7b09b8e54ab 100644 --- a/crates/rspack_core/src/compiler/compilation.rs +++ b/crates/rspack_core/src/compiler/compilation.rs @@ -18,6 +18,7 @@ use rspack_futures::FuturesResults; use rspack_hash::{RspackHash, RspackHashDigest}; use rspack_hook::define_hook; use rspack_sources::{BoxSource, CachedSource, SourceExt}; +use rspack_util::itoa; use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet, FxHasher}; use tracing::instrument; @@ -457,7 +458,7 @@ impl Compilation { let import_var = match import_var_map_of_module.entry(module_id) { hash_map::Entry::Occupied(occ) => occ.get().clone(), hash_map::Entry::Vacant(vac) => { - let import_var = format!("{}__WEBPACK_IMPORTED_MODULE_{}__", user_request, len); + let import_var = format!("{}__WEBPACK_IMPORTED_MODULE_{}__", user_request, itoa!(len)); vac.insert(import_var.clone()); import_var } diff --git a/crates/rspack_core/src/concatenated_module.rs b/crates/rspack_core/src/concatenated_module.rs index 2ae5fe99234..a785a8c1a2f 100644 --- a/crates/rspack_core/src/concatenated_module.rs +++ b/crates/rspack_core/src/concatenated_module.rs @@ -18,7 +18,7 @@ use rspack_error::{Diagnosable, Diagnostic, DiagnosticKind, Result, TraceableErr use rspack_hash::{HashDigest, HashFunction, RspackHash}; use rspack_hook::define_hook; use rspack_sources::{CachedSource, ConcatSource, RawSource, ReplaceSource, Source, SourceExt}; -use rspack_util::{ext::DynHash, source_map::SourceMapKind, swc::join_atom}; +use rspack_util::{ext::DynHash, itoa, source_map::SourceMapKind, swc::join_atom}; use rustc_hash::FxHasher; use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet}; use swc_core::{ @@ -508,7 +508,7 @@ impl Module for ConcatenatedModule { Cow::Owned(format!( "{} + {} modules", self.root_module_ctxt.readable_identifier, - self.modules.len() - 1 + itoa!(self.modules.len() - 1) )) } @@ -2260,14 +2260,14 @@ pub fn find_new_name( } let mut i = 0; - let mut name_with_number = to_identifier(&format!("{}_{}", name, i)).into(); + let mut name_with_number = to_identifier(&format!("{}_{}", name, itoa!(i))).into(); while used_names1.contains(&name_with_number) || used_names2 .map(|map| map.contains(&name_with_number)) .unwrap_or_default() { i += 1; - name_with_number = to_identifier(&format!("{}_{}", name, i)).into(); + name_with_number = to_identifier(&format!("{}_{}", name, itoa!(i))).into(); } name_with_number diff --git a/crates/rspack_core/src/context_module.rs b/crates/rspack_core/src/context_module.rs index ed928d39b26..3c03318d9d3 100644 --- a/crates/rspack_core/src/context_module.rs +++ b/crates/rspack_core/src/context_module.rs @@ -11,6 +11,7 @@ use rspack_macros::impl_source_map_config; use rspack_paths::{AssertUtf8, Utf8Path, Utf8PathBuf}; use rspack_regex::RspackRegex; use rspack_sources::{BoxSource, ConcatSource, RawSource, SourceExt}; +use rspack_util::itoa; use rspack_util::{fx_hash::FxIndexMap, json_stringify, source_map::SourceMapKind}; use rustc_hash::FxHashMap as HashMap; use rustc_hash::FxHashSet as HashSet; @@ -497,7 +498,7 @@ impl ContextModule { format!( "{}(ids[{}])", RuntimeGlobals::ENSURE_CHUNK, - chunks_start_position + itoa!(chunks_start_position) ) }; let return_module_object = self.get_return_module_object_source( diff --git a/crates/rspack_core/src/utils/concatenation_scope.rs b/crates/rspack_core/src/utils/concatenation_scope.rs index e1b584609c7..f922c5dd6b2 100644 --- a/crates/rspack_core/src/utils/concatenation_scope.rs +++ b/crates/rspack_core/src/utils/concatenation_scope.rs @@ -4,6 +4,7 @@ use std::sync::LazyLock; use regex::Regex; use rspack_collections::IdentifierIndexMap; +use rspack_util::itoa; use swc_core::atoms::Atom; use crate::concatenated_module::{ConcatenatedModuleInfo, ModuleInfo}; @@ -110,7 +111,7 @@ impl ConcatenationScope { format!( "__WEBPACK_MODULE_REFERENCE__{}_{}{}{}{}__._", - info.index(), + itoa!(info.index()), export_data, call_flag, direct_import_flag, diff --git a/crates/rspack_ids/src/id_helpers.rs b/crates/rspack_ids/src/id_helpers.rs index 1e4f6d0bba9..8a552163083 100644 --- a/crates/rspack_ids/src/id_helpers.rs +++ b/crates/rspack_ids/src/id_helpers.rs @@ -16,6 +16,7 @@ use rspack_core::{ compare_runtime, BoxModule, Chunk, ChunkGraph, ChunkUkey, Compilation, ModuleGraph, ModuleIdentifier, }; +use rspack_util::itoa; use rspack_util::{ comparators::{compare_ids, compare_numbers}, identifier::make_paths_relative, @@ -229,10 +230,10 @@ pub fn assign_names_par( items.sort_unstable_by(&comparator); let mut i = 0; for item in items { - let mut formatted_name = format!("{name}{i}"); + let mut formatted_name = format!("{name}{}", itoa!(i)); while name_to_items_keys.contains(&formatted_name) && used_ids.contains(&formatted_name) { i += 1; - formatted_name = format!("{name}{i}"); + formatted_name = format!("{name}{}", itoa!(i)); } assign_name(item, formatted_name.clone()); used_ids.insert(formatted_name); @@ -275,10 +276,10 @@ pub fn assign_deterministic_ids( for item in items { let ident = get_name(item); let mut i = salt; - let mut id = get_number_hash(&format!("{ident}{i}"), range); + let mut id = get_number_hash(&format!("{ident}{}", itoa!(i)), range); while !assign_id(item, id) { i += 1; - id = get_number_hash(&format!("{ident}{i}"), range); + id = get_number_hash(&format!("{ident}{}", itoa!(i)), range); } } } diff --git a/crates/rspack_loader_swc/src/compiler.rs b/crates/rspack_loader_swc/src/compiler.rs index 4dc19807a3d..a02f4d2497e 100644 --- a/crates/rspack_loader_swc/src/compiler.rs +++ b/crates/rspack_loader_swc/src/compiler.rs @@ -16,6 +16,7 @@ use base64::prelude::*; use dashmap::DashMap; use jsonc_parser::parse_to_serde_value; use rspack_ast::javascript::{Ast as JsAst, Context as JsAstContext, Program as JsProgram}; +use rspack_util::itoa; use serde_json::error::Category; use swc_config::config_types::BoolOr; use swc_config::merge::Merge; @@ -89,7 +90,9 @@ fn parse_swcrc(s: &str) -> Result { }; Error::new(e).context(format!( "failed to deserialize .swcrc (json) file: {}: {}:{}", - msg, line, column + msg, + itoa!(line), + itoa!(column) )) } diff --git a/crates/rspack_plugin_css/src/utils.rs b/crates/rspack_plugin_css/src/utils.rs index 4c7cb7491b8..eda2c78c2f1 100644 --- a/crates/rspack_plugin_css/src/utils.rs +++ b/crates/rspack_plugin_css/src/utils.rs @@ -18,6 +18,7 @@ use rspack_error::{DiagnosticExt, RspackSeverity}; use rspack_hash::RspackHash; use rspack_util::identifier::make_paths_relative; use rspack_util::infallible::ResultInfallibleExt; +use rspack_util::itoa; use rspack_util::json_stringify; use rustc_hash::FxHashSet as HashSet; @@ -256,7 +257,7 @@ pub fn css_modules_exports_to_concatenate_module_string<'a>( let mut identifier = to_identifier(key); let mut i = 0; while used_identifiers.contains(&identifier) { - identifier = Cow::Owned(format!("{key}{i}")); + identifier = Cow::Owned(format!("{key}{}", itoa!(i))); i += 1; } // TODO: conditional support `const or var` after we finished runtimeTemplate utils diff --git a/crates/rspack_plugin_extract_css/src/css_module.rs b/crates/rspack_plugin_extract_css/src/css_module.rs index f34aa27c595..688463694b4 100644 --- a/crates/rspack_plugin_extract_css/src/css_module.rs +++ b/crates/rspack_plugin_extract_css/src/css_module.rs @@ -15,6 +15,7 @@ use rspack_error::Result; use rspack_error::{impl_empty_diagnosable_trait, Diagnostic}; use rspack_hash::{RspackHash, RspackHashDigest}; use rspack_util::ext::DynHash; +use rspack_util::itoa; use rustc_hash::FxHashSet; use crate::css_dependency::CssDependency; @@ -55,7 +56,7 @@ impl CssModule { let identifier__ = format!( "css|{}|{}|{}|{}|{}}}", dep.identifier, - dep.identifier_index, + itoa!(dep.identifier_index), dep.layer.as_deref().unwrap_or_default(), dep.supports.as_deref().unwrap_or_default(), dep.media.as_deref().unwrap_or_default(), @@ -110,7 +111,7 @@ impl Module for CssModule { "css {}{}{}{}{}", context.shorten(&self.identifier), if self.identifier_index > 0 { - format!("({})", self.identifier_index) + format!("({})", itoa!(self.identifier_index)) } else { "".into() }, diff --git a/crates/rspack_plugin_javascript/src/parser_and_generator/mod.rs b/crates/rspack_plugin_javascript/src/parser_and_generator/mod.rs index cb59d43c687..bfaf46bd5f5 100644 --- a/crates/rspack_plugin_javascript/src/parser_and_generator/mod.rs +++ b/crates/rspack_plugin_javascript/src/parser_and_generator/mod.rs @@ -12,6 +12,7 @@ use rspack_core::{ }; use rspack_error::miette::Diagnostic; use rspack_error::{DiagnosticExt, IntoTWithDiagnosticArray, Result, TWithDiagnosticArray}; +use rspack_util::itoa; use swc_core::common::comments::Comments; use swc_core::common::input::SourceFileInput; use swc_core::common::{FileName, Span, SyntaxContext}; @@ -370,6 +371,7 @@ impl ParserAndGenerator for JavaScriptParserAndGenerator { } } +// Todo(shulaoda): check if this can be removed fn span_to_location(span: Span, source: &str) -> Option { let r = ropey::Rope::from_str(source); let start = span.real_lo(); @@ -382,12 +384,19 @@ fn span_to_location(span: Span, source: &str) -> Option { let end_line = r.char_to_line(end_char_offset); let end_column = end_char_offset - r.line_to_char(end_line); if start_line == end_line { - Some(format!("{}:{start_column}-{end_column}", start_line + 1)) + Some(format!( + "{}:{}-{}", + itoa!(start_line + 1), + itoa!(start_column), + itoa!(end_column) + )) } else { Some(format!( - "{}:{start_column}-{}:{end_column}", - start_line + 1, - end_line + 1 + "{}:{}-{}:{}", + itoa!(start_line + 1), + itoa!(start_column), + itoa!(end_line + 1), + itoa!(end_column) )) } } diff --git a/crates/rspack_plugin_javascript/src/parser_plugin/compatibility_plugin.rs b/crates/rspack_plugin_javascript/src/parser_plugin/compatibility_plugin.rs index 63d39a7e4f7..4a706b5bc3e 100644 --- a/crates/rspack_plugin_javascript/src/parser_plugin/compatibility_plugin.rs +++ b/crates/rspack_plugin_javascript/src/parser_plugin/compatibility_plugin.rs @@ -1,6 +1,7 @@ use rspack_core::{ ConstDependency, ContextDependency, RealDependencyLocation, RuntimeGlobals, SpanExt, }; +use rspack_util::itoa; use swc_core::{common::Spanned, ecma::ast::CallExpr}; use super::JavascriptParserPlugin; @@ -107,7 +108,7 @@ impl JavascriptParserPlugin for CompatibilityPlugin { self.tag_nested_require_data( parser, ident.sym.to_string(), - format!("__nested_webpack_require_{start}_{end}__"), + format!("__nested_webpack_require_{}_{}__", itoa!(start), itoa!(end),), start, end, ); @@ -137,7 +138,7 @@ impl JavascriptParserPlugin for CompatibilityPlugin { self.tag_nested_require_data( parser, ident.sym.to_string(), - format!("__nested_webpack_require_{start}_{end}__"), + format!("__nested_webpack_require_{}_{}__", itoa!(start), itoa!(end),), start, end, ); @@ -156,7 +157,10 @@ impl JavascriptParserPlugin for CompatibilityPlugin { self.tag_nested_require_data( parser, name.to_string(), - format!("__nested_webpack_require_{}__", fn_decl.span().real_lo()), + format!( + "__nested_webpack_require_{}__", + itoa!(fn_decl.span().real_lo()) + ), ident.span().real_lo(), ident.span().real_hi(), ); diff --git a/crates/rspack_plugin_javascript/src/parser_plugin/define_plugin/mod.rs b/crates/rspack_plugin_javascript/src/parser_plugin/define_plugin/mod.rs index 9574ff72519..2da50cc43d5 100644 --- a/crates/rspack_plugin_javascript/src/parser_plugin/define_plugin/mod.rs +++ b/crates/rspack_plugin_javascript/src/parser_plugin/define_plugin/mod.rs @@ -14,6 +14,7 @@ use rspack_error::{ DiagnosticExt, Result, }; use rspack_hook::{plugin, plugin_hook}; +use rspack_util::itoa; use serde_json::Value; use crate::parser_and_generator::JavaScriptParserAndGenerator; @@ -72,7 +73,7 @@ async fn compilation( ) } else if let Some(value) = value.as_array() { let indexes = (0..value.len()) - .map(|index| format!("{}", index)) + .map(|index| itoa!(index).to_string()) .collect_vec(); let iter = indexes.iter().zip(value.iter()); walk_definitions(iter, compilation, Cow::Owned(format!("{prefix}{key}."))) diff --git a/crates/rspack_plugin_javascript/src/plugin/module_concatenation_plugin.rs b/crates/rspack_plugin_javascript/src/plugin/module_concatenation_plugin.rs index 41891378c9d..1ba8421a3f8 100644 --- a/crates/rspack_plugin_javascript/src/plugin/module_concatenation_plugin.rs +++ b/crates/rspack_plugin_javascript/src/plugin/module_concatenation_plugin.rs @@ -18,6 +18,7 @@ use rspack_core::{ }; use rspack_error::Result; use rspack_hook::{plugin, plugin_hook}; +use rspack_util::itoa; use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet}; fn format_bailout_reason(msg: &str) -> String { @@ -884,8 +885,8 @@ impl ModuleConcatenationPlugin { logger.time_end(start); logger.debug(format!( "{} potential root modules, {} potential inner modules", - relevant_modules.len(), - possible_inners.len(), + itoa!(relevant_modules.len()), + itoa!(possible_inners.len()), )); let start = logger.time("sort relevant modules"); @@ -996,25 +997,25 @@ impl ModuleConcatenationPlugin { if !concat_configurations.is_empty() { logger.debug(format!( "{} successful concat configurations (avg size: {}), {} bailed out completely", - concat_configurations.len(), - stats_size_sum / concat_configurations.len(), - stats_empty_configurations + itoa!(concat_configurations.len()), + itoa!(stats_size_sum / concat_configurations.len()), + itoa!(stats_empty_configurations) )); } logger.debug(format!( "{} candidates were considered for adding ({} cached failure, {} already in config, {} invalid module, {} incorrect chunks, {} incorrect dependency, {} incorrect chunks of importer, {} incorrect module dependency, {} incorrect runtime condition, {} importer failed, {} added)", - stats_candidates, - statistics.cached, - statistics.already_in_config, - statistics.invalid_module, - statistics.incorrect_chunks, - statistics.incorrect_dependency, - statistics.incorrect_chunks_of_importer, - statistics.incorrect_module_dependency, - statistics.incorrect_runtime_condition, - statistics.importer_failed, - statistics.added + itoa!(stats_candidates), + itoa!(statistics.cached), + itoa!(statistics.already_in_config), + itoa!(statistics.invalid_module), + itoa!(statistics.incorrect_chunks), + itoa!(statistics.incorrect_dependency), + itoa!(statistics.incorrect_chunks_of_importer), + itoa!(statistics.incorrect_module_dependency), + itoa!(statistics.incorrect_runtime_condition), + itoa!(statistics.importer_failed), + itoa!(statistics.added) )); // Copy from https://github.com/webpack/webpack/blob/1f99ad6367f2b8a6ef17cce0e058f7a67fb7db18/lib/optimize/ModuleConcatenationPlugin.js#L368-L371 diff --git a/crates/rspack_plugin_json/src/json_exports_dependency.rs b/crates/rspack_plugin_json/src/json_exports_dependency.rs index 4f95b408849..c18884bb07b 100644 --- a/crates/rspack_plugin_json/src/json_exports_dependency.rs +++ b/crates/rspack_plugin_json/src/json_exports_dependency.rs @@ -4,7 +4,7 @@ use rspack_core::{ DependencyTemplate, ExportNameOrSpec, ExportSpec, ExportsOfExportsSpec, ExportsSpec, ModuleGraph, RuntimeSpec, TemplateContext, TemplateReplaceSource, }; -use rspack_util::ext::DynHash; +use rspack_util::{ext::DynHash, itoa}; #[derive(Debug, Clone)] pub struct JsonExportsDependency { @@ -99,7 +99,7 @@ fn get_exports_from_data(data: &JsonValue) -> Option { .enumerate() .map(|(i, item)| { ExportNameOrSpec::ExportSpec(ExportSpec { - name: format!("{i}").into(), + name: itoa!(i).into(), can_mangle: Some(true), exports: get_exports_from_data(item).map(|item| match item { ExportsOfExportsSpec::True | ExportsOfExportsSpec::Null => unreachable!(), diff --git a/crates/rspack_plugin_json/src/lib.rs b/crates/rspack_plugin_json/src/lib.rs index 526d9b82dd7..579dabb52e5 100644 --- a/crates/rspack_plugin_json/src/lib.rs +++ b/crates/rspack_plugin_json/src/lib.rs @@ -21,6 +21,7 @@ use rspack_error::{ miette::diagnostic, DiagnosticExt, DiagnosticKind, IntoTWithDiagnosticArray, Result, TWithDiagnosticArray, TraceableError, }; +use rspack_util::itoa; use crate::json_exports_dependency::JsonExportsDependency; @@ -276,7 +277,7 @@ fn create_object_for_exports_info( .into_iter() .enumerate() .map(|(i, item)| { - let export_info = exports_info.get_read_only_export_info(mg, &format!("{i}").into()); + let export_info = exports_info.get_read_only_export_info(mg, &itoa!(i).into()); let used = export_info.get_used(mg, runtime); if used == UsageState::Unused { return None; diff --git a/crates/rspack_plugin_mf/src/container/container_reference_plugin.rs b/crates/rspack_plugin_mf/src/container/container_reference_plugin.rs index c1576cf9708..4343e718ed8 100644 --- a/crates/rspack_plugin_mf/src/container/container_reference_plugin.rs +++ b/crates/rspack_plugin_mf/src/container/container_reference_plugin.rs @@ -9,6 +9,7 @@ use rspack_core::{ }; use rspack_error::Result; use rspack_hook::{plugin, plugin_hook}; +use rspack_util::itoa; use super::{ fallback_module_factory::FallbackModuleFactory, remote_module::RemoteModule, @@ -90,7 +91,7 @@ async fn factorize(&self, data: &mut ModuleFactoryCreateData) -> Result 0) - .then(|| format!("/fallback-{}", i)) + .then(|| format!("/fallback-{}", itoa!(i))) .unwrap_or_default() ) } diff --git a/crates/rspack_plugin_mf/src/container/fallback_module.rs b/crates/rspack_plugin_mf/src/container/fallback_module.rs index 942808dc8bb..b6b7be43816 100644 --- a/crates/rspack_plugin_mf/src/container/fallback_module.rs +++ b/crates/rspack_plugin_mf/src/container/fallback_module.rs @@ -11,7 +11,7 @@ use rspack_core::{ RuntimeSpec, SourceType, }; use rspack_error::{impl_empty_diagnosable_trait, Diagnostic, Result}; -use rspack_util::source_map::SourceMapKind; +use rspack_util::{itoa, source_map::SourceMapKind}; use super::fallback_item_dependency::FallbackItemDependency; use crate::utils::json_stringify; @@ -38,7 +38,7 @@ impl FallbackModule { requests .first() .expect("should have at one more requests in FallbackModule"), - requests.len() - 1 + itoa!(requests.len() - 1) ); Self { blocks: Default::default(), diff --git a/crates/rspack_plugin_runtime/src/module_chunk_format.rs b/crates/rspack_plugin_runtime/src/module_chunk_format.rs index 19e77a6ebc1..622416d87ac 100644 --- a/crates/rspack_plugin_runtime/src/module_chunk_format.rs +++ b/crates/rspack_plugin_runtime/src/module_chunk_format.rs @@ -13,6 +13,7 @@ use rspack_plugin_javascript::runtime::render_chunk_runtime_modules; use rspack_plugin_javascript::{ JavascriptModulesChunkHash, JavascriptModulesRenderChunk, JsPlugin, RenderSource, }; +use rspack_util::itoa; use rustc_hash::FxHashSet as HashSet; use super::update_hash_for_entry_startup; @@ -167,12 +168,14 @@ fn render_chunk( let chunk = compilation.chunk_by_ukey.expect_get(chunk_ukey); let other_chunk_output_name = get_chunk_output_name(chunk, compilation)?; startup_source.push(format!( - "import * as __webpack_chunk_${index}__ from '{}';", + "import * as __webpack_chunk_${}__ from '{}';", + itoa!(index), get_relative_path(&base_chunk_output_name, &other_chunk_output_name) )); startup_source.push(format!( - "{}(__webpack_chunk_${index}__);", - RuntimeGlobals::EXTERNAL_INSTALL_CHUNK + "{}(__webpack_chunk_${}__);", + RuntimeGlobals::EXTERNAL_INSTALL_CHUNK, + itoa!(index) )); } diff --git a/crates/rspack_plugin_runtime/src/runtime_module/get_chunk_filename.rs b/crates/rspack_plugin_runtime/src/runtime_module/get_chunk_filename.rs index 92a898756f9..67961116733 100644 --- a/crates/rspack_plugin_runtime/src/runtime_module/get_chunk_filename.rs +++ b/crates/rspack_plugin_runtime/src/runtime_module/get_chunk_filename.rs @@ -9,7 +9,7 @@ use rspack_core::{ Chunk, ChunkUkey, Compilation, Filename, FilenameTemplate, PathData, RuntimeGlobals, RuntimeModule, SourceType, }; -use rspack_util::infallible::ResultInfallibleExt; +use rspack_util::{infallible::ResultInfallibleExt, itoa}; use rustc_hash::FxHashMap; use super::create_fake_chunk; @@ -221,7 +221,7 @@ impl RuntimeModule for GetChunkFilenameRuntimeModule { Some(hash_len) => format!( "\" + {}().slice(0, {}) + \"", RuntimeGlobals::GET_FULL_HASH, - hash_len + itoa!(*hash_len) ), None => format!("\" + {}() + \"", RuntimeGlobals::GET_FULL_HASH), }; @@ -292,7 +292,7 @@ impl RuntimeModule for GetChunkFilenameRuntimeModule { Some(hash_len) => format!( "\" + {}().slice(0, {}) + \"", RuntimeGlobals::GET_FULL_HASH, - hash_len + itoa!(*hash_len) ), None => format!("\" + {}() + \"", RuntimeGlobals::GET_FULL_HASH), }; diff --git a/crates/rspack_plugin_wasm/src/parser_and_generator.rs b/crates/rspack_plugin_wasm/src/parser_and_generator.rs index 88e0d9749b8..8f2cea3f1fa 100644 --- a/crates/rspack_plugin_wasm/src/parser_and_generator.rs +++ b/crates/rspack_plugin_wasm/src/parser_and_generator.rs @@ -14,6 +14,7 @@ use rspack_core::{ }; use rspack_error::{Diagnostic, IntoTWithDiagnosticArray, Result, TWithDiagnosticArray}; use rspack_util::infallible::ResultInfallibleExt as _; +use rspack_util::itoa; use swc_core::atoms::Atom; use wasmparser::{Import, Parser, Payload}; @@ -169,7 +170,7 @@ impl ParserAndGenerator for AsyncWasmParserAndGenerator { .for_each(|(dep, mgm)| { if let Some(mgm) = mgm { if !dep_modules.contains_key(&mgm.module_identifier) { - let import_var = format!("WEBPACK_IMPORTED_MODULE_{}", dep_modules.len()); + let import_var = format!("WEBPACK_IMPORTED_MODULE_{}", itoa!(dep_modules.len())); let val = (import_var.clone(), mgm.id(chunk_graph)); if matches!(module_graph.is_async(&mgm.module_identifier), Some(true)) { diff --git a/crates/rspack_plugin_wasm/src/runtime.rs b/crates/rspack_plugin_wasm/src/runtime.rs index da96f6442bb..ea28c2e58b9 100644 --- a/crates/rspack_plugin_wasm/src/runtime.rs +++ b/crates/rspack_plugin_wasm/src/runtime.rs @@ -5,6 +5,7 @@ use rspack_core::{ RuntimeModule, RuntimeModuleStage, }; use rspack_util::infallible::ResultInfallibleExt as _; +use rspack_util::itoa; #[impl_runtime_module] #[derive(Debug)] @@ -43,7 +44,7 @@ impl RuntimeModule for AsyncWasmLoadingRuntimeModule { .get("[contenthash]") .or(hash_len_map.get("[hash]")) { - Some(hash_len) => format!("\" + wasmModuleHash.slice(0, {}) + \"", hash_len), + Some(hash_len) => format!("\" + wasmModuleHash.slice(0, {}) + \"", itoa!(*hash_len)), None => "\" + wasmModuleHash + \"".to_string(), }; diff --git a/crates/rspack_util/Cargo.toml b/crates/rspack_util/Cargo.toml index e30792d6829..59d1040fbfc 100644 --- a/crates/rspack_util/Cargo.toml +++ b/crates/rspack_util/Cargo.toml @@ -13,6 +13,7 @@ bitflags = { workspace = true } concat-string = { workspace = true } dashmap = { workspace = true } indexmap = { workspace = true } +itoa = { version = "1.0.11" } regex = { workspace = true } rustc-hash = { workspace = true } serde = { workspace = true } diff --git a/crates/rspack_util/src/itoa.rs b/crates/rspack_util/src/itoa.rs new file mode 100644 index 00000000000..2eb68ec1044 --- /dev/null +++ b/crates/rspack_util/src/itoa.rs @@ -0,0 +1,8 @@ +pub use itoa::Buffer; + +#[macro_export] +macro_rules! itoa { + ($i:expr) => {{ + $crate::itoa::Buffer::new().format($i) + }}; +} diff --git a/crates/rspack_util/src/lib.rs b/crates/rspack_util/src/lib.rs index e223fe39dea..007527f340f 100644 --- a/crates/rspack_util/src/lib.rs +++ b/crates/rspack_util/src/lib.rs @@ -10,6 +10,7 @@ pub mod ext; pub mod fx_hash; pub mod identifier; pub mod infallible; +pub mod itoa; pub mod number_hash; pub mod path; pub mod queue;