cargo clippy --fix

This commit is contained in:
Luke Street 2025-06-01 16:42:00 -06:00
parent f212b35d28
commit 88d0e6b789
36 changed files with 181 additions and 187 deletions

View File

@ -191,7 +191,7 @@ impl AnalyzerState {
}; };
obj.add_symbol( obj.add_symbol(
ObjSymbol { ObjSymbol {
name: format!("jumptable_{}", address_str), name: format!("jumptable_{address_str}"),
address: addr.address as u64, address: addr.address as u64,
section: Some(addr.section), section: Some(addr.section),
size: size as u64, size: size as u64,
@ -275,7 +275,7 @@ impl AnalyzerState {
let (section_index, _) = obj let (section_index, _) = obj
.sections .sections
.at_address(entry) .at_address(entry)
.context(format!("Entry point {:#010X} outside of any section", entry))?; .context(format!("Entry point {entry:#010X} outside of any section"))?;
self.process_function_at(obj, SectionAddress::new(section_index, entry))?; self.process_function_at(obj, SectionAddress::new(section_index, entry))?;
} }
// Locate bounds for referenced functions until none are left // Locate bounds for referenced functions until none are left
@ -530,7 +530,7 @@ pub fn locate_sda_bases(obj: &mut ObjInfo) -> Result<bool> {
let (section_index, _) = obj let (section_index, _) = obj
.sections .sections
.at_address(entry as u32) .at_address(entry as u32)
.context(format!("Entry point {:#010X} outside of any section", entry))?; .context(format!("Entry point {entry:#010X} outside of any section"))?;
let entry_addr = SectionAddress::new(section_index, entry as u32); let entry_addr = SectionAddress::new(section_index, entry as u32);
let mut executor = Executor::new(obj); let mut executor = Executor::new(obj);
@ -589,7 +589,7 @@ pub fn locate_bss_memsets(obj: &mut ObjInfo) -> Result<Vec<(u32, u32)>> {
let (section_index, _) = obj let (section_index, _) = obj
.sections .sections
.at_address(entry as u32) .at_address(entry as u32)
.context(format!("Entry point {:#010X} outside of any section", entry))?; .context(format!("Entry point {entry:#010X} outside of any section"))?;
let entry_addr = SectionAddress::new(section_index, entry as u32); let entry_addr = SectionAddress::new(section_index, entry as u32);
let mut executor = Executor::new(obj); let mut executor = Executor::new(obj);

View File

@ -183,8 +183,7 @@ fn get_jump_table_entries(
let (section_index, _) = let (section_index, _) =
obj.sections.at_address(entry_addr).with_context(|| { obj.sections.at_address(entry_addr).with_context(|| {
format!( format!(
"Invalid jump table entry {:#010X} at {:#010X}", "Invalid jump table entry {entry_addr:#010X} at {cur_addr:#010X}"
entry_addr, cur_addr
) )
})?; })?;
entries.push(SectionAddress::new(section_index, entry_addr)); entries.push(SectionAddress::new(section_index, entry_addr));

View File

@ -101,7 +101,7 @@ impl AnalysisPass for FindSaveRestSleds {
for i in reg_start..reg_end { for i in reg_start..reg_end {
let addr = start + (i - reg_start) * step_size; let addr = start + (i - reg_start) * step_size;
state.known_symbols.entry(addr).or_default().push(ObjSymbol { state.known_symbols.entry(addr).or_default().push(ObjSymbol {
name: format!("{}{}", label, i), name: format!("{label}{i}"),
address: addr.address as u64, address: addr.address as u64,
section: Some(start.section), section: Some(start.section),
size_known: true, size_known: true,

View File

@ -227,7 +227,7 @@ impl FunctionSlices {
})?; })?;
} }
self.check_epilogue(section, ins_addr, ins) self.check_epilogue(section, ins_addr, ins)
.with_context(|| format!("While processing {:#010X}: {:#?}", function_start, self))?; .with_context(|| format!("While processing {function_start:#010X}: {self:#?}"))?;
if !self.has_conditional_blr && is_conditional_blr(ins) { if !self.has_conditional_blr && is_conditional_blr(ins) {
self.has_conditional_blr = true; self.has_conditional_blr = true;
} }

View File

@ -576,7 +576,7 @@ impl Tracker {
let relocation_target = relocation_target_for(obj, from, None).ok().flatten(); let relocation_target = relocation_target_for(obj, from, None).ok().flatten();
if !matches!(relocation_target, None | Some(RelocationTarget::External)) { if !matches!(relocation_target, None | Some(RelocationTarget::External)) {
// VM should have already handled this // VM should have already handled this
panic!("Relocation already exists for {:#010X} (from {:#010X})", addr, from); panic!("Relocation already exists for {addr:#010X} (from {from:#010X})");
} }
} }
// Remainder of this function is for executable objects only // Remainder of this function is for executable objects only
@ -668,7 +668,7 @@ impl Tracker {
0 0
}; };
let new_name = let new_name =
if module_id == 0 { name.to_string() } else { format!("{}:{}", name, module_id) }; if module_id == 0 { name.to_string() } else { format!("{name}:{module_id}") };
log::debug!("Renaming {} to {}", section.name, new_name); log::debug!("Renaming {} to {}", section.name, new_name);
section.name = new_name; section.name = new_name;
} }

View File

@ -127,16 +127,16 @@ fn extract(args: ExtractArgs) -> Result<()> {
} }
std::fs::create_dir_all(&out_dir)?; std::fs::create_dir_all(&out_dir)?;
if !args.quiet { if !args.quiet {
println!("Extracting {} to {}", path, out_dir); println!("Extracting {path} to {out_dir}");
} }
let mut file = open_file(path, false)?; let mut file = open_file(path, false)?;
let mut archive = ar::Archive::new(file.map()?); let mut archive = ar::Archive::new(file.map()?);
while let Some(entry) = archive.next_entry() { while let Some(entry) = archive.next_entry() {
let mut entry = entry.with_context(|| format!("Processing entry in {}", path))?; let mut entry = entry.with_context(|| format!("Processing entry in {path}"))?;
let file_name = std::str::from_utf8(entry.header().identifier())?; let file_name = std::str::from_utf8(entry.header().identifier())?;
if !args.quiet && args.verbose { if !args.quiet && args.verbose {
println!("\t{}", file_name); println!("\t{file_name}");
} }
let mut file_path = out_dir.clone(); let mut file_path = out_dir.clone();
for segment in file_name.split(&['/', '\\']) { for segment in file_name.split(&['/', '\\']) {
@ -146,7 +146,7 @@ fn extract(args: ExtractArgs) -> Result<()> {
std::fs::create_dir_all(parent)?; std::fs::create_dir_all(parent)?;
} }
let mut file = File::create(&file_path) let mut file = File::create(&file_path)
.with_context(|| format!("Failed to create file {}", file_path))?; .with_context(|| format!("Failed to create file {file_path}"))?;
std::io::copy(&mut entry, &mut file)?; std::io::copy(&mut entry, &mut file)?;
file.flush()?; file.flush()?;
@ -154,7 +154,7 @@ fn extract(args: ExtractArgs) -> Result<()> {
} }
} }
if !args.quiet { if !args.quiet {
println!("Extracted {} files", num_files); println!("Extracted {num_files} files");
} }
Ok(()) Ok(())
} }

View File

@ -536,7 +536,7 @@ pub fn info(args: InfoArgs) -> Result<()> {
println!("{}:", obj.name); println!("{}:", obj.name);
if let Some(entry) = obj.entry { if let Some(entry) = obj.entry {
println!("Entry point: {:#010X}", entry); println!("Entry point: {entry:#010X}");
} }
println!("\nSections:"); println!("\nSections:");
println!("\t{: >10} | {: <10} | {: <10} | {: <10}", "Name", "Address", "Size", "File Off"); println!("\t{: >10} | {: <10} | {: <10} | {: <10}", "Name", "Address", "Size", "File Off");
@ -955,7 +955,7 @@ fn split_write_obj(
DirBuilder::new() DirBuilder::new()
.recursive(true) .recursive(true)
.create(out_dir) .create(out_dir)
.with_context(|| format!("Failed to create out dir '{}'", out_dir))?; .with_context(|| format!("Failed to create out dir '{out_dir}'"))?;
let obj_dir = out_dir.join("obj"); let obj_dir = out_dir.join("obj");
let entry = if module.obj.kind == ObjKind::Executable { let entry = if module.obj.kind == ObjKind::Executable {
module.obj.entry.and_then(|e| { module.obj.entry.and_then(|e| {
@ -1056,9 +1056,8 @@ fn split_write_obj(
// Generate ldscript.lcf // Generate ldscript.lcf
let ldscript_template = if let Some(template_path) = &module.config.ldscript_template { let ldscript_template = if let Some(template_path) = &module.config.ldscript_template {
let template_path = template_path.with_encoding(); let template_path = template_path.with_encoding();
let template = fs::read_to_string(&template_path).with_context(|| { let template = fs::read_to_string(&template_path)
format!("Failed to read linker script template '{}'", template_path) .with_context(|| format!("Failed to read linker script template '{template_path}'"))?;
})?;
module.dep.push(template_path); module.dep.push(template_path);
Some(template) Some(template)
} else { } else {
@ -1076,8 +1075,7 @@ fn split_write_obj(
let out_path = asm_dir.join(asm_path_for_unit(&unit.name)); let out_path = asm_dir.join(asm_path_for_unit(&unit.name));
let mut w = buf_writer(&out_path)?; let mut w = buf_writer(&out_path)?;
write_asm(&mut w, split_obj) write_asm(&mut w, split_obj).with_context(|| format!("Failed to write {out_path}"))?;
.with_context(|| format!("Failed to write {}", out_path))?;
w.flush()?; w.flush()?;
} }
} }
@ -1094,7 +1092,7 @@ fn write_if_changed(path: &Utf8NativePath, contents: &[u8]) -> Result<()> {
return Ok(()); return Ok(());
} }
} }
fs::write(path, contents).with_context(|| format!("Failed to write file '{}'", path))?; fs::write(path, contents).with_context(|| format!("Failed to write file '{path}'"))?;
Ok(()) Ok(())
} }
@ -2166,7 +2164,7 @@ impl ObjectBase {
} }
base.join(path.with_encoding()) base.join(path.with_encoding())
} }
ObjectBase::Vfs(base, _) => Utf8NativePathBuf::from(format!("{}:{}", base, path)), ObjectBase::Vfs(base, _) => Utf8NativePathBuf::from(format!("{base}:{path}")),
} }
} }
@ -2183,7 +2181,7 @@ impl ObjectBase {
} }
ObjectBase::Vfs(vfs_path, vfs) => { ObjectBase::Vfs(vfs_path, vfs) => {
open_file_with_fs(vfs.clone(), &path.with_encoding(), true) open_file_with_fs(vfs.clone(), &path.with_encoding(), true)
.with_context(|| format!("Using disc image {}", vfs_path)) .with_context(|| format!("Using disc image {vfs_path}"))
} }
} }
} }
@ -2201,18 +2199,18 @@ pub fn find_object_base(config: &ProjectConfig) -> Result<ObjectBase> {
if let Some(base) = &config.object_base { if let Some(base) = &config.object_base {
let base = base.with_encoding(); let base = base.with_encoding();
// Search for disc images in the object base directory // Search for disc images in the object base directory
for result in fs::read_dir(&base).with_context(|| format!("Reading directory {}", base))? { for result in fs::read_dir(&base).with_context(|| format!("Reading directory {base}"))? {
let entry = result.with_context(|| format!("Reading entry in directory {}", base))?; let entry = result.with_context(|| format!("Reading entry in directory {base}"))?;
let Ok(path) = check_path_buf(entry.path()) else { let Ok(path) = check_path_buf(entry.path()) else {
log::warn!("Path is not valid UTF-8: {:?}", entry.path()); log::warn!("Path is not valid UTF-8: {:?}", entry.path());
continue; continue;
}; };
let file_type = let file_type =
entry.file_type().with_context(|| format!("Getting file type for {}", path))?; entry.file_type().with_context(|| format!("Getting file type for {path}"))?;
let is_file = if file_type.is_symlink() { let is_file = if file_type.is_symlink() {
// Also traverse symlinks to files // Also traverse symlinks to files
fs::metadata(&path) fs::metadata(&path)
.with_context(|| format!("Getting metadata for {}", path))? .with_context(|| format!("Getting metadata for {path}"))?
.is_file() .is_file()
} else { } else {
file_type.is_file() file_type.is_file()
@ -2220,7 +2218,7 @@ pub fn find_object_base(config: &ProjectConfig) -> Result<ObjectBase> {
if is_file { if is_file {
let mut file = open_file(&path, false)?; let mut file = open_file(&path, false)?;
let format = detect(file.as_mut()) let format = detect(file.as_mut())
.with_context(|| format!("Detecting file type for {}", path))?; .with_context(|| format!("Detecting file type for {path}"))?;
match format { match format {
FileFormat::Archive(ArchiveKind::Disc(format)) => { FileFormat::Archive(ArchiveKind::Disc(format)) => {
let fs = open_fs(file, ArchiveKind::Disc(format))?; let fs = open_fs(file, ArchiveKind::Disc(format))?;
@ -2249,7 +2247,7 @@ fn extract_objects(config: &ProjectConfig, object_base: &ObjectBase) -> Result<U
{ {
let target_path = extracted_path(&target_dir, &config.base.object); let target_path = extracted_path(&target_dir, &config.base.object);
if !fs::exists(&target_path) if !fs::exists(&target_path)
.with_context(|| format!("Failed to check path '{}'", target_path))? .with_context(|| format!("Failed to check path '{target_path}'"))?
{ {
object_paths.push((&config.base.object, config.base.hash.as_deref(), target_path)); object_paths.push((&config.base.object, config.base.hash.as_deref(), target_path));
} }
@ -2257,7 +2255,7 @@ fn extract_objects(config: &ProjectConfig, object_base: &ObjectBase) -> Result<U
if let Some(selfile) = &config.selfile { if let Some(selfile) = &config.selfile {
let target_path = extracted_path(&target_dir, selfile); let target_path = extracted_path(&target_dir, selfile);
if !fs::exists(&target_path) if !fs::exists(&target_path)
.with_context(|| format!("Failed to check path '{}'", target_path))? .with_context(|| format!("Failed to check path '{target_path}'"))?
{ {
object_paths.push((selfile, config.selfile_hash.as_deref(), target_path)); object_paths.push((selfile, config.selfile_hash.as_deref(), target_path));
} }
@ -2265,7 +2263,7 @@ fn extract_objects(config: &ProjectConfig, object_base: &ObjectBase) -> Result<U
for module_config in &config.modules { for module_config in &config.modules {
let target_path = extracted_path(&target_dir, &module_config.object); let target_path = extracted_path(&target_dir, &module_config.object);
if !fs::exists(&target_path) if !fs::exists(&target_path)
.with_context(|| format!("Failed to check path '{}'", target_path))? .with_context(|| format!("Failed to check path '{target_path}'"))?
{ {
object_paths.push((&module_config.object, module_config.hash.as_deref(), target_path)); object_paths.push((&module_config.object, module_config.hash.as_deref(), target_path));
} }
@ -2284,12 +2282,12 @@ fn extract_objects(config: &ProjectConfig, object_base: &ObjectBase) -> Result<U
let mut file = object_base.open(source_path)?; let mut file = object_base.open(source_path)?;
if let Some(parent) = target_path.parent() { if let Some(parent) = target_path.parent() {
fs::create_dir_all(parent) fs::create_dir_all(parent)
.with_context(|| format!("Failed to create directory '{}'", parent))?; .with_context(|| format!("Failed to create directory '{parent}'"))?;
} }
let mut out = fs::File::create(&target_path) let mut out = fs::File::create(&target_path)
.with_context(|| format!("Failed to create file '{}'", target_path))?; .with_context(|| format!("Failed to create file '{target_path}'"))?;
let hash_bytes = buf_copy_with_hash(&mut file, &mut out) let hash_bytes = buf_copy_with_hash(&mut file, &mut out)
.with_context(|| format!("Failed to extract file '{}'", target_path))?; .with_context(|| format!("Failed to extract file '{target_path}'"))?;
if let Some(hash) = hash { if let Some(hash) = hash {
check_hash_str(hash_bytes, hash).with_context(|| { check_hash_str(hash_bytes, hash).with_context(|| {
format!("Source file failed verification: '{}'", object_base.join(source_path)) format!("Source file failed verification: '{}'", object_base.join(source_path))

View File

@ -104,16 +104,16 @@ fn dump(args: DumpArgs) -> Result<()> {
// TODO make a basename method // TODO make a basename method
let name = name.trim_start_matches("D:").replace('\\', "/"); let name = name.trim_start_matches("D:").replace('\\', "/");
let name = name.rsplit_once('/').map(|(_, b)| b).unwrap_or(&name); let name = name.rsplit_once('/').map(|(_, b)| b).unwrap_or(&name);
let file_path = out_path.join(format!("{}.txt", name)); let file_path = out_path.join(format!("{name}.txt"));
let mut file = buf_writer(&file_path)?; let mut file = buf_writer(&file_path)?;
dump_debug_section(&args, &mut file, &obj_file, debug_section)?; dump_debug_section(&args, &mut file, &obj_file, debug_section)?;
file.flush()?; file.flush()?;
} else if args.no_color { } else if args.no_color {
println!("\n// File {}:", name); println!("\n// File {name}:");
dump_debug_section(&args, &mut stdout(), &obj_file, debug_section)?; dump_debug_section(&args, &mut stdout(), &obj_file, debug_section)?;
} else { } else {
let mut writer = HighlightWriter::new(syntax_set.clone(), syntax.clone(), theme); let mut writer = HighlightWriter::new(syntax_set.clone(), syntax.clone(), theme);
writeln!(writer, "\n// File {}:", name)?; writeln!(writer, "\n// File {name}:")?;
dump_debug_section(&args, &mut writer, &obj_file, debug_section)?; dump_debug_section(&args, &mut writer, &obj_file, debug_section)?;
} }
} }
@ -209,26 +209,25 @@ where
} }
writeln!(w, "\n/*\n Compile unit: {}", unit.name)?; writeln!(w, "\n/*\n Compile unit: {}", unit.name)?;
if let Some(producer) = unit.producer { if let Some(producer) = unit.producer {
writeln!(w, " Producer: {}", producer)?; writeln!(w, " Producer: {producer}")?;
} }
if let Some(comp_dir) = unit.comp_dir { if let Some(comp_dir) = unit.comp_dir {
writeln!(w, " Compile directory: {}", comp_dir)?; writeln!(w, " Compile directory: {comp_dir}")?;
} }
if let Some(language) = unit.language { if let Some(language) = unit.language {
writeln!(w, " Language: {}", language)?; writeln!(w, " Language: {language}")?;
} }
if let (Some(start), Some(end)) = (unit.start_address, unit.end_address) { if let (Some(start), Some(end)) = (unit.start_address, unit.end_address) {
writeln!(w, " Code range: {:#010X} -> {:#010X}", start, end)?; writeln!(w, " Code range: {start:#010X} -> {end:#010X}")?;
} }
if let Some(gcc_srcfile_name_offset) = unit.gcc_srcfile_name_offset { if let Some(gcc_srcfile_name_offset) = unit.gcc_srcfile_name_offset {
writeln!( writeln!(
w, w,
" GCC Source File Name Offset: {:#010X}", " GCC Source File Name Offset: {gcc_srcfile_name_offset:#010X}"
gcc_srcfile_name_offset
)?; )?;
} }
if let Some(gcc_srcinfo_offset) = unit.gcc_srcinfo_offset { if let Some(gcc_srcinfo_offset) = unit.gcc_srcinfo_offset {
writeln!(w, " GCC Source Info Offset: {:#010X}", gcc_srcinfo_offset)?; writeln!(w, " GCC Source Info Offset: {gcc_srcinfo_offset:#010X}")?;
} }
writeln!(w, "*/")?; writeln!(w, "*/")?;
@ -269,7 +268,7 @@ where
continue; continue;
} }
match tag_type_string(&info, &typedefs, &tag_type, child.is_erased) { match tag_type_string(&info, &typedefs, &tag_type, child.is_erased) {
Ok(s) => writeln!(w, "{}", s)?, Ok(s) => writeln!(w, "{s}")?,
Err(e) => { Err(e) => {
log::error!( log::error!(
"Failed to emit tag {:X} (unit {}): {}", "Failed to emit tag {:X} (unit {}): {}",

View File

@ -146,14 +146,14 @@ fn disasm(args: DisasmArgs) -> Result<()> {
let mut files_out = buf_writer(&args.out.join("link_order.txt"))?; let mut files_out = buf_writer(&args.out.join("link_order.txt"))?;
for (unit, split_obj) in obj.link_order.iter().zip(&split_objs) { for (unit, split_obj) in obj.link_order.iter().zip(&split_objs) {
let out_name = file_stem_from_unit(&unit.name); let out_name = file_stem_from_unit(&unit.name);
let out_path = asm_dir.join(format!("{}.s", out_name)); let out_path = asm_dir.join(format!("{out_name}.s"));
log::info!("Writing {}", out_path); log::info!("Writing {}", out_path);
let mut w = buf_writer(&out_path)?; let mut w = buf_writer(&out_path)?;
write_asm(&mut w, split_obj)?; write_asm(&mut w, split_obj)?;
w.flush()?; w.flush()?;
writeln!(files_out, "{}.o", out_name)?; writeln!(files_out, "{out_name}.o")?;
} }
files_out.flush()?; files_out.flush()?;
} }
@ -402,7 +402,7 @@ fn signatures(args: SignaturesArgs) -> Result<()> {
Ok(Some(signature)) => signature, Ok(Some(signature)) => signature,
Ok(None) => continue, Ok(None) => continue,
Err(e) => { Err(e) => {
eprintln!("Failed: {:?}", e); eprintln!("Failed: {e:?}");
continue; continue;
} }
}; };
@ -545,13 +545,13 @@ fn info(args: InfoArgs) -> Result<()> {
.context("While reading .note.split section")?; .context("While reading .note.split section")?;
println!("\nSplit metadata (.note.split):"); println!("\nSplit metadata (.note.split):");
if let Some(generator) = &meta.generator { if let Some(generator) = &meta.generator {
println!("\tGenerator: {}", generator); println!("\tGenerator: {generator}");
} }
if let Some(module_name) = &meta.module_name { if let Some(module_name) = &meta.module_name {
println!("\tModule name: {}", module_name); println!("\tModule name: {module_name}");
} }
if let Some(module_id) = meta.module_id { if let Some(module_id) = meta.module_id {
println!("\tModule ID: {}", module_id); println!("\tModule ID: {module_id}");
} }
if let Some(virtual_addresses) = &meta.virtual_addresses { if let Some(virtual_addresses) = &meta.virtual_addresses {
println!("\tVirtual addresses:"); println!("\tVirtual addresses:");

View File

@ -175,7 +175,7 @@ fn symbol(args: SymbolArgs) -> Result<()> {
if let Some(vec) = entries.unit_references.get_vec(&symbol_ref) { if let Some(vec) = entries.unit_references.get_vec(&symbol_ref) {
println!("\nGenerated in TUs:"); println!("\nGenerated in TUs:");
for x in vec { for x in vec {
println!(">>> {}", x); println!(">>> {x}");
} }
} }
println!("\n"); println!("\n");

View File

@ -59,7 +59,7 @@ fn decompress(args: DecompressArgs) -> Result<()> {
path.as_path().to_cow() path.as_path().to_cow()
}; };
fs::write(out_path.as_ref(), data) fs::write(out_path.as_ref(), data)
.with_context(|| format!("Failed to write '{}'", out_path))?; .with_context(|| format!("Failed to write '{out_path}'"))?;
} }
Ok(()) Ok(())
} }

View File

@ -316,7 +316,7 @@ fn make(args: MakeArgs) -> Result<()> {
.unwrap_or(idx as u32); .unwrap_or(idx as u32);
load_obj(file.map()?) load_obj(file.map()?)
.map(|o| LoadedModule { module_id, file: o, path: path.clone() }) .map(|o| LoadedModule { module_id, file: o, path: path.clone() })
.with_context(|| format!("Failed to load '{}'", path)) .with_context(|| format!("Failed to load '{path}'"))
}) })
.collect::<Result<Vec<_>>>()?; .collect::<Result<Vec<_>>>()?;
@ -395,7 +395,7 @@ fn make(args: MakeArgs) -> Result<()> {
let rel_path = module_info.path.with_extension("rel"); let rel_path = module_info.path.with_extension("rel");
let mut w = buf_writer(&rel_path)?; let mut w = buf_writer(&rel_path)?;
write_rel(&mut w, &info, &module_info.file, relocations) write_rel(&mut w, &info, &module_info.file, relocations)
.with_context(|| format!("Failed to write '{}'", rel_path))?; .with_context(|| format!("Failed to write '{rel_path}'"))?;
w.flush()?; w.flush()?;
} }

View File

@ -143,7 +143,7 @@ fn make_rso(
let si = sym let si = sym
.section_index() .section_index()
.with_context(|| format!("Failed to find symbol `{}` section index", name))?; .with_context(|| format!("Failed to find symbol `{name}` section index"))?;
let addr = sym.address(); let addr = sym.address();
*index = si.0 as u8; *index = si.0 as u8;

View File

@ -45,14 +45,13 @@ pub fn run(args: Args) -> Result<()> {
check(&args, file.as_mut())?; check(&args, file.as_mut())?;
} }
if let Some(out_path) = &args.output { if let Some(out_path) = &args.output {
touch(out_path) touch(out_path).with_context(|| format!("Failed to touch output file '{out_path}'"))?;
.with_context(|| format!("Failed to touch output file '{}'", out_path))?;
} }
} else { } else {
let mut w: Box<dyn Write> = if let Some(out_path) = &args.output { let mut w: Box<dyn Write> = if let Some(out_path) = &args.output {
Box::new( Box::new(
buf_writer(out_path) buf_writer(out_path)
.with_context(|| format!("Failed to open output file '{}'", out_path))?, .with_context(|| format!("Failed to open output file '{out_path}'"))?,
) )
} else { } else {
Box::new(stdout()) Box::new(stdout())

View File

@ -85,7 +85,7 @@ fn file_info(
metadata: &VfsMetadata, metadata: &VfsMetadata,
) -> anyhow::Result<Columns<5>> { ) -> anyhow::Result<Columns<5>> {
let format = let format =
detect(file).with_context(|| format!("Failed to detect file format for {}", filename))?; detect(file).with_context(|| format!("Failed to detect file format for {filename}"))?;
let mut info: Columns<5> = [ let mut info: Columns<5> = [
Size::from_bytes(metadata.len).to_string(), Size::from_bytes(metadata.len).to_string(),
filename.to_string(), filename.to_string(),
@ -97,9 +97,9 @@ fn file_info(
let mut decompressed = decompress_file(file, kind)?; let mut decompressed = decompress_file(file, kind)?;
let metadata = decompressed let metadata = decompressed
.metadata() .metadata()
.with_context(|| format!("Failed to fetch metadata for {}", filename))?; .with_context(|| format!("Failed to fetch metadata for {filename}"))?;
let format = detect(decompressed.as_mut()) let format = detect(decompressed.as_mut())
.with_context(|| format!("Failed to detect file format for {}", filename))?; .with_context(|| format!("Failed to detect file format for {filename}"))?;
info[3] = format!("Decompressed: {}", Size::from_bytes(metadata.len)); info[3] = format!("Decompressed: {}", Size::from_bytes(metadata.len));
info[4] = format.to_string(); info[4] = format.to_string();
} }
@ -112,11 +112,11 @@ pub fn ls(args: LsArgs) -> anyhow::Result<()> {
OpenResult::File(mut file, path) => { OpenResult::File(mut file, path) => {
let filename = path.file_name().ok_or_else(|| anyhow!("Path has no filename"))?; let filename = path.file_name().ok_or_else(|| anyhow!("Path has no filename"))?;
if args.short { if args.short {
println!("{}", filename); println!("{filename}");
} else { } else {
let metadata = file let metadata = file
.metadata() .metadata()
.with_context(|| format!("Failed to fetch metadata for {}", path))?; .with_context(|| format!("Failed to fetch metadata for {path}"))?;
files.push(file_info(filename, file.as_mut(), &metadata)?); files.push(file_info(filename, file.as_mut(), &metadata)?);
} }
} }
@ -131,10 +131,10 @@ pub fn ls(args: LsArgs) -> anyhow::Result<()> {
for (i, column) in entry.iter().enumerate() { for (i, column) in entry.iter().enumerate() {
if widths[i] > 0 { if widths[i] > 0 {
if written > 0 { if written > 0 {
print!("{}", SEPARATOR); print!("{SEPARATOR}");
} }
written += 1; written += 1;
print!("{}", column); print!("{column}");
let remain = widths[i].saturating_sub(column.width_cjk()); let remain = widths[i].saturating_sub(column.width_cjk());
if remain > 0 { if remain > 0 {
print!("{:width$}", "", width = remain); print!("{:width$}", "", width = remain);
@ -161,25 +161,25 @@ fn ls_directory(
let display_path = base_filename.join(&filename); let display_path = base_filename.join(&filename);
let metadata = fs let metadata = fs
.metadata(&entry_path) .metadata(&entry_path)
.with_context(|| format!("Failed to fetch metadata for {}", entry_path))?; .with_context(|| format!("Failed to fetch metadata for {entry_path}"))?;
match metadata.file_type { match metadata.file_type {
VfsFileType::File => { VfsFileType::File => {
let mut file = fs let mut file = fs
.open(&entry_path) .open(&entry_path)
.with_context(|| format!("Failed to open file {}", entry_path))?; .with_context(|| format!("Failed to open file {entry_path}"))?;
if args.short { if args.short {
println!("{}", display_path); println!("{display_path}");
} else { } else {
files.push(file_info(display_path.as_str(), file.as_mut(), &metadata)?); files.push(file_info(display_path.as_str(), file.as_mut(), &metadata)?);
} }
} }
VfsFileType::Directory => { VfsFileType::Directory => {
if args.short { if args.short {
println!("{}/", display_path); println!("{display_path}/");
} else { } else {
files.push([ files.push([
" ".to_string(), " ".to_string(),
format!("{}/", display_path), format!("{display_path}/"),
"Directory".to_string(), "Directory".to_string(),
String::new(), String::new(),
String::new(), String::new(),
@ -206,7 +206,7 @@ pub fn cp(mut args: CpArgs) -> anyhow::Result<()> {
OpenResult::File(file, path) => { OpenResult::File(file, path) => {
let dest = if dest_is_dir { let dest = if dest_is_dir {
fs::create_dir_all(&dest) fs::create_dir_all(&dest)
.with_context(|| format!("Failed to create directory {}", dest))?; .with_context(|| format!("Failed to create directory {dest}"))?;
let filename = let filename =
path.file_name().ok_or_else(|| anyhow!("Path has no filename"))?; path.file_name().ok_or_else(|| anyhow!("Path has no filename"))?;
dest.join(filename) dest.join(filename)
@ -234,12 +234,12 @@ fn cp_file(
if let FileFormat::Compressed(kind) = detect(file.as_mut())? { if let FileFormat::Compressed(kind) = detect(file.as_mut())? {
if auto_decompress { if auto_decompress {
file = decompress_file(file.as_mut(), kind) file = decompress_file(file.as_mut(), kind)
.with_context(|| format!("Failed to decompress file {}", dest))?; .with_context(|| format!("Failed to decompress file {dest}"))?;
compression = Some(kind); compression = Some(kind);
} }
} }
let metadata = let metadata =
file.metadata().with_context(|| format!("Failed to fetch metadata for {}", dest))?; file.metadata().with_context(|| format!("Failed to fetch metadata for {dest}"))?;
if !quiet { if !quiet {
if let Some(kind) = compression { if let Some(kind) = compression {
println!( println!(
@ -254,10 +254,10 @@ fn cp_file(
} }
} }
let mut dest_file = let mut dest_file =
File::create(dest).with_context(|| format!("Failed to create file {}", dest))?; File::create(dest).with_context(|| format!("Failed to create file {dest}"))?;
buf_copy(file.as_mut(), &mut dest_file) buf_copy(file.as_mut(), &mut dest_file)
.with_context(|| format!("Failed to copy file {}", dest))?; .with_context(|| format!("Failed to copy file {dest}"))?;
dest_file.flush().with_context(|| format!("Failed to flush file {}", dest))?; dest_file.flush().with_context(|| format!("Failed to flush file {dest}"))?;
Ok(()) Ok(())
} }
@ -268,18 +268,18 @@ fn cp_recursive(
auto_decompress: bool, auto_decompress: bool,
quiet: bool, quiet: bool,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
fs::create_dir_all(dest).with_context(|| format!("Failed to create directory {}", dest))?; fs::create_dir_all(dest).with_context(|| format!("Failed to create directory {dest}"))?;
let entries = fs.read_dir(path)?; let entries = fs.read_dir(path)?;
for filename in entries { for filename in entries {
let entry_path = path.join(&filename); let entry_path = path.join(&filename);
let metadata = fs let metadata = fs
.metadata(&entry_path) .metadata(&entry_path)
.with_context(|| format!("Failed to fetch metadata for {}", entry_path))?; .with_context(|| format!("Failed to fetch metadata for {entry_path}"))?;
match metadata.file_type { match metadata.file_type {
VfsFileType::File => { VfsFileType::File => {
let file = fs let file = fs
.open(&entry_path) .open(&entry_path)
.with_context(|| format!("Failed to open file {}", entry_path))?; .with_context(|| format!("Failed to open file {entry_path}"))?;
cp_file(file, &entry_path, &dest.join(filename), auto_decompress, quiet)?; cp_file(file, &entry_path, &dest.join(filename), auto_decompress, quiet)?;
} }
VfsFileType::Directory => { VfsFileType::Directory => {

View File

@ -80,7 +80,7 @@ fn compress(args: CompressArgs) -> Result<()> {
path.as_path().to_cow() path.as_path().to_cow()
}; };
fs::write(out_path.as_ref(), data) fs::write(out_path.as_ref(), data)
.with_context(|| format!("Failed to write '{}'", out_path))?; .with_context(|| format!("Failed to write '{out_path}'"))?;
} }
Ok(()) Ok(())
} }
@ -92,7 +92,7 @@ fn decompress(args: DecompressArgs) -> Result<()> {
let data = { let data = {
let mut file = open_file(&path, true)?; let mut file = open_file(&path, true)?;
decompress_yay0(file.map()?) decompress_yay0(file.map()?)
.with_context(|| format!("Failed to decompress '{}' using Yay0", path))? .with_context(|| format!("Failed to decompress '{path}' using Yay0"))?
}; };
let out_path = if let Some(output) = &args.output { let out_path = if let Some(output) = &args.output {
if single_file { if single_file {
@ -104,7 +104,7 @@ fn decompress(args: DecompressArgs) -> Result<()> {
path.as_path().to_cow() path.as_path().to_cow()
}; };
fs::write(out_path.as_ref(), data) fs::write(out_path.as_ref(), data)
.with_context(|| format!("Failed to write '{}'", out_path))?; .with_context(|| format!("Failed to write '{out_path}'"))?;
} }
Ok(()) Ok(())
} }

View File

@ -80,7 +80,7 @@ fn compress(args: CompressArgs) -> Result<()> {
path.as_path().to_cow() path.as_path().to_cow()
}; };
fs::write(out_path.as_ref(), data) fs::write(out_path.as_ref(), data)
.with_context(|| format!("Failed to write '{}'", out_path))?; .with_context(|| format!("Failed to write '{out_path}'"))?;
} }
Ok(()) Ok(())
} }
@ -92,7 +92,7 @@ fn decompress(args: DecompressArgs) -> Result<()> {
let data = { let data = {
let mut file = open_file(&path, false)?; let mut file = open_file(&path, false)?;
decompress_yaz0(file.map()?) decompress_yaz0(file.map()?)
.with_context(|| format!("Failed to decompress '{}' using Yaz0", path))? .with_context(|| format!("Failed to decompress '{path}' using Yaz0"))?
}; };
let out_path = if let Some(output) = &args.output { let out_path = if let Some(output) = &args.output {
if single_file { if single_file {
@ -104,7 +104,7 @@ fn decompress(args: DecompressArgs) -> Result<()> {
path.as_path().to_cow() path.as_path().to_cow()
}; };
fs::write(out_path.as_ref(), data) fs::write(out_path.as_ref(), data)
.with_context(|| format!("Failed to write '{}'", out_path))?; .with_context(|| format!("Failed to write '{out_path}'"))?;
} }
Ok(()) Ok(())
} }

View File

@ -403,7 +403,7 @@ impl ObjSymbols {
pub fn iter_ordered(&self) -> impl DoubleEndedIterator<Item = (SymbolIndex, &ObjSymbol)> { pub fn iter_ordered(&self) -> impl DoubleEndedIterator<Item = (SymbolIndex, &ObjSymbol)> {
self.symbols_by_section self.symbols_by_section
.iter() .iter()
.flat_map(|v| v.iter().map(|(_, v)| v)) .flat_map(|v| v.values())
.flat_map(move |v| v.iter().map(move |u| (*u, &self.symbols[*u as usize]))) .flat_map(move |v| v.iter().map(move |u| (*u, &self.symbols[*u as usize])))
} }
@ -450,7 +450,7 @@ impl ObjSymbols {
self.symbols_by_section self.symbols_by_section
.get(section_idx as usize) .get(section_idx as usize)
.into_iter() .into_iter()
.flat_map(|v| v.iter().map(|(_, v)| v)) .flat_map(|v| v.values())
.flat_map(move |v| v.iter().map(move |u| (*u, &self.symbols[*u as usize]))) .flat_map(move |v| v.iter().map(move |u| (*u, &self.symbols[*u as usize])))
} }

View File

@ -161,7 +161,7 @@ impl FromReader for AlfSymbolKind {
match u32::from_reader(reader, e)? { match u32::from_reader(reader, e)? {
0 => Ok(Self::Function), 0 => Ok(Self::Function),
1 => Ok(Self::Object), 1 => Ok(Self::Object),
v => Err(Error::new(ErrorKind::InvalidData, format!("invalid ALF symbol kind: {}", v))), v => Err(Error::new(ErrorKind::InvalidData, format!("invalid ALF symbol kind: {v}"))),
} }
} }
} }

View File

@ -442,12 +442,12 @@ where
match parse_extab(symbols, entry, section) { match parse_extab(symbols, entry, section) {
Ok(s) => { Ok(s) => {
for line in s.trim_end().lines() { for line in s.trim_end().lines() {
writeln!(w, " * {}", line)?; writeln!(w, " * {line}")?;
} }
} }
Err(e) => { Err(e) => {
log::warn!("Failed to decode extab entry {}: {}", symbol.name, e); log::warn!("Failed to decode extab entry {}: {}", symbol.name, e);
writeln!(w, " * Failed to decode extab entry: {}", e)?; writeln!(w, " * Failed to decode extab entry: {e}")?;
} }
} }
writeln!(w, " */")?; writeln!(w, " */")?;
@ -505,7 +505,7 @@ where
} }
current_symbol_kind = find_symbol_kind(current_symbol_kind, symbols, vec)?; current_symbol_kind = find_symbol_kind(current_symbol_kind, symbols, vec)?;
current_data_kind = find_data_kind(current_data_kind, symbols, vec) current_data_kind = find_data_kind(current_data_kind, symbols, vec)
.with_context(|| format!("At address {:#010X}", sym_addr))?; .with_context(|| format!("At address {sym_addr:#010X}"))?;
entry = entry_iter.next(); entry = entry_iter.next();
} else if current_address > sym_addr { } else if current_address > sym_addr {
let dbg_symbols = vec.iter().map(|e| &symbols[e.index as usize]).collect_vec(); let dbg_symbols = vec.iter().map(|e| &symbols[e.index as usize]).collect_vec();
@ -660,8 +660,8 @@ where W: Write + ?Sized {
'\x0D' => write!(w, "\\r")?, '\x0D' => write!(w, "\\r")?,
'\\' => write!(w, "\\\\")?, '\\' => write!(w, "\\\\")?,
'"' => write!(w, "\\\"")?, '"' => write!(w, "\\\"")?,
c if c.is_ascii_graphic() || c.is_ascii_whitespace() => write!(w, "{}", c)?, c if c.is_ascii_graphic() || c.is_ascii_whitespace() => write!(w, "{c}")?,
_ => write!(w, "\\{:03o}", b)?, _ => write!(w, "\\{b:03o}")?,
} }
} }
writeln!(w, "\"")?; writeln!(w, "\"")?;
@ -684,13 +684,13 @@ where W: Write + ?Sized {
for c in cow.chars() { for c in cow.chars() {
match c { match c {
'#' => write!(w, "\\#")?, '#' => write!(w, "\\#")?,
_ => write!(w, "{}", c)?, _ => write!(w, "{c}")?,
} }
} }
write!(w, "\n\t.byte ")?; write!(w, "\n\t.byte ")?;
for (i, &b) in data.iter().enumerate() { for (i, &b) in data.iter().enumerate() {
write!(w, "0x{:02X}", b)?; write!(w, "0x{b:02X}")?;
if i + 1 != data.len() { if i + 1 != data.len() {
write!(w, ", ")?; write!(w, ", ")?;
} }
@ -721,7 +721,7 @@ where W: Write + ?Sized {
'\x0D' => write!(w, "\\r")?, '\x0D' => write!(w, "\\r")?,
'\\' => write!(w, "\\\\")?, '\\' => write!(w, "\\\\")?,
'"' => write!(w, "\\\"")?, '"' => write!(w, "\\\"")?,
c if c.is_ascii_graphic() || c.is_ascii_whitespace() => write!(w, "{}", c)?, c if c.is_ascii_graphic() || c.is_ascii_whitespace() => write!(w, "{c}")?,
_ => write!(w, "\\{:#X}", c as u32)?, _ => write!(w, "\\{:#X}", c as u32)?,
} }
} }
@ -793,7 +793,7 @@ where W: Write + ?Sized {
}; };
for chunk in remain.chunks(chunk_size) { for chunk in remain.chunks(chunk_size) {
if data_kind == ObjDataKind::Byte || matches!(chunk.len(), 1 | 3 | 5..=7) { if data_kind == ObjDataKind::Byte || matches!(chunk.len(), 1 | 3 | 5..=7) {
let bytes = chunk.iter().map(|c| format!("{:#04X}", c)).collect::<Vec<String>>(); let bytes = chunk.iter().map(|c| format!("{c:#04X}")).collect::<Vec<String>>();
writeln!(w, "\t.byte {}", bytes.join(", "))?; writeln!(w, "\t.byte {}", bytes.join(", "))?;
} else { } else {
match chunk.len() { match chunk.len() {

View File

@ -95,7 +95,7 @@ fn bin2c_symbol(
} else { } else {
output.push(' '); output.push(' ');
} }
output.push_str(&format!("0x{:02X},", byte)); output.push_str(&format!("0x{byte:02X},"));
} }
output.push_str("\n};\n"); output.push_str("\n};\n");
output output
@ -111,7 +111,7 @@ fn bin2c_raw(data: &[u8]) -> String {
output.push(' '); output.push(' ');
} }
} }
output.push_str(&format!("0x{:02X},", byte)); output.push_str(&format!("0x{byte:02X},"));
} }
output.push('\n'); output.push('\n');
output output

View File

@ -58,7 +58,7 @@ impl FromReader for MWComment {
if magic != MAGIC { if magic != MAGIC {
return Err(io::Error::new( return Err(io::Error::new(
io::ErrorKind::InvalidData, io::ErrorKind::InvalidData,
format!("Invalid .comment section magic: {:?}", magic), format!("Invalid .comment section magic: {magic:?}"),
)); ));
} }
// 0xB // 0xB
@ -78,7 +78,7 @@ impl FromReader for MWComment {
value => { value => {
return Err(io::Error::new( return Err(io::Error::new(
io::ErrorKind::InvalidData, io::ErrorKind::InvalidData,
format!("Invalid value for pool_data: {}", value), format!("Invalid value for pool_data: {value}"),
)) ))
} }
}; };
@ -93,7 +93,7 @@ impl FromReader for MWComment {
v => { v => {
return Err(io::Error::new( return Err(io::Error::new(
io::ErrorKind::InvalidData, io::ErrorKind::InvalidData,
format!("Expected header size {:#X}, got {:#X}", HEADER_SIZE, v), format!("Expected header size {HEADER_SIZE:#X}, got {v:#X}"),
)) ))
} }
} }
@ -102,7 +102,7 @@ impl FromReader for MWComment {
if flags & !7 != 0 { if flags & !7 != 0 {
return Err(io::Error::new( return Err(io::Error::new(
io::ErrorKind::InvalidData, io::ErrorKind::InvalidData,
format!("Unexpected flag value {:#X}", flags), format!("Unexpected flag value {flags:#X}"),
)); ));
} }
if flags & 1 == 1 { if flags & 1 == 1 {
@ -221,14 +221,14 @@ impl FromReader for CommentSym {
if value != 0 { if value != 0 {
return Err(io::Error::new( return Err(io::Error::new(
io::ErrorKind::InvalidData, io::ErrorKind::InvalidData,
format!("Unexpected value after active_flags (1): {:#X}", value), format!("Unexpected value after active_flags (1): {value:#X}"),
)); ));
} }
let value = u8::from_reader(reader, e)?; let value = u8::from_reader(reader, e)?;
if value != 0 { if value != 0 {
return Err(io::Error::new( return Err(io::Error::new(
io::ErrorKind::InvalidData, io::ErrorKind::InvalidData,
format!("Unexpected value after active_flags (2): {:#X}", value), format!("Unexpected value after active_flags (2): {value:#X}"),
)); ));
} }
Ok(out) Ok(out)

View File

@ -282,11 +282,11 @@ where W: Write + ?Sized {
write!(w, " data:{kind}")?; write!(w, " data:{kind}")?;
} }
if let Some(hash) = symbol.name_hash { if let Some(hash) = symbol.name_hash {
write!(w, " hash:{:#010X}", hash)?; write!(w, " hash:{hash:#010X}")?;
} }
if let Some(hash) = symbol.demangled_name_hash { if let Some(hash) = symbol.demangled_name_hash {
if symbol.name_hash != symbol.demangled_name_hash { if symbol.name_hash != symbol.demangled_name_hash {
write!(w, " dhash:{:#010X}", hash)?; write!(w, " dhash:{hash:#010X}")?;
} }
} }
if symbol.flags.is_hidden() { if symbol.flags.is_hidden() {
@ -439,10 +439,10 @@ where W: Write + ?Sized {
for unit in obj.link_order.iter().filter(|unit| all || !unit.autogenerated) { for unit in obj.link_order.iter().filter(|unit| all || !unit.autogenerated) {
write!(w, "\n{}:", unit.name)?; write!(w, "\n{}:", unit.name)?;
if let Some(comment_version) = unit.comment_version { if let Some(comment_version) = unit.comment_version {
write!(w, " comment:{}", comment_version)?; write!(w, " comment:{comment_version}")?;
} }
if let Some(order) = unit.order { if let Some(order) = unit.order {
write!(w, " order:{}", order)?; write!(w, " order:{order}")?;
} }
writeln!(w)?; writeln!(w)?;
let mut split_iter = obj.sections.all_splits().peekable(); let mut split_iter = obj.sections.all_splits().peekable();
@ -458,14 +458,14 @@ where W: Write + ?Sized {
write!(w, "\t{:<11} start:{:#010X} end:{:#010X}", section.name, addr, end)?; write!(w, "\t{:<11} start:{:#010X} end:{:#010X}", section.name, addr, end)?;
if let Some(align) = split.align { if let Some(align) = split.align {
if align != default_section_align(section) as u32 { if align != default_section_align(section) as u32 {
write!(w, " align:{}", align)?; write!(w, " align:{align}")?;
} }
} }
if split.common { if split.common {
write!(w, " common")?; write!(w, " common")?;
} }
if let Some(name) = &split.rename { if let Some(name) = &split.rename {
write!(w, " rename:{}", name)?; write!(w, " rename:{name}")?;
} }
if split.skip { if split.skip {
write!(w, " skip")?; write!(w, " skip")?;
@ -783,7 +783,7 @@ pub mod signed_hex_serde {
if *value < 0 { if *value < 0 {
serializer.serialize_str(&format!("-{:#X}", -value)) serializer.serialize_str(&format!("-{:#X}", -value))
} else { } else {
serializer.serialize_str(&format!("{:#X}", value)) serializer.serialize_str(&format!("{value:#X}"))
} }
} }

View File

@ -209,7 +209,7 @@ fn print_line(ins_diff: &ObjInsDiff, base_addr: u64) -> Vec<Span> {
pad_to = 5; pad_to = 5;
} }
DiffText::Address(addr) => { DiffText::Address(addr) => {
label_text = format!("{:x}:", addr); label_text = format!("{addr:x}:");
pad_to = 5; pad_to = 5;
} }
DiffText::Opcode(mnemonic, _op) => { DiffText::Opcode(mnemonic, _op) => {

View File

@ -398,7 +398,7 @@ pub fn process_dol(buf: &[u8], name: &str) -> Result<ObjInfo> {
idx => match dol_section.kind { idx => match dol_section.kind {
DolSectionKind::Text => (format!(".text{idx}"), ObjSectionKind::Code, false), DolSectionKind::Text => (format!(".text{idx}"), ObjSectionKind::Code, false),
DolSectionKind::Data => (format!(".data{idx}"), ObjSectionKind::Data, false), DolSectionKind::Data => (format!(".data{idx}"), ObjSectionKind::Data, false),
DolSectionKind::Bss => (format!(".bss{}", idx), ObjSectionKind::Bss, false), DolSectionKind::Bss => (format!(".bss{idx}"), ObjSectionKind::Bss, false),
}, },
}; };
@ -453,7 +453,7 @@ pub fn process_dol(buf: &[u8], name: &str) -> Result<ObjInfo> {
); );
sections.push(ObjSection { sections.push(ObjSection {
name: format!(".bss{}", idx), name: format!(".bss{idx}"),
kind: ObjSectionKind::Bss, kind: ObjSectionKind::Bss,
address: addr as u64, address: addr as u64,
size: size as u64, size: size as u64,
@ -699,7 +699,7 @@ pub fn process_dol(buf: &[u8], name: &str) -> Result<ObjInfo> {
}; };
obj.add_symbol( obj.add_symbol(
ObjSymbol { ObjSymbol {
name: format!("@etb_{:08X}", addr), name: format!("@etb_{addr:08X}"),
address: addr as u64, address: addr as u64,
section: Some(extab_section_index), section: Some(extab_section_index),
size: size as u64, size: size as u64,

View File

@ -1145,8 +1145,8 @@ fn structure_type_string(
struct_def_string(info, typedefs, t)? struct_def_string(info, typedefs, t)?
} else if include_keyword { } else if include_keyword {
match t.kind { match t.kind {
StructureKind::Struct => format!("struct {}", name), StructureKind::Struct => format!("struct {name}"),
StructureKind::Class => format!("class {}", name), StructureKind::Class => format!("class {name}"),
} }
} else { } else {
name.clone() name.clone()
@ -1178,7 +1178,7 @@ fn enumeration_type_string(
if name.starts_with('@') { if name.starts_with('@') {
enum_def_string(t)? enum_def_string(t)?
} else if include_keyword { } else if include_keyword {
format!("enum {}", name) format!("enum {name}")
} else { } else {
name.clone() name.clone()
} }
@ -1203,7 +1203,7 @@ fn union_type_string(
if name.starts_with('@') { if name.starts_with('@') {
union_def_string(info, typedefs, t)? union_def_string(info, typedefs, t)?
} else if include_keyword { } else if include_keyword {
format!("union {}", name) format!("union {name}")
} else { } else {
name.clone() name.clone()
} }
@ -1306,7 +1306,7 @@ pub fn subroutine_type_string(
write!(parameters, "{}{}", ts.prefix, ts.suffix)?; write!(parameters, "{}{}", ts.prefix, ts.suffix)?;
} }
if let Some(location) = &parameter.location { if let Some(location) = &parameter.location {
write!(parameters, " /* {} */", location)?; write!(parameters, " /* {location} */")?;
} }
} }
if t.var_args { if t.var_args {
@ -1322,7 +1322,7 @@ pub fn subroutine_type_string(
let base_name = tag let base_name = tag
.string_attribute(AttributeKind::Name) .string_attribute(AttributeKind::Name)
.ok_or_else(|| anyhow!("member_of tag {} has no name attribute", member_of))?; .ok_or_else(|| anyhow!("member_of tag {} has no name attribute", member_of))?;
out.member = format!("{}::", base_name); out.member = format!("{base_name}::");
} }
Ok(out) Ok(out)
} }
@ -1337,7 +1337,7 @@ pub fn subroutine_def_string(
if is_erased { if is_erased {
out.push_str("// Erased\n"); out.push_str("// Erased\n");
} else if let (Some(start), Some(end)) = (t.start_address, t.end_address) { } else if let (Some(start), Some(end)) = (t.start_address, t.end_address) {
writeln!(out, "// Range: {:#X} -> {:#X}", start, end)?; writeln!(out, "// Range: {start:#X} -> {end:#X}")?;
} }
let rt = type_string(info, typedefs, &t.return_type, true)?; let rt = type_string(info, typedefs, &t.return_type, true)?;
if t.local { if t.local {
@ -1361,15 +1361,15 @@ pub fn subroutine_def_string(
let base_name = tag let base_name = tag
.string_attribute(AttributeKind::Name) .string_attribute(AttributeKind::Name)
.ok_or_else(|| anyhow!("member_of tag {} has no name attribute", member_of))?; .ok_or_else(|| anyhow!("member_of tag {} has no name attribute", member_of))?;
write!(out, "{}::", base_name)?; write!(out, "{base_name}::")?;
// Handle constructors and destructors // Handle constructors and destructors
if let Some(name) = t.name.as_ref() { if let Some(name) = t.name.as_ref() {
if name == "__dt" { if name == "__dt" {
write!(out, "~{}", base_name)?; write!(out, "~{base_name}")?;
name_written = true; name_written = true;
} else if name == "__ct" { } else if name == "__ct" {
write!(out, "{}", base_name)?; write!(out, "{base_name}")?;
name_written = true; name_written = true;
} }
} }
@ -1398,7 +1398,7 @@ pub fn subroutine_def_string(
write!(parameters, "{}{}", ts.prefix, ts.suffix)?; write!(parameters, "{}{}", ts.prefix, ts.suffix)?;
} }
if let Some(location) = &parameter.location { if let Some(location) = &parameter.location {
write!(parameters, " /* {} */", location)?; write!(parameters, " /* {location} */")?;
} }
} }
if t.var_args { if t.var_args {
@ -1420,7 +1420,7 @@ pub fn subroutine_def_string(
ts.suffix ts.suffix
)?; )?;
if let Some(location) = &variable.location { if let Some(location) = &variable.location {
write!(var_out, " // {}", location)?; write!(var_out, " // {location}")?;
} }
writeln!(var_out)?; writeln!(var_out)?;
} }
@ -1435,7 +1435,7 @@ pub fn subroutine_def_string(
.get(&reference) .get(&reference)
.ok_or_else(|| anyhow!("Failed to locate reference tag {}", reference))?; .ok_or_else(|| anyhow!("Failed to locate reference tag {}", reference))?;
if tag.kind == TagKind::Padding { if tag.kind == TagKind::Padding {
writeln!(out, " // -> ??? ({})", reference)?; writeln!(out, " // -> ??? ({reference})")?;
continue; continue;
} }
let variable = process_variable_tag(info, tag)?; let variable = process_variable_tag(info, tag)?;
@ -1477,13 +1477,13 @@ fn subroutine_block_string(
) -> Result<String> { ) -> Result<String> {
let mut out = String::new(); let mut out = String::new();
if let Some(name) = &block.name { if let Some(name) = &block.name {
write!(out, "{}: ", name)?; write!(out, "{name}: ")?;
} else { } else {
out.push_str("/* anonymous block */ "); out.push_str("/* anonymous block */ ");
} }
out.push_str("{\n"); out.push_str("{\n");
if let (Some(start), Some(end)) = (block.start_address, block.end_address) { if let (Some(start), Some(end)) = (block.start_address, block.end_address) {
writeln!(out, " // Range: {:#X} -> {:#X}", start, end)?; writeln!(out, " // Range: {start:#X} -> {end:#X}")?;
} }
let mut var_out = String::new(); let mut var_out = String::new();
for variable in &block.variables { for variable in &block.variables {
@ -1496,7 +1496,7 @@ fn subroutine_block_string(
ts.suffix ts.suffix
)?; )?;
if let Some(location) = &variable.location { if let Some(location) = &variable.location {
write!(var_out, " // {}", location)?; write!(var_out, " // {location}")?;
} }
writeln!(var_out)?; writeln!(var_out)?;
} }
@ -1635,9 +1635,9 @@ pub fn struct_def_string(
}; };
if let Some(name) = t.name.as_ref() { if let Some(name) = t.name.as_ref() {
if name.starts_with('@') { if name.starts_with('@') {
write!(out, " /* {} */", name)?; write!(out, " /* {name} */")?;
} else { } else {
write!(out, " {}", name)?; write!(out, " {name}")?;
} }
} }
let mut wrote_base = false; let mut wrote_base = false;
@ -1665,7 +1665,7 @@ pub fn struct_def_string(
} }
out.push_str(" {\n"); out.push_str(" {\n");
if let Some(byte_size) = t.byte_size { if let Some(byte_size) = t.byte_size {
writeln!(out, " // total size: {:#X}", byte_size)?; writeln!(out, " // total size: {byte_size:#X}")?;
} }
let mut vis = match t.kind { let mut vis = match t.kind {
StructureKind::Struct => Visibility::Public, StructureKind::Struct => Visibility::Public,
@ -1751,9 +1751,9 @@ pub fn enum_def_string(t: &EnumerationType) -> Result<String> {
let mut out = match t.name.as_ref() { let mut out = match t.name.as_ref() {
Some(name) => { Some(name) => {
if name.starts_with('@') { if name.starts_with('@') {
format!("enum /* {} */ {{\n", name) format!("enum /* {name} */ {{\n")
} else { } else {
format!("enum {} {{\n", name) format!("enum {name} {{\n")
} }
} }
None => "enum {\n".to_string(), None => "enum {\n".to_string(),
@ -1769,9 +1769,9 @@ pub fn union_def_string(info: &DwarfInfo, typedefs: &TypedefMap, t: &UnionType)
let mut out = match t.name.as_ref() { let mut out = match t.name.as_ref() {
Some(name) => { Some(name) => {
if name.starts_with('@') { if name.starts_with('@') {
format!("union /* {} */ {{\n", name) format!("union /* {name} */ {{\n")
} else { } else {
format!("union {} {{\n", name) format!("union {name} {{\n")
} }
} }
None => "union {\n".to_string(), None => "union {\n".to_string(),
@ -2029,7 +2029,7 @@ fn process_array_tag(info: &DwarfInfo, tag: &Tag) -> Result<ArrayType> {
(AttributeKind::SubscrData, AttributeValue::Block(data)) => { (AttributeKind::SubscrData, AttributeValue::Block(data)) => {
subscr_data = subscr_data =
Some(process_array_subscript_data(data, info.e, tag.is_erased).with_context( Some(process_array_subscript_data(data, info.e, tag.is_erased).with_context(
|| format!("Failed to process SubscrData for tag: {:?}", tag), || format!("Failed to process SubscrData for tag: {tag:?}"),
)?) )?)
} }
(AttributeKind::Ordering, val) => match val { (AttributeKind::Ordering, val) => match val {
@ -2615,13 +2615,13 @@ pub fn process_type(attr: &Attribute, e: Endian) -> Result<Type> {
match (attr.kind, &attr.value) { match (attr.kind, &attr.value) {
(AttributeKind::FundType, &AttributeValue::Data2(type_id)) => { (AttributeKind::FundType, &AttributeValue::Data2(type_id)) => {
let fund_type = FundType::parse_int(type_id) let fund_type = FundType::parse_int(type_id)
.with_context(|| format!("Invalid fundamental type ID '{:04X}'", type_id))?; .with_context(|| format!("Invalid fundamental type ID '{type_id:04X}'"))?;
Ok(Type { kind: TypeKind::Fundamental(fund_type), modifiers: vec![] }) Ok(Type { kind: TypeKind::Fundamental(fund_type), modifiers: vec![] })
} }
(AttributeKind::ModFundType, AttributeValue::Block(ops)) => { (AttributeKind::ModFundType, AttributeValue::Block(ops)) => {
let type_id = u16::from_bytes(ops[ops.len() - 2..].try_into()?, e); let type_id = u16::from_bytes(ops[ops.len() - 2..].try_into()?, e);
let fund_type = FundType::parse_int(type_id) let fund_type = FundType::parse_int(type_id)
.with_context(|| format!("Invalid fundamental type ID '{:04X}'", type_id))?; .with_context(|| format!("Invalid fundamental type ID '{type_id:04X}'"))?;
let modifiers = process_modifiers(&ops[..ops.len() - 2])?; let modifiers = process_modifiers(&ops[..ops.len() - 2])?;
Ok(Type { kind: TypeKind::Fundamental(fund_type), modifiers }) Ok(Type { kind: TypeKind::Fundamental(fund_type), modifiers })
} }
@ -2762,7 +2762,7 @@ pub fn tag_type_string(
match ud { match ud {
UserDefinedType::Structure(_) UserDefinedType::Structure(_)
| UserDefinedType::Enumeration(_) | UserDefinedType::Enumeration(_)
| UserDefinedType::Union(_) => Ok(format!("{};", ud_str)), | UserDefinedType::Union(_) => Ok(format!("{ud_str};")),
_ => Ok(ud_str), _ => Ok(ud_str),
} }
} }
@ -2789,9 +2789,9 @@ fn variable_string(
out.push(';'); out.push(';');
if include_extra { if include_extra {
let size = variable.kind.size(info)?; let size = variable.kind.size(info)?;
out.push_str(&format!(" // size: {:#X}", size)); out.push_str(&format!(" // size: {size:#X}"));
if let Some(addr) = variable.address { if let Some(addr) = variable.address {
out.push_str(&format!(", address: {:#X}", addr)); out.push_str(&format!(", address: {addr:#X}"));
} }
} }
Ok(out) Ok(out)

View File

@ -164,7 +164,7 @@ pub fn process_elf(path: &Utf8NativePath) -> Result<ObjInfo> {
hash_map::Entry::Vacant(e) => e.insert(0), hash_map::Entry::Vacant(e) => e.insert(0),
}; };
*index += 1; *index += 1;
let new_name = format!("{}_{}", file_name, index); let new_name = format!("{file_name}_{index}");
// log::info!("Renaming {} to {}", file_name, new_name); // log::info!("Renaming {} to {}", file_name, new_name);
file_name.clone_from(&new_name); file_name.clone_from(&new_name);
match section_starts.entry(new_name.clone()) { match section_starts.entry(new_name.clone()) {

View File

@ -26,7 +26,7 @@ pub fn buf_writer(path: &Utf8NativePath) -> Result<BufWriter<File>> {
if let Some(parent) = path.parent() { if let Some(parent) = path.parent() {
DirBuilder::new().recursive(true).create(parent)?; DirBuilder::new().recursive(true).create(parent)?;
} }
let file = File::create(path).with_context(|| format!("Failed to create file '{}'", path))?; let file = File::create(path).with_context(|| format!("Failed to create file '{path}'"))?;
Ok(BufWriter::new(file)) Ok(BufWriter::new(file))
} }

View File

@ -47,11 +47,11 @@ pub fn generate_ldscript(
let out = template let out = template
.unwrap_or(LCF_TEMPLATE) .unwrap_or(LCF_TEMPLATE)
.replace("$ORIGIN", &format!("{:#X}", origin)) .replace("$ORIGIN", &format!("{origin:#X}"))
.replace("$SECTIONS", &section_defs) .replace("$SECTIONS", &section_defs)
.replace("$LAST_SECTION_SYMBOL", &last_section_symbol) .replace("$LAST_SECTION_SYMBOL", &last_section_symbol)
.replace("$LAST_SECTION_NAME", &last_section_name) .replace("$LAST_SECTION_NAME", &last_section_name)
.replace("$STACKSIZE", &format!("{:#X}", stack_size)) .replace("$STACKSIZE", &format!("{stack_size:#X}"))
.replace("$FORCEACTIVE", &force_active.join("\n ")) .replace("$FORCEACTIVE", &force_active.join("\n "))
.replace("$ARENAHI", &format!("{:#X}", obj.arena_hi.unwrap_or(0x81700000))); .replace("$ARENAHI", &format!("{:#X}", obj.arena_hi.unwrap_or(0x81700000)));
Ok(out) Ok(out)
@ -74,7 +74,7 @@ pub fn generate_ldscript_partial(
// Some RELs have no entry point (`.text` was stripped) so mwld requires at least an empty // Some RELs have no entry point (`.text` was stripped) so mwld requires at least an empty
// `.init` section to be present in the linker script, for some reason. // `.init` section to be present in the linker script, for some reason.
if obj.entry.is_none() { if obj.entry.is_none() {
section_defs = format!(".init :{{}}\n {}", section_defs); section_defs = format!(".init :{{}}\n {section_defs}");
} }
let mut force_files = Vec::with_capacity(obj.link_order.len()); let mut force_files = Vec::with_capacity(obj.link_order.len());

View File

@ -209,7 +209,7 @@ impl<'a> RarcView<'a> {
) )
})?; })?;
let c_string = CStr::from_bytes_until_nul(name_buf) let c_string = CStr::from_bytes_until_nul(name_buf)
.map_err(|_| format!("RARC: name at offset {} not null-terminated", offset))?; .map_err(|_| format!("RARC: name at offset {offset} not null-terminated"))?;
Ok(c_string.to_string_lossy()) Ok(c_string.to_string_lossy())
} }

View File

@ -364,7 +364,7 @@ where
reader.seek(SeekFrom::Start(header.section_info_offset as u64))?; reader.seek(SeekFrom::Start(header.section_info_offset as u64))?;
for idx in 0..header.num_sections { for idx in 0..header.num_sections {
let section = RelSectionHeader::from_reader(reader, Endian::Big) let section = RelSectionHeader::from_reader(reader, Endian::Big)
.with_context(|| format!("Failed to read REL section header {}", idx))?; .with_context(|| format!("Failed to read REL section header {idx}"))?;
sections.push(section); sections.push(section);
} }
Ok(sections) Ok(sections)
@ -390,7 +390,7 @@ where R: Read + Seek + ?Sized {
reader.seek(SeekFrom::Start(offset as u64))?; reader.seek(SeekFrom::Start(offset as u64))?;
let mut data = vec![0u8; size as usize]; let mut data = vec![0u8; size as usize];
reader.read_exact(&mut data).with_context(|| { reader.read_exact(&mut data).with_context(|| {
format!("Failed to read REL section {} data with size {:#X}", idx, size) format!("Failed to read REL section {idx} data with size {size:#X}")
})?; })?;
reader.seek(SeekFrom::Start(position))?; reader.seek(SeekFrom::Start(position))?;
data data
@ -405,7 +405,7 @@ where R: Read + Seek + ?Sized {
text_section = Some(idx as u8); text_section = Some(idx as u8);
(".text".to_string(), ObjSectionKind::Code, true) (".text".to_string(), ObjSectionKind::Code, true)
} else { } else {
(format!(".section{}", idx), ObjSectionKind::Data, false) (format!(".section{idx}"), ObjSectionKind::Data, false)
}; };
sections.push(ObjSection { sections.push(ObjSection {
name, name,

View File

@ -147,14 +147,14 @@ impl FromReader for RsoHeader {
if next != 0 { if next != 0 {
return Err(io::Error::new( return Err(io::Error::new(
io::ErrorKind::InvalidData, io::ErrorKind::InvalidData,
format!("Expected 'next' to be 0, got {:#X}", next), format!("Expected 'next' to be 0, got {next:#X}"),
)); ));
} }
let prev = u32::from_reader(reader, e)?; let prev = u32::from_reader(reader, e)?;
if prev != 0 { if prev != 0 {
return Err(io::Error::new( return Err(io::Error::new(
io::ErrorKind::InvalidData, io::ErrorKind::InvalidData,
format!("Expected 'prev' to be 0, got {:#X}", prev), format!("Expected 'prev' to be 0, got {prev:#X}"),
)); ));
} }
let num_sections = u32::from_reader(reader, e)?; let num_sections = u32::from_reader(reader, e)?;
@ -170,7 +170,7 @@ impl FromReader for RsoHeader {
if bss_section != 0 { if bss_section != 0 {
return Err(io::Error::new( return Err(io::Error::new(
io::ErrorKind::InvalidData, io::ErrorKind::InvalidData,
format!("Expected 'bssSection' to be 0, got {:#X}", bss_section), format!("Expected 'bssSection' to be 0, got {bss_section:#X}"),
)); ));
} }
let prolog_offset = u32::from_reader(reader, e)?; let prolog_offset = u32::from_reader(reader, e)?;
@ -440,7 +440,7 @@ where R: Read + Seek + ?Sized {
// println!("Section {} offset {:#X} size {:#X}", idx, offset, size); // println!("Section {} offset {:#X} size {:#X}", idx, offset, size);
sections.push(ObjSection { sections.push(ObjSection {
name: format!(".section{}", idx), name: format!(".section{idx}"),
kind: if offset == 0 { kind: if offset == 0 {
ObjSectionKind::Bss ObjSectionKind::Bss
} else if section.exec() { } else if section.exec() {

View File

@ -655,7 +655,7 @@ fn add_padding_symbols(obj: &mut ObjInfo) -> Result<()> {
next_address next_address
); );
let name = if obj.module_id == 0 { let name = if obj.module_id == 0 {
format!("lbl_{:08X}", symbol_end) format!("lbl_{symbol_end:08X}")
} else { } else {
format!( format!(
"lbl_{}_{}_{:X}", "lbl_{}_{}_{:X}",
@ -1465,7 +1465,7 @@ fn auto_unit_name(
if unit_exists(&unit_name, obj, new_splits) { if unit_exists(&unit_name, obj, new_splits) {
let mut i = 1; let mut i = 1;
loop { loop {
let new_unit_name = format!("{}_{}", unit_name, i); let new_unit_name = format!("{unit_name}_{i}");
if !unit_exists(&new_unit_name, obj, new_splits) { if !unit_exists(&new_unit_name, obj, new_splits) {
unit_name = new_unit_name; unit_name = new_unit_name;
break; break;

View File

@ -333,7 +333,7 @@ impl VfsFile for DiscFile {
pub fn nod_to_io_error(e: nod::Error) -> io::Error { pub fn nod_to_io_error(e: nod::Error) -> io::Error {
match e { match e {
nod::Error::Io(msg, e) => io::Error::new(e.kind(), format!("{}: {}", msg, e)), nod::Error::Io(msg, e) => io::Error::new(e.kind(), format!("{msg}: {e}")),
e => io::Error::new(io::ErrorKind::InvalidData, e), e => io::Error::new(io::ErrorKind::InvalidData, e),
} }
} }

View File

@ -108,8 +108,8 @@ impl Display for VfsError {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
match self { match self {
VfsError::NotFound => write!(f, "File or directory not found"), VfsError::NotFound => write!(f, "File or directory not found"),
VfsError::IoError(e) => write!(f, "{}", e), VfsError::IoError(e) => write!(f, "{e}"),
VfsError::Other(e) => write!(f, "{}", e), VfsError::Other(e) => write!(f, "{e}"),
VfsError::NotADirectory => write!(f, "Path is a file, not a directory"), VfsError::NotADirectory => write!(f, "Path is a file, not a directory"),
VfsError::IsADirectory => write!(f, "Path is a directory, not a file"), VfsError::IsADirectory => write!(f, "Path is a directory, not a file"),
} }
@ -129,8 +129,8 @@ impl Display for FileFormat {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
match self { match self {
FileFormat::Regular => write!(f, "File"), FileFormat::Regular => write!(f, "File"),
FileFormat::Compressed(kind) => write!(f, "Compressed: {}", kind), FileFormat::Compressed(kind) => write!(f, "Compressed: {kind}"),
FileFormat::Archive(kind) => write!(f, "Archive: {}", kind), FileFormat::Archive(kind) => write!(f, "Archive: {kind}"),
} }
} }
} }
@ -165,7 +165,7 @@ impl Display for ArchiveKind {
match self { match self {
ArchiveKind::Rarc => write!(f, "RARC"), ArchiveKind::Rarc => write!(f, "RARC"),
ArchiveKind::U8 => write!(f, "U8"), ArchiveKind::U8 => write!(f, "U8"),
ArchiveKind::Disc(format) => write!(f, "Disc ({})", format), ArchiveKind::Disc(format) => write!(f, "Disc ({format})"),
ArchiveKind::Wad => write!(f, "WAD"), ArchiveKind::Wad => write!(f, "WAD"),
} }
} }
@ -228,13 +228,13 @@ pub fn open_path_with_fs(
let file_type = match fs.metadata(segment) { let file_type = match fs.metadata(segment) {
Ok(metadata) => metadata.file_type, Ok(metadata) => metadata.file_type,
Err(VfsError::NotFound) => return Err(anyhow!("{} not found", current_path)), Err(VfsError::NotFound) => return Err(anyhow!("{} not found", current_path)),
Err(e) => return Err(e).context(format!("Failed to open {}", current_path)), Err(e) => return Err(e).context(format!("Failed to open {current_path}")),
}; };
match file_type { match file_type {
VfsFileType::File => { VfsFileType::File => {
file = Some( file = Some(
fs.open(segment) fs.open(segment)
.with_context(|| format!("Failed to open {}", current_path))?, .with_context(|| format!("Failed to open {current_path}"))?,
); );
} }
VfsFileType::Directory => { VfsFileType::Directory => {
@ -248,7 +248,7 @@ pub fn open_path_with_fs(
} }
let mut current_file = file.take().unwrap(); let mut current_file = file.take().unwrap();
let format = detect(current_file.as_mut()) let format = detect(current_file.as_mut())
.with_context(|| format!("Failed to detect file type for {}", current_path))?; .with_context(|| format!("Failed to detect file type for {current_path}"))?;
if let Some(&next) = split.peek() { if let Some(&next) = split.peek() {
match next { match next {
"nlzss" => { "nlzss" => {
@ -256,7 +256,7 @@ pub fn open_path_with_fs(
file = Some( file = Some(
decompress_file(current_file.as_mut(), CompressionKind::Nlzss) decompress_file(current_file.as_mut(), CompressionKind::Nlzss)
.with_context(|| { .with_context(|| {
format!("Failed to decompress {} with NLZSS", current_path) format!("Failed to decompress {current_path} with NLZSS")
})?, })?,
); );
} }
@ -265,7 +265,7 @@ pub fn open_path_with_fs(
file = Some( file = Some(
decompress_file(current_file.as_mut(), CompressionKind::Yay0) decompress_file(current_file.as_mut(), CompressionKind::Yay0)
.with_context(|| { .with_context(|| {
format!("Failed to decompress {} with Yay0", current_path) format!("Failed to decompress {current_path} with Yay0")
})?, })?,
); );
} }
@ -274,7 +274,7 @@ pub fn open_path_with_fs(
file = Some( file = Some(
decompress_file(current_file.as_mut(), CompressionKind::Yaz0) decompress_file(current_file.as_mut(), CompressionKind::Yaz0)
.with_context(|| { .with_context(|| {
format!("Failed to decompress {} with Yaz0", current_path) format!("Failed to decompress {current_path} with Yaz0")
})?, })?,
); );
} }
@ -283,16 +283,15 @@ pub fn open_path_with_fs(
return Err(anyhow!("{} is not an archive", current_path)) return Err(anyhow!("{} is not an archive", current_path))
} }
FileFormat::Compressed(kind) => { FileFormat::Compressed(kind) => {
file = file = Some(
Some(decompress_file(current_file.as_mut(), kind).with_context( decompress_file(current_file.as_mut(), kind)
|| format!("Failed to decompress {}", current_path), .with_context(|| format!("Failed to decompress {current_path}"))?,
)?); );
// Continue the loop to detect the new format // Continue the loop to detect the new format
} }
FileFormat::Archive(kind) => { FileFormat::Archive(kind) => {
fs = open_fs(current_file, kind).with_context(|| { fs = open_fs(current_file, kind)
format!("Failed to open container {}", current_path) .with_context(|| format!("Failed to open container {current_path}"))?;
})?;
// Continue the loop to open the next segment // Continue the loop to open the next segment
} }
}, },
@ -302,7 +301,7 @@ pub fn open_path_with_fs(
return match format { return match format {
FileFormat::Compressed(kind) if auto_decompress => Ok(OpenResult::File( FileFormat::Compressed(kind) if auto_decompress => Ok(OpenResult::File(
decompress_file(current_file.as_mut(), kind) decompress_file(current_file.as_mut(), kind)
.with_context(|| format!("Failed to decompress {}", current_path))?, .with_context(|| format!("Failed to decompress {current_path}"))?,
segment.to_path_buf(), segment.to_path_buf(),
)), )),
_ => Ok(OpenResult::File(current_file, segment.to_path_buf())), _ => Ok(OpenResult::File(current_file, segment.to_path_buf())),

View File

@ -118,11 +118,11 @@ impl Vfs for WadFs {
} }
let title_id = hex::encode(self.wad.ticket().title_id); let title_id = hex::encode(self.wad.ticket().title_id);
let mut entries = Vec::new(); let mut entries = Vec::new();
entries.push(format!("{}.tik", title_id)); entries.push(format!("{title_id}.tik"));
entries.push(format!("{}.tmd", title_id)); entries.push(format!("{title_id}.tmd"));
entries.push(format!("{}.cert", title_id)); entries.push(format!("{title_id}.cert"));
if self.wad.header.footer_size.get() > 0 { if self.wad.header.footer_size.get() > 0 {
entries.push(format!("{}.trailer", title_id)); entries.push(format!("{title_id}.trailer"));
} }
for content in self.wad.contents() { for content in self.wad.contents() {
entries.push(format!("{:08x}.app", content.content_index.get())); entries.push(format!("{:08x}.app", content.content_index.get()));