core: Fix clippy format string lint

This commit is contained in:
Aaron Hill 2022-10-26 18:46:09 -05:00 committed by relrelb
parent fb7ba9c9a0
commit 68471723b3
56 changed files with 117 additions and 117 deletions

View File

@ -55,7 +55,7 @@ pub fn build_playerglobal(
match status { match status {
Ok(code) => { Ok(code) => {
if !code.success() { if !code.success() {
return Err(format!("Compiling failed with code {:?}", code).into()); return Err(format!("Compiling failed with code {code:?}").into());
} }
} }
Err(err) => { Err(err) => {
@ -95,7 +95,7 @@ fn resolve_multiname_name<'a>(abc: &'a AbcFile, multiname: &Multiname) -> &'a st
if let Multiname::QName { name, .. } | Multiname::Multiname { name, .. } = multiname { if let Multiname::QName { name, .. } | Multiname::Multiname { name, .. } = multiname {
&abc.constant_pool.strings[name.0 as usize - 1] &abc.constant_pool.strings[name.0 as usize - 1]
} else { } else {
panic!("Unexpected Multiname {:?}", multiname); panic!("Unexpected Multiname {multiname:?}");
} }
} }
@ -106,10 +106,10 @@ fn resolve_multiname_ns<'a>(abc: &'a AbcFile, multiname: &Multiname) -> &'a str
if let Namespace::Package(p) = ns { if let Namespace::Package(p) = ns {
&abc.constant_pool.strings[p.0 as usize - 1] &abc.constant_pool.strings[p.0 as usize - 1]
} else { } else {
panic!("Unexpected Namespace {:?}", ns); panic!("Unexpected Namespace {ns:?}");
} }
} else { } else {
panic!("Unexpected Multiname {:?}", multiname); panic!("Unexpected Multiname {multiname:?}");
} }
} }
@ -265,7 +265,7 @@ fn write_native_table(data: &[u8], out_dir: &Path) -> Result<Vec<u8>, Box<dyn st
method method
} }
TraitKind::Function { .. } => { TraitKind::Function { .. } => {
panic!("TraitKind::Function is not supported: {:?}", trait_) panic!("TraitKind::Function is not supported: {trait_:?}")
} }
_ => return, _ => return,
}; };
@ -308,7 +308,7 @@ fn write_native_table(data: &[u8], out_dir: &Path) -> Result<Vec<u8>, Box<dyn st
let name = &abc.constant_pool.strings[metadata.name.0 as usize - 1]; let name = &abc.constant_pool.strings[metadata.name.0 as usize - 1];
match name.as_str() { match name.as_str() {
RUFFLE_METADATA_NAME => {} RUFFLE_METADATA_NAME => {}
_ => panic!("Unexpected class metadata {:?}", name), _ => panic!("Unexpected class metadata {name:?}"),
} }
for item in &metadata.items { for item in &metadata.items {
@ -326,7 +326,7 @@ fn write_native_table(data: &[u8], out_dir: &Path) -> Result<Vec<u8>, Box<dyn st
rust_instance_allocators[class_id as usize] = rust_instance_allocators[class_id as usize] =
rust_method_name_and_path(&abc, trait_, None, "", &method_name); rust_method_name_and_path(&abc, trait_, None, "", &method_name);
} }
_ => panic!("Unexpected metadata pair ({:?}, {})", key, value), _ => panic!("Unexpected metadata pair ({key:?}, {value})"),
} }
} }
} }

View File

@ -29,7 +29,7 @@ fn main() {
let tmp = root.join("tmp"); let tmp = root.join("tmp");
if let Err(e) = std::fs::create_dir(&tmp) { if let Err(e) = std::fs::create_dir(&tmp) {
if e.kind() != ErrorKind::AlreadyExists { if e.kind() != ErrorKind::AlreadyExists {
panic!("Failed to create temporary folder {}", e); panic!("Failed to create temporary folder {e}");
} }
} }
let classes_dir = repo_root.join("core/src/avm2/globals/"); let classes_dir = repo_root.join("core/src/avm2/globals/");
@ -53,7 +53,7 @@ fn main() {
let pmd = Pmd::open(classes_dir, tmp.join("pmd.xml")).expect("Invalid PMD xml file"); let pmd = Pmd::open(classes_dir, tmp.join("pmd.xml")).expect("Invalid PMD xml file");
std::fs::remove_dir_all(tmp).expect("Failed to delete temp folder"); std::fs::remove_dir_all(tmp).expect("Failed to delete temp folder");
if pmd.contains_violations() { if pmd.contains_violations() {
eprintln!("{}", pmd); eprintln!("{pmd}");
std::process::exit(1); std::process::exit(1);
} }
} }

View File

@ -105,7 +105,7 @@ pub fn enum_trait_object(args: TokenStream, item: TokenStream) -> TokenStream {
block: parse_quote!(#method_block), block: parse_quote!(#method_block),
}) })
} }
_ => panic!("Unsupported trait item: {:?}", item), _ => panic!("Unsupported trait item: {item:?}"),
}) })
.collect(); .collect();

View File

@ -108,7 +108,7 @@ pub struct ActivationIdentifier<'a> {
impl fmt::Display for ActivationIdentifier<'_> { impl fmt::Display for ActivationIdentifier<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(parent) = self.parent { if let Some(parent) = self.parent {
write!(f, "{} / ", parent)?; write!(f, "{parent} / ")?;
} }
f.write_str(&self.name)?; f.write_str(&self.name)?;
@ -2324,9 +2324,9 @@ impl<'a, 'gc, 'gc_context> Activation<'a, 'gc, 'gc_context> {
match method { match method {
NavigationMethod::Get if !url.contains(b'?') => { NavigationMethod::Get if !url.contains(b'?') => {
Request::get(format!("{}?{}", url, qstring)) Request::get(format!("{url}?{qstring}"))
} }
NavigationMethod::Get => Request::get(format!("{}&{}", url, qstring)), NavigationMethod::Get => Request::get(format!("{url}&{qstring}")),
NavigationMethod::Post => Request::post( NavigationMethod::Post => Request::post(
url.to_utf8_lossy().into_owned(), url.to_utf8_lossy().into_owned(),
Some(( Some((

View File

@ -178,7 +178,7 @@ impl<'a> VariableDumper<'a> {
for key in keys.into_iter() { for key in keys.into_iter() {
self.output.push_str(name); self.output.push_str(name);
self.output.push('.'); self.output.push('.');
let _ = write!(self.output, "{}", key); let _ = write!(self.output, "{key}");
self.output.push_str(" = "); self.output.push_str(" = ");
self.print_property(object, key, activation); self.print_property(object, key, activation);
self.output.push('\n'); self.output.push('\n');

View File

@ -314,7 +314,7 @@ impl fmt::Debug for Executable<'_> {
match self { match self {
Executable::Native(nf) => f Executable::Native(nf) => f
.debug_tuple("Executable::Native") .debug_tuple("Executable::Native")
.field(&format!("{:p}", nf)) .field(&format!("{nf:p}"))
.finish(), .finish(),
Executable::Action(af) => f.debug_tuple("Executable::Action").field(&af).finish(), Executable::Action(af) => f.debug_tuple("Executable::Action").field(&af).finish(),
} }

View File

@ -326,7 +326,7 @@ pub fn get_local<'gc>(
// Final SO path: foo.com/folder/game.swf/SOName // Final SO path: foo.com/folder/game.swf/SOName
// SOName may be a path containing slashes. In this case, prefix with # to mimic Flash Player behavior. // SOName may be a path containing slashes. In this case, prefix with # to mimic Flash Player behavior.
let prefix = if name.contains('/') { "#" } else { "" }; let prefix = if name.contains('/') { "#" } else { "" };
let full_name = format!("{}/{}/{}{}", movie_host, local_path, prefix, name); let full_name = format!("{movie_host}/{local_path}/{prefix}{name}");
// Avoid any paths with `..` to prevent SWFs from crawling the file system on desktop. // Avoid any paths with `..` to prevent SWFs from crawling the file system on desktop.
// Flash will generally fail to save shared objects with a path component starting with `.`, // Flash will generally fail to save shared objects with a path component starting with `.`,

View File

@ -108,9 +108,9 @@ impl Manufacturer {
}; };
if version <= 8 { if version <= 8 {
format!("Macromedia {}", os_part) format!("Macromedia {os_part}")
} else { } else {
format!("Adobe {}", os_part) format!("Adobe {os_part}")
} }
} }

View File

@ -23,7 +23,7 @@ where
let this = root.object().coerce_to_object(&mut activation); let this = root.object().coerce_to_object(&mut activation);
let result = test(&mut activation, this); let result = test(&mut activation, this);
if let Err(e) = result { if let Err(e) = result {
panic!("Encountered exception during test: {}", e); panic!("Encountered exception during test: {e}");
} }
}) })
} }

View File

@ -655,7 +655,7 @@ fn f64_to_string(mut n: f64) -> Cow<'static, str> {
buf.truncate(1); buf.truncate(1);
} }
} }
let _ = write!(&mut buf, "e{:+}", exp); let _ = write!(&mut buf, "e{exp:+}");
} }
// One final band-aid to eliminate any leading zeros. // One final band-aid to eliminate any leading zeros.

View File

@ -246,7 +246,7 @@ impl<'a, 'gc, 'gc_context> Activation<'a, 'gc, 'gc_context> {
self.resolve_definition(name)? self.resolve_definition(name)?
.and_then(|maybe| maybe.as_object()) .and_then(|maybe| maybe.as_object())
.and_then(|o| o.as_class_object()) .and_then(|o| o.as_class_object())
.ok_or_else(|| format!("Attempted to resolve nonexistent type {:?}", name).into()) .ok_or_else(|| format!("Attempted to resolve nonexistent type {name:?}").into())
} }
/// Resolve a type name to a class. /// Resolve a type name to a class.
@ -312,8 +312,8 @@ impl<'a, 'gc, 'gc_context> Activation<'a, 'gc, 'gc_context> {
return Ok(Value::Undefined); return Ok(Value::Undefined);
} else { } else {
return Err(format!( return Err(format!(
"Param {} (index {}) was missing when calling {}", "Param {} (index {index}) was missing when calling {method_name}",
param_config.param_name, index, method_name param_config.param_name
) )
.into()); .into());
}; };
@ -564,7 +564,7 @@ impl<'a, 'gc, 'gc_context> Activation<'a, 'gc, 'gc_context> {
self.local_registers self.local_registers
.get(id) .get(id)
.cloned() .cloned()
.ok_or_else(|| format!("Out of bounds register read: {}", id).into()) .ok_or_else(|| format!("Out of bounds register read: {id}").into())
} }
/// Set a local register. /// Set a local register.
@ -580,7 +580,7 @@ impl<'a, 'gc, 'gc_context> Activation<'a, 'gc, 'gc_context> {
Ok(()) Ok(())
} else { } else {
Err(format!("Out of bounds register write: {}", id).into()) Err(format!("Out of bounds register write: {id}").into())
} }
} }

View File

@ -53,6 +53,6 @@ impl<'gc> std::fmt::Display for CallStack<'gc> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut output = WString::new(); let mut output = WString::new();
self.display(&mut output); self.display(&mut output);
write!(f, "{}", output) write!(f, "{output}")
} }
} }

View File

@ -122,7 +122,7 @@ fn error_constructor<'gc>(
impl<'gc> std::fmt::Display for Error<'gc> { impl<'gc> std::fmt::Display for Error<'gc> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self) write!(f, "{self:?}")
} }
} }

View File

@ -764,7 +764,7 @@ pub fn draw<'gc>(
} else if let Some(source_bitmap) = source.as_bitmap_data() { } else if let Some(source_bitmap) = source.as_bitmap_data() {
IBitmapDrawable::BitmapData(source_bitmap) IBitmapDrawable::BitmapData(source_bitmap)
} else { } else {
return Err(format!("BitmapData.draw: unexpected source {:?}", source).into()); return Err(format!("BitmapData.draw: unexpected source {source:?}").into());
}; };
bitmap_data.draw( bitmap_data.draw(

View File

@ -941,7 +941,7 @@ fn set_mask<'gc>(
.coerce_to_object(activation)? .coerce_to_object(activation)?
.as_display_object() .as_display_object()
.ok_or_else(|| -> Error { .ok_or_else(|| -> Error {
format!("Mask is not a DisplayObject: {:?}", mask).into() format!("Mask is not a DisplayObject: {mask:?}").into()
})?; })?;
this.set_masker(activation.context.gc_context, Some(mask), true); this.set_masker(activation.context.gc_context, Some(mask), true);

View File

@ -407,7 +407,7 @@ pub fn remove_children<'gc>(
} }
if from > to { if from > to {
return Err(format!("RangeError: Range {} to {} is invalid", from, to).into()); return Err(format!("RangeError: Range {from} to {to} is invalid").into());
} }
ctr.remove_range( ctr.remove_range(
@ -475,11 +475,11 @@ pub fn swap_children_at<'gc>(
let bounds = ctr.num_children(); let bounds = ctr.num_children();
if index0 < 0 || index0 as usize >= bounds { if index0 < 0 || index0 as usize >= bounds {
return Err(format!("RangeError: Index {} is out of bounds", index0).into()); return Err(format!("RangeError: Index {index0} is out of bounds").into());
} }
if index1 < 0 || index1 as usize >= bounds { if index1 < 0 || index1 as usize >= bounds {
return Err(format!("RangeError: Index {} is out of bounds", index1).into()); return Err(format!("RangeError: Index {index1} is out of bounds").into());
} }
let child0 = ctr.child_by_index(index0 as usize).unwrap(); let child0 = ctr.child_by_index(index0 as usize).unwrap();

View File

@ -153,7 +153,7 @@ pub fn get_local<'gc>(
// Final SO path: foo.com/folder/game.swf/SOName // Final SO path: foo.com/folder/game.swf/SOName
// SOName may be a path containing slashes. In this case, prefix with # to mimic Flash Player behavior. // SOName may be a path containing slashes. In this case, prefix with # to mimic Flash Player behavior.
let prefix = if name.contains('/') { "#" } else { "" }; let prefix = if name.contains('/') { "#" } else { "" };
let full_name = format!("{}/{}/{}{}", movie_host, local_path, prefix, name); let full_name = format!("{movie_host}/{local_path}/{prefix}{name}");
// Avoid any paths with `..` to prevent SWFs from crawling the file system on desktop. // Avoid any paths with `..` to prevent SWFs from crawling the file system on desktop.
// Flash will generally fail to save shared objects with a path component starting with `.`, // Flash will generally fail to save shared objects with a path component starting with `.`,

View File

@ -32,7 +32,7 @@ pub fn load<'gc>(
} else if &data_format == b"variables" { } else if &data_format == b"variables" {
DataFormat::Variables DataFormat::Variables
} else { } else {
return Err(format!("Unknown data format: {}", data_format).into()); return Err(format!("Unknown data format: {data_format}").into());
}; };
return spawn_fetch(activation, this, request, data_format); return spawn_fetch(activation, this, request, data_format);

View File

@ -624,7 +624,7 @@ pub fn set_type<'gc>(
} else if &is_editable == b"dynamic" { } else if &is_editable == b"dynamic" {
this.set_editable(false, &mut activation.context); this.set_editable(false, &mut activation.context);
} else { } else {
return Err(format!("Invalid TextField.type: {}", is_editable).into()); return Err(format!("Invalid TextField.type: {is_editable}").into());
} }
} }

View File

@ -151,7 +151,7 @@ fn to_exponential<'gc>(
return Ok(AvmString::new_utf8( return Ok(AvmString::new_utf8(
activation.context.gc_context, activation.context.gc_context,
format!("{0:.1$e}", number, digits) format!("{number:.digits$e}")
.replace('e', "e+") .replace('e', "e+")
.replace("e+-", "e-") .replace("e+-", "e-")
.replace("e+0", ""), .replace("e+0", ""),

View File

@ -164,7 +164,7 @@ fn to_exponential<'gc>(
return Ok(AvmString::new_utf8( return Ok(AvmString::new_utf8(
activation.context.gc_context, activation.context.gc_context,
format!("{0:.1$e}", number, digits) format!("{number:.digits$e}")
.replace('e', "e+") .replace('e', "e+")
.replace("e+-", "e-") .replace("e+-", "e-")
.replace("e+0", ""), .replace("e+0", ""),
@ -198,7 +198,7 @@ fn to_fixed<'gc>(
return Ok(AvmString::new_utf8( return Ok(AvmString::new_utf8(
activation.context.gc_context, activation.context.gc_context,
format!("{0:.1$}", number, digits), format!("{number:.digits$}"),
) )
.into()); .into());
} }
@ -234,7 +234,7 @@ pub fn print_with_precision<'gc>(
} else { } else {
Ok(AvmString::new_utf8( Ok(AvmString::new_utf8(
activation.context.gc_context, activation.context.gc_context,
format!("{}", precision), format!("{precision}"),
)) ))
} }
} }

View File

@ -111,9 +111,9 @@ pub fn escape<'gc>(
output.push(x); output.push(x);
} else { } else {
let encode = if x <= u8::MAX.into() { let encode = if x <= u8::MAX.into() {
format!("%{:02X}", x) format!("%{x:02X}")
} else { } else {
format!("%u{:04X}", x) format!("%u{x:04X}")
}; };
output.push_str(WStr::from_units(encode.as_bytes())); output.push_str(WStr::from_units(encode.as_bytes()));
} }

View File

@ -150,7 +150,7 @@ fn to_exponential<'gc>(
return Ok(AvmString::new_utf8( return Ok(AvmString::new_utf8(
activation.context.gc_context, activation.context.gc_context,
format!("{0:.1$e}", number, digits) format!("{number:.digits$e}")
.replace('e', "e+") .replace('e', "e+")
.replace("e+-", "e-") .replace("e+-", "e-")
.replace("e+0", ""), .replace("e+0", ""),

View File

@ -425,7 +425,7 @@ pub trait TObject<'gc>: 'gc + Collect + Debug + Into<Object<'gc>> + Clone + Copy
return method_object.call(Some(self.into()), arguments, activation); return method_object.call(Some(self.into()), arguments, activation);
} }
Err(format!("Cannot call unknown method id {}", id).into()) Err(format!("Cannot call unknown method id {id}").into())
} }
/// Implements the `in` opcode and AS3 operator. /// Implements the `in` opcode and AS3 operator.
@ -735,7 +735,7 @@ pub trait TObject<'gc>: 'gc + Collect + Debug + Into<Object<'gc>> + Clone + Copy
Ok(AvmString::new_utf8( Ok(AvmString::new_utf8(
activation.context.gc_context, activation.context.gc_context,
format!("[object {}]", class_name), format!("[object {class_name}]"),
) )
.into()) .into())
} }
@ -759,7 +759,7 @@ pub trait TObject<'gc>: 'gc + Collect + Debug + Into<Object<'gc>> + Clone + Copy
Ok(AvmString::new_utf8( Ok(AvmString::new_utf8(
activation.context.gc_context, activation.context.gc_context,
format!("[object {}]", class_name), format!("[object {class_name}]"),
) )
.into()) .into())
} }

View File

@ -317,7 +317,7 @@ impl<'gc> ClassObject<'gc> {
let interface = scope.resolve(&interface_name, activation)?; let interface = scope.resolve(&interface_name, activation)?;
if interface.is_none() { if interface.is_none() {
return Err(format!("Could not resolve interface {:?}", interface_name).into()); return Err(format!("Could not resolve interface {interface_name:?}").into());
} }
let iface_class = interface let iface_class = interface

View File

@ -123,7 +123,7 @@ impl<'gc> TObject<'gc> for PrimitiveObject<'gc> {
Ok(AvmString::new_utf8( Ok(AvmString::new_utf8(
activation.context.gc_context, activation.context.gc_context,
format!("[object {}]", class_name), format!("[object {class_name}]"),
) )
.into()) .into())
} }

View File

@ -293,7 +293,7 @@ impl<'gc> ScriptObjectData<'gc> {
self.slots self.slots
.get(id as usize) .get(id as usize)
.cloned() .cloned()
.ok_or_else(|| format!("Slot index {} out of bounds!", id).into()) .ok_or_else(|| format!("Slot index {id} out of bounds!").into())
} }
/// Set a slot by its index. /// Set a slot by its index.
@ -307,7 +307,7 @@ impl<'gc> ScriptObjectData<'gc> {
*slot = value; *slot = value;
Ok(()) Ok(())
} else { } else {
Err(format!("Slot index {} out of bounds!", id).into()) Err(format!("Slot index {id} out of bounds!").into())
} }
} }
@ -322,7 +322,7 @@ impl<'gc> ScriptObjectData<'gc> {
*slot = value; *slot = value;
Ok(()) Ok(())
} else { } else {
Err(format!("Slot index {} out of bounds!", id).into()) Err(format!("Slot index {id} out of bounds!").into())
} }
} }

View File

@ -176,11 +176,11 @@ fn resolve_class_private<'gc>(
txunit txunit
.get_loaded_private_trait_script(name) .get_loaded_private_trait_script(name)
.ok_or_else(|| { .ok_or_else(|| {
Error::from(format!("Could not find script for class trait {:?}", name)) Error::from(format!("Could not find script for class trait {name:?}"))
})? })?
.globals(&mut activation.context)? .globals(&mut activation.context)?
} else { } else {
return Err(format!("Missing script and translation unit for class {:?}", name).into()); return Err(format!("Missing script and translation unit for class {name:?}").into());
}; };
Ok(globals Ok(globals

View File

@ -180,8 +180,8 @@ impl<'gc> QName<'gc> {
impl<'gc> Debug for QName<'gc> { impl<'gc> Debug for QName<'gc> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
match self.to_qualified_name_no_mc() { match self.to_qualified_name_no_mc() {
Either::Left(name) => write!(f, "{}", name), Either::Left(name) => write!(f, "{name}"),
Either::Right(name) => write!(f, "{}", name), Either::Right(name) => write!(f, "{name}"),
} }
} }
} }

View File

@ -250,7 +250,7 @@ impl<'gc> TranslationUnit<'gc> {
.constant_pool .constant_pool
.strings .strings
.get(string_index as usize - 1) .get(string_index as usize - 1)
.ok_or_else(|| format!("Unknown string constant {}", string_index))?, .ok_or_else(|| format!("Unknown string constant {string_index}"))?,
); );
write.strings[string_index as usize] = Some(avm_string); write.strings[string_index as usize] = Some(avm_string);

View File

@ -543,7 +543,7 @@ impl<'gc> Value<'gc> {
Value::Object(ns) => ns Value::Object(ns) => ns
.as_namespace() .as_namespace()
.ok_or_else(|| "Expected Namespace, found Object".into()), .ok_or_else(|| "Expected Namespace, found Object".into()),
_ => Err(format!("Expected Namespace, found {:?}", self).into()), _ => Err(format!("Expected Namespace, found {self:?}").into()),
} }
} }
@ -562,11 +562,11 @@ impl<'gc> Value<'gc> {
Value::Object(num) => match num.value_of(mc)? { Value::Object(num) => match num.value_of(mc)? {
Value::Number(num) => Ok(num), Value::Number(num) => Ok(num),
Value::Integer(num) => Ok(num as f64), Value::Integer(num) => Ok(num as f64),
_ => Err(format!("Expected Number, int, or uint, found {:?}", self).into()), _ => Err(format!("Expected Number, int, or uint, found {self:?}").into()),
}, },
Value::Number(num) => Ok(*num), Value::Number(num) => Ok(*num),
Value::Integer(num) => Ok(*num as f64), Value::Integer(num) => Ok(*num as f64),
_ => Err(format!("Expected Number, int, or uint, found {:?}", self).into()), _ => Err(format!("Expected Number, int, or uint, found {self:?}").into()),
} }
} }
@ -817,7 +817,7 @@ impl<'gc> Value<'gc> {
) -> Result<AvmString<'gc>, Error<'gc>> { ) -> Result<AvmString<'gc>, Error<'gc>> {
Ok(match self { Ok(match self {
Value::String(s) => { Value::String(s) => {
AvmString::new_utf8(activation.context.gc_context, format!("\"{}\"", s)) AvmString::new_utf8(activation.context.gc_context, format!("\"{s}\""))
} }
Value::Object(_) => self Value::Object(_) => self
.coerce_to_primitive(Some(Hint::String), activation)? .coerce_to_primitive(Some(Hint::String), activation)?
@ -986,7 +986,7 @@ impl<'gc> Value<'gc> {
let name = class.inner_class_definition().read().name(); let name = class.inner_class_definition().read().name();
Err(format!("Cannot coerce {:?} to an {:?}", self, name).into()) Err(format!("Cannot coerce {self:?} to an {name:?}").into())
} }
/// Determine if this value is any kind of number. /// Determine if this value is any kind of number.

View File

@ -1056,7 +1056,7 @@ impl<'gc> BitmapData<'gc> {
Err(ruffle_render::error::Error::Unimplemented) => { Err(ruffle_render::error::Error::Unimplemented) => {
log::warn!("BitmapData.draw: Not yet implemented") log::warn!("BitmapData.draw: Not yet implemented")
} }
Err(e) => panic!("BitmapData.draw failed: {:?}", e), Err(e) => panic!("BitmapData.draw failed: {e:?}"),
} }
} }
} }

View File

@ -938,7 +938,7 @@ pub trait TDisplayObject<'gc>:
WString::new() WString::new()
} else { } else {
// Other levels do append their name. // Other levels do append their name.
WString::from_utf8_owned(format!("_level{}", level)) WString::from_utf8_owned(format!("_level{level}"))
} }
} }
} }

View File

@ -835,8 +835,8 @@ impl Player {
let level = display_object.depth(); let level = display_object.depth();
let object = display_object.object().coerce_to_object(&mut activation); let object = display_object.object().coerce_to_object(&mut activation);
dumper.print_variables( dumper.print_variables(
&format!("Level #{}:", level), &format!("Level #{level}:"),
&format!("_level{}", level), &format!("_level{level}"),
&object, &object,
&mut activation, &mut activation,
); );

View File

@ -168,7 +168,7 @@ fn load_movie(url: &Url, opt: &Opt) -> Result<SwfMovie, Error> {
let client = builder.build().context("Couldn't create HTTP client")?; let client = builder.build().context("Couldn't create HTTP client")?;
let response = client let response = client
.get(url.to_string()) .get(url.to_string())
.with_context(|| format!("Couldn't load URL {}", url))?; .with_context(|| format!("Couldn't load URL {url}"))?;
let mut buffer: Vec<u8> = Vec::new(); let mut buffer: Vec<u8> = Vec::new();
response response
.into_body() .into_body()
@ -218,7 +218,7 @@ impl App {
.and_then(|segments| segments.last()) .and_then(|segments| segments.last())
.unwrap_or_else(|| movie_url.as_str()); .unwrap_or_else(|| movie_url.as_str());
format!("Ruffle - {}", filename) format!("Ruffle - {filename}")
} else { } else {
"Ruffle".into() "Ruffle".into()
}; };
@ -824,7 +824,7 @@ fn run_timedemo(opt: Opt) -> Result<(), Error> {
let end = Instant::now(); let end = Instant::now();
let duration = end.duration_since(start); let duration = end.duration_since(start);
println!("Ran {} frames in {}s.", num_frames, duration.as_secs_f32()); println!("Ran {num_frames} frames in {}s.", duration.as_secs_f32());
Ok(()) Ok(())
} }
@ -851,7 +851,7 @@ fn init() {
fn panic_hook() { fn panic_hook() {
CALLSTACK.with(|callstack| { CALLSTACK.with(|callstack| {
if let Some(callstack) = &*callstack.borrow() { if let Some(callstack) = &*callstack.borrow() {
callstack.avm2(|callstack| println!("AVM2 stack trace: {}", callstack)) callstack.avm2(|callstack| println!("AVM2 stack trace: {callstack}"))
} }
}); });
} }

View File

@ -120,7 +120,7 @@ impl NavigatorBackend for ExternalNavigatorBackend {
let full_url = match self.base_url.join(request.url()) { let full_url = match self.base_url.join(request.url()) {
Ok(url) => url, Ok(url) => url,
Err(e) => { Err(e) => {
let msg = format!("Invalid URL {}: {}", request.url(), e); let msg = format!("Invalid URL {}: {e}", request.url());
return Box::pin(async move { Err(Error::FetchError(msg)) }); return Box::pin(async move { Err(Error::FetchError(msg)) });
} }
}; };

View File

@ -34,7 +34,7 @@ impl DiskStorageBackend {
} }
fn get_shared_object_path(&self, name: &str) -> PathBuf { fn get_shared_object_path(&self, name: &str) -> PathBuf {
self.shared_objects_path.join(format!("{}.sol", name)) self.shared_objects_path.join(format!("{name}.sol"))
} }
fn get_back_compat_shared_object_path(&self, name: &str) -> PathBuf { fn get_back_compat_shared_object_path(&self, name: &str) -> PathBuf {

View File

@ -243,7 +243,7 @@ fn capture_single_swf(descriptors: Arc<Descriptors>, opt: &Opt) -> Result<()> {
} else { } else {
for (frame, image) in frames.iter().enumerate() { for (frame, image) in frames.iter().enumerate() {
let mut path: PathBuf = (&output).into(); let mut path: PathBuf = (&output).into();
path.push(format!("{}.png", frame)); path.push(format!("{frame}.png"));
image.save(&path)?; image.save(&path)?;
} }
} }
@ -266,7 +266,7 @@ fn capture_single_swf(descriptors: Arc<Descriptors>, opt: &Opt) -> Result<()> {
if let Some(progress) = progress { if let Some(progress) = progress {
progress.finish_with_message(message); progress.finish_with_message(message);
} else { } else {
println!("{}", message); println!("{message}");
} }
Ok(()) Ok(())
@ -331,7 +331,7 @@ fn capture_multiple_swfs(descriptors: Arc<Descriptors>, opt: &Opt) -> Result<()>
let _ = create_dir_all(&parent); let _ = create_dir_all(&parent);
for (frame, image) in frames.iter().enumerate() { for (frame, image) in frames.iter().enumerate() {
let mut destination = parent.clone(); let mut destination = parent.clone();
destination.push(format!("{}.png", frame)); destination.push(format!("{frame}.png"));
image.save(&destination)?; image.save(&destination)?;
} }
} }
@ -358,7 +358,7 @@ fn capture_multiple_swfs(descriptors: Arc<Descriptors>, opt: &Opt) -> Result<()>
if let Some(progress) = progress { if let Some(progress) = progress {
progress.finish_with_message(message); progress.finish_with_message(message);
} else { } else {
println!("{}", message); println!("{message}");
} }
Ok(()) Ok(())

View File

@ -67,7 +67,7 @@ impl CanvasColor {
let g = (*g as f32 * cxform.g_mult.to_f32() + (cxform.g_add as f32)) as u8; let g = (*g as f32 * cxform.g_mult.to_f32() + (cxform.g_add as f32)) as u8;
let b = (*b as f32 * cxform.b_mult.to_f32() + (cxform.b_add as f32)) as u8; let b = (*b as f32 * cxform.b_mult.to_f32() + (cxform.b_add as f32)) as u8;
let a = (*a as f32 * cxform.a_mult.to_f32() + (cxform.a_add as f32)) as u8; let a = (*a as f32 * cxform.a_mult.to_f32() + (cxform.a_add as f32)) as u8;
let colstring = format!("rgba({},{},{},{})", r, g, b, f32::from(a) / 255.0); let colstring = format!("rgba({r},{g},{b},{})", f32::from(a) / 255.0);
Self(colstring, r, g, b, a) Self(colstring, r, g, b, a)
} }
} }

View File

@ -380,7 +380,7 @@ impl<'a> NagaBuilder<'a> {
// and return them at the end of the function. // and return them at the end of the function.
let local = self.func.local_variables.append( let local = self.func.local_variables.append(
LocalVariable { LocalVariable {
name: Some(format!("varying_{}", index)), name: Some(format!("varying_{index}")),
ty: self.vec4f, ty: self.vec4f,
init: None, init: None,
}, },
@ -398,7 +398,7 @@ impl<'a> NagaBuilder<'a> {
if let TypeInner::Struct { members, .. } = &mut self.return_type.inner { if let TypeInner::Struct { members, .. } = &mut self.return_type.inner {
members.push(StructMember { members.push(StructMember {
name: Some(format!("varying_{}", index)), name: Some(format!("varying_{index}")),
ty: self.vec4f, ty: self.vec4f,
binding: Some(Binding::Location { binding: Some(Binding::Location {
location: index as u32, location: index as u32,

View File

@ -10,7 +10,7 @@ pub fn to_wgsl(module: &Module) -> String {
let mut validator = Validator::new(ValidationFlags::all(), Capabilities::all()); let mut validator = Validator::new(ValidationFlags::all(), Capabilities::all());
let module_info = validator let module_info = validator
.validate(module) .validate(module)
.unwrap_or_else(|e| panic!("Validation failed: {}", e)); .unwrap_or_else(|e| panic!("Validation failed: {e}"));
let mut writer = let mut writer =
naga::back::wgsl::Writer::new(&mut out, naga::back::wgsl::WriterFlags::EXPLICIT_TYPES); naga::back::wgsl::Writer::new(&mut out, naga::back::wgsl::WriterFlags::EXPLICIT_TYPES);

View File

@ -399,7 +399,7 @@ impl<T: RenderTarget + 'static> RenderBackend for WgpuRenderBackend<T> {
) )
.is_some() .is_some()
{ {
panic!("Overwrote existing bitmap {:?}", handle); panic!("Overwrote existing bitmap {handle:?}");
} }
Ok(handle) Ok(handle)

View File

@ -28,7 +28,7 @@ pub fn analyze(results: impl Iterator<Item = FileResults>) {
} }
} }
println!("Scanned {} swf files.", total); println!("Scanned {total} swf files.");
let digits = max( let digits = max(
(start as f64).log10().ceil() as usize, (start as f64).log10().ceil() as usize,
@ -67,7 +67,7 @@ pub fn analyze(results: impl Iterator<Item = FileResults>) {
decompress, decompress,
digits = digits digits = digits
); );
println!("{:>digits$} movies failed to parse", parse, digits = digits); println!("{parse:>digits$} movies failed to parse");
println!( println!(
"{:>digits$} movies failed to execute", "{:>digits$} movies failed to execute",
execute, execute,
@ -91,7 +91,7 @@ pub fn analyze_main(opt: AnalyzeOpt) -> Result<(), std::io::Error> {
Err(e) => { Err(e) => {
// Treat unparseable CSV rows as a scanner panic // Treat unparseable CSV rows as a scanner panic
FileResults { FileResults {
error: Some(format!("{}", e)), error: Some(format!("{e}")),
..FileResults::default() ..FileResults::default()
} }
} }

View File

@ -79,7 +79,7 @@ pub fn execute_report_main(execute_report_opt: ExecuteReportOpt) -> Result<(), s
let data = match std::fs::read(&file_path) { let data = match std::fs::read(&file_path) {
Ok(data) => data, Ok(data) => data,
Err(e) => { Err(e) => {
file_result.error = Some(format!("File error: {}", e)); file_result.error = Some(format!("File error: {e}"));
checkpoint(&mut file_result, &start, &mut writer)?; checkpoint(&mut file_result, &start, &mut writer)?;
return Ok(()); return Ok(());
@ -119,7 +119,7 @@ pub fn execute_report_main(execute_report_opt: ExecuteReportOpt) -> Result<(), s
file_result.uncompressed_len = Some(swf.header.uncompressed_len()); file_result.uncompressed_len = Some(swf.header.uncompressed_len());
file_result.compression = Some(swf.header.compression().into()); file_result.compression = Some(swf.header.compression().into());
file_result.version = Some(swf.header.version()); file_result.version = Some(swf.header.version());
file_result.stage_size = Some(format!("{}x{}", stage_width, stage_height)); file_result.stage_size = Some(format!("{stage_width}x{stage_height}"));
file_result.frame_rate = Some(swf.header.frame_rate().into()); file_result.frame_rate = Some(swf.header.frame_rate().into());
file_result.num_frames = Some(swf.header.num_frames()); file_result.num_frames = Some(swf.header.num_frames());
file_result.use_direct_blit = Some(swf.header.use_direct_blit()); file_result.use_direct_blit = Some(swf.header.use_direct_blit());
@ -131,13 +131,13 @@ pub fn execute_report_main(execute_report_opt: ExecuteReportOpt) -> Result<(), s
}); });
} }
Err(e) => { Err(e) => {
file_result.error = Some(format!("Parse error: {}", e)); file_result.error = Some(format!("Parse error: {e}"));
checkpoint(&mut file_result, &start, &mut writer)?; checkpoint(&mut file_result, &start, &mut writer)?;
} }
}, },
Err(e) => match e.downcast::<String>() { Err(e) => match e.downcast::<String>() {
Ok(e) => { Ok(e) => {
file_result.error = Some(format!("PANIC: {}", e)); file_result.error = Some(format!("PANIC: {e}"));
checkpoint(&mut file_result, &start, &mut writer)?; checkpoint(&mut file_result, &start, &mut writer)?;
} }
Err(_) => { Err(_) => {
@ -154,7 +154,7 @@ pub fn execute_report_main(execute_report_opt: ExecuteReportOpt) -> Result<(), s
if let Err(e) = catch_unwind(|| execute_swf(&file_path)) { if let Err(e) = catch_unwind(|| execute_swf(&file_path)) {
match e.downcast::<String>() { match e.downcast::<String>() {
Ok(e) => { Ok(e) => {
file_result.error = Some(format!("PANIC: {}", e)); file_result.error = Some(format!("PANIC: {e}"));
checkpoint(&mut file_result, &start, &mut writer)?; checkpoint(&mut file_result, &start, &mut writer)?;
} }
Err(_) => { Err(_) => {

View File

@ -164,7 +164,7 @@ where
{ {
let mut out = String::with_capacity(2 * hash.len()); let mut out = String::with_capacity(2 * hash.len());
for byte in hash { for byte in hash {
write!(out, "{:02X}", byte).map_err(|e| SerError::custom(e.to_string()))?; write!(out, "{byte:02X}").map_err(|e| SerError::custom(e.to_string()))?;
} }
s.serialize_str(&out) s.serialize_str(&out)

View File

@ -97,7 +97,7 @@ pub fn scan_file<P: AsRef<OsStr>>(exec_path: P, file: &DirEntry, name: &str) ->
file_results.error = Some( file_results.error = Some(
file_results file_results
.error .error
.map(|e| format!("{}\n{}", e, panic_error)) .map(|e| format!("{e}\n{panic_error}"))
.unwrap_or(panic_error), .unwrap_or(panic_error),
); );
} }
@ -145,7 +145,7 @@ pub fn scan_main(opt: ScanOpt) -> Result<(), std::io::Error> {
.ser_bridge() .ser_bridge()
.map(|result| { .map(|result| {
if let Err(e) = writer.serialize(result.clone()) { if let Err(e) = writer.serialize(result.clone()) {
eprintln!("{}", e); eprintln!("{e}");
}; };
result result

View File

@ -123,9 +123,9 @@ impl OpCode {
pub fn format(opcode: u8) -> String { pub fn format(opcode: u8) -> String {
if let Some(op) = Self::from_u8(opcode) { if let Some(op) = Self::from_u8(opcode) {
format!("{:?}", op) format!("{op:?}")
} else { } else {
format!("Unknown({})", opcode) format!("Unknown({opcode})")
} }
} }
} }

View File

@ -430,7 +430,7 @@ pub mod tests {
match reader.read_action() { match reader.read_action() {
Err(crate::error::Error::Avm1ParseError { .. }) => (), Err(crate::error::Error::Avm1ParseError { .. }) => (),
result => { result => {
panic!("Expected Avm1ParseError, got {:?}", result); panic!("Expected Avm1ParseError, got {result:?}");
} }
} }
} }

View File

@ -888,7 +888,7 @@ pub mod tests {
return do_abc.data.to_vec(); return do_abc.data.to_vec();
} }
} }
panic!("ABC tag not found in {}", path); panic!("ABC tag not found in {path}");
} }
#[test] #[test]

View File

@ -78,7 +78,7 @@ impl fmt::Display for Error {
Self::Avm1ParseError { opcode, source } => { Self::Avm1ParseError { opcode, source } => {
write!(f, "Error parsing AVM1 action {}", OpCode::format(*opcode))?; write!(f, "Error parsing AVM1 action {}", OpCode::format(*opcode))?;
if let Some(source) = source { if let Some(source) = source {
write!(f, ": {}", source)?; write!(f, ": {source}")?;
} }
Ok(()) Ok(())
} }
@ -91,8 +91,8 @@ impl fmt::Display for Error {
) )
} }
Self::IoError(e) => e.fmt(f), Self::IoError(e) => e.fmt(f),
Self::InvalidData(message) => write!(f, "Invalid data: {}", message), Self::InvalidData(message) => write!(f, "Invalid data: {message}"),
Self::Unsupported(message) => write!(f, "Unsupported data: {}", message), Self::Unsupported(message) => write!(f, "Unsupported data: {message}"),
} }
} }
} }

View File

@ -3016,7 +3016,7 @@ pub mod tests {
let mut reader = Reader::new(&tag_bytes[..], swf_version); let mut reader = Reader::new(&tag_bytes[..], swf_version);
let parsed_tag = match reader.read_tag() { let parsed_tag = match reader.read_tag() {
Ok(tag) => tag, Ok(tag) => tag,
Err(e) => panic!("Error parsing tag: {}", e), Err(e) => panic!("Error parsing tag: {e}"),
}; };
assert_eq!( assert_eq!(
parsed_tag, expected_tag, parsed_tag, expected_tag,
@ -3049,7 +3049,7 @@ pub mod tests {
match reader.read_tag() { match reader.read_tag() {
Err(crate::error::Error::SwfParseError { .. }) => (), Err(crate::error::Error::SwfParseError { .. }) => (),
result => { result => {
panic!("Expected SwfParseError, got {:?}", result); panic!("Expected SwfParseError, got {result:?}");
} }
} }
} }

View File

@ -95,9 +95,9 @@ impl TagCode {
pub fn format(tag_code: u16) -> String { pub fn format(tag_code: u16) -> String {
if let Some(tag_code) = TagCode::from_u16(tag_code) { if let Some(tag_code) = TagCode::from_u16(tag_code) {
format!("{:?}", tag_code) format!("{tag_code:?}")
} else { } else {
format!("Unknown({})", tag_code) format!("Unknown({tag_code})")
} }
} }
} }

View File

@ -1510,15 +1510,15 @@ fn run_swf(
} }
Err(e) => { Err(e) => {
eprintln!( eprintln!(
"Failed to open expected image {:?}: {:?}", "Failed to open expected image {:?}: {e:?}",
&expected_image_path, e &expected_image_path
); );
false false
} }
}; };
if !matches { if !matches {
let actual_image_path = base_path.join(format!("actual-{}.png", suffix)); let actual_image_path = base_path.join(format!("actual-{suffix}.png"));
actual_image.save_with_format(&actual_image_path, image::ImageFormat::Png)?; actual_image.save_with_format(&actual_image_path, image::ImageFormat::Png)?;
panic!( panic!(
"Test output does not match expected image - saved actual image to {:?}", "Test output does not match expected image - saved actual image to {:?}",
@ -1561,7 +1561,7 @@ impl ExternalInterfaceTestProvider {
} }
fn do_trace(context: &mut UpdateContext<'_, '_, '_>, args: &[ExternalValue]) -> ExternalValue { fn do_trace(context: &mut UpdateContext<'_, '_, '_>, args: &[ExternalValue]) -> ExternalValue {
context.avm_trace(&format!("[ExternalInterface] trace: {:?}", args)); context.avm_trace(&format!("[ExternalInterface] trace: {args:?}"));
"Traced!".into() "Traced!".into()
} }

View File

@ -186,7 +186,7 @@ impl Ruffle {
pub fn new(parent: HtmlElement, js_player: JavascriptPlayer, config: JsValue) -> Promise { pub fn new(parent: HtmlElement, js_player: JavascriptPlayer, config: JsValue) -> Promise {
wasm_bindgen_futures::future_to_promise(async move { wasm_bindgen_futures::future_to_promise(async move {
let config: Config = serde_wasm_bindgen::from_value(config) let config: Config = serde_wasm_bindgen::from_value(config)
.map_err(|e| format!("Error parsing config: {}", e))?; .map_err(|e| format!("Error parsing config: {e}"))?;
if RUFFLE_GLOBAL_PANIC.is_completed() { if RUFFLE_GLOBAL_PANIC.is_completed() {
// If an actual panic happened, then we can't trust the state it left us in. // If an actual panic happened, then we can't trust the state it left us in.
@ -224,7 +224,7 @@ impl Ruffle {
/// This method should only be called once per player. /// This method should only be called once per player.
pub fn load_data(&mut self, swf_data: Uint8Array, parameters: JsValue) -> Result<(), JsValue> { pub fn load_data(&mut self, swf_data: Uint8Array, parameters: JsValue) -> Result<(), JsValue> {
let mut movie = SwfMovie::from_data(&swf_data.to_vec(), None, None) let mut movie = SwfMovie::from_data(&swf_data.to_vec(), None, None)
.map_err(|e| format!("Error loading movie: {}", e))?; .map_err(|e| format!("Error loading movie: {e}"))?;
movie.append_parameters(parse_movie_parameters(&parameters)); movie.append_parameters(parse_movie_parameters(&parameters));
self.on_metadata(movie.header()); self.on_metadata(movie.header());

View File

@ -186,7 +186,7 @@ impl NavigatorBackend for WebNavigatorBackend {
} }
let request = WebRequest::new_with_str_and_init(&url, &init) let request = WebRequest::new_with_str_and_init(&url, &init)
.map_err(|_| Error::FetchError(format!("Unable to create request for {}", url)))?; .map_err(|_| Error::FetchError(format!("Unable to create request for {url}")))?;
let window = web_sys::window().expect("window()"); let window = web_sys::window().expect("window()");
let fetchval = JsFuture::from(window.fetch_with_request(&request)) let fetchval = JsFuture::from(window.fetch_with_request(&request))

View File

@ -28,7 +28,7 @@ fn roundtrip() {
_ => false, _ => false,
}; };
assert!(eq, "expected {:?}, got {:?}", units, conv); assert!(eq, "expected {units:?}, got {conv:?}");
} }
test(b""); test(b"");
@ -76,15 +76,15 @@ fn fmt() {
let c = bstr!(b"\t\n\x03"); let c = bstr!(b"\t\n\x03");
let d = wstr!(0x202d 0x202e); let d = wstr!(0x202d 0x202e);
assert_eq!(format!("{}", a), "Hello world!"); assert_eq!(format!("{a}"), "Hello world!");
assert_eq!(format!("{}", b), "Hello world!"); assert_eq!(format!("{b}"), "Hello world!");
assert_eq!(format!("{}", c), "\t\n\x03"); assert_eq!(format!("{c}"), "\t\n\x03");
assert_eq!(format!("{}", d), "\u{202d}\u{202e}"); assert_eq!(format!("{d}"), "\u{202d}\u{202e}");
assert_eq!(format!("{:?}", a), "\"Hello world!\""); assert_eq!(format!("{a:?}"), "\"Hello world!\"");
assert_eq!(format!("{:?}", b), "\"Hello world!\""); assert_eq!(format!("{b:?}"), "\"Hello world!\"");
assert_eq!(format!("{:?}", c), "\"\\t\\n\\u{3}\""); assert_eq!(format!("{c:?}"), "\"\\t\\n\\u{3}\"");
assert_eq!(format!("{:?}", d), "\"\\u{202d}\\u{202e}\""); assert_eq!(format!("{d:?}"), "\"\\u{202d}\\u{202e}\"");
} }
#[test] #[test]