Skip to content

Commit

Permalink
style: simplify string formatting for readability (gfx-rs#6316)
Browse files Browse the repository at this point in the history
  • Loading branch information
hamirmahal authored Sep 25, 2024
1 parent fc2fd95 commit 8e787eb
Show file tree
Hide file tree
Showing 26 changed files with 59 additions and 71 deletions.
2 changes: 1 addition & 1 deletion benches/benches/root.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ impl DeviceState {

let adapter_info = adapter.get_info();

eprintln!("{:?}", adapter_info);
eprintln!("{adapter_info:?}");

let (device, queue) = block_on(adapter.request_device(
&wgpu::DeviceDescriptor {
Expand Down
2 changes: 1 addition & 1 deletion benches/benches/shader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ impl Inputs {
_ => continue,
},
Err(e) => {
eprintln!("Skipping file: {:?}", e);
eprintln!("Skipping file: {e:?}");
continue;
}
}
Expand Down
2 changes: 1 addition & 1 deletion examples/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ fn print_unknown_example(_result: Option<String>) {}
#[cfg(not(target_arch = "wasm32"))]
fn print_unknown_example(result: Option<String>) {
if let Some(example) = result {
println!("Unknown example: {}", example);
println!("Unknown example: {example}");
} else {
println!("Please specify an example as the first argument!");
}
Expand Down
2 changes: 1 addition & 1 deletion examples/src/timestamp_queries/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ async fn run() {

let queries = submit_render_and_compute_pass_with_queries(&device, &queue);
let raw_results = queries.wait_for_results(&device);
println!("Raw timestamp buffer contents: {:?}", raw_results);
println!("Raw timestamp buffer contents: {raw_results:?}");
QueryResults::from_raw_results(raw_results, timestamps_inside_passes).print(&queue);
}

Expand Down
4 changes: 2 additions & 2 deletions naga-cli/src/bin/naga.rs
Original file line number Diff line number Diff line change
Expand Up @@ -853,7 +853,7 @@ fn bulk_validate(args: Args, params: &Parameters) -> anyhow::Result<()> {
Ok(parsed) => parsed,
Err(error) => {
invalid.push(input_path.clone());
eprintln!("Error validating {}:", input_path);
eprintln!("Error validating {input_path}:");
eprintln!("{error}");
continue;
}
Expand All @@ -866,7 +866,7 @@ fn bulk_validate(args: Args, params: &Parameters) -> anyhow::Result<()> {

if let Err(error) = validator.validate(&module) {
invalid.push(input_path.clone());
eprintln!("Error validating {}:", input_path);
eprintln!("Error validating {input_path}:");
if let Some(input) = &input_text {
let filename = path.file_name().and_then(std::ffi::OsStr::to_str);
emit_annotated_error(&error, filename.unwrap_or("input"), input);
Expand Down
2 changes: 1 addition & 1 deletion naga/src/back/dot/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -698,7 +698,7 @@ fn write_function_expressions(
E::RayQueryGetIntersection { query, committed } => {
edges.insert("", query);
let ty = if committed { "Committed" } else { "Candidate" };
(format!("rayQueryGet{}Intersection", ty).into(), 4)
(format!("rayQueryGet{ty}Intersection").into(), 4)
}
E::SubgroupBallotResult => ("SubgroupBallotResult".into(), 4),
E::SubgroupOperationResult { .. } => ("SubgroupOperationResult".into(), 4),
Expand Down
12 changes: 6 additions & 6 deletions naga/src/back/glsl/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2645,15 +2645,15 @@ impl<'a, W: Write> Writer<'a, W> {
match literal {
// Floats are written using `Debug` instead of `Display` because it always appends the
// decimal part even it's zero which is needed for a valid glsl float constant
crate::Literal::F64(value) => write!(self.out, "{:?}LF", value)?,
crate::Literal::F32(value) => write!(self.out, "{:?}", value)?,
crate::Literal::F64(value) => write!(self.out, "{value:?}LF")?,
crate::Literal::F32(value) => write!(self.out, "{value:?}")?,
// Unsigned integers need a `u` at the end
//
// While `core` doesn't necessarily need it, it's allowed and since `es` needs it we
// always write it as the extra branch wouldn't have any benefit in readability
crate::Literal::U32(value) => write!(self.out, "{}u", value)?,
crate::Literal::I32(value) => write!(self.out, "{}", value)?,
crate::Literal::Bool(value) => write!(self.out, "{}", value)?,
crate::Literal::U32(value) => write!(self.out, "{value}u")?,
crate::Literal::I32(value) => write!(self.out, "{value}")?,
crate::Literal::Bool(value) => write!(self.out, "{value}")?,
crate::Literal::I64(_) => {
return Err(Error::Custom("GLSL has no 64-bit integer type".into()));
}
Expand Down Expand Up @@ -4614,7 +4614,7 @@ impl<'a, W: Write> Writer<'a, W> {

for i in 0..count.get() {
// Add the array accessor and recurse.
segments.push(format!("[{}]", i));
segments.push(format!("[{i}]"));
self.collect_push_constant_items(base, segments, layouter, offset, items);
segments.pop();
}
Expand Down
3 changes: 1 addition & 2 deletions naga/src/back/hlsl/help.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1046,8 +1046,7 @@ impl<'a, W: Write> super::Writer<'a, W> {
}
ref other => {
return Err(super::Error::Unimplemented(format!(
"Array length of base {:?}",
other
"Array length of base {other:?}"
)))
}
};
Expand Down
2 changes: 1 addition & 1 deletion naga/src/back/hlsl/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,7 @@ impl<W: fmt::Write> super::Writer<'_, W> {
self.write_store_value(module, &value, func_ctx)?;
writeln!(self.out, "));")?;
} else {
write!(self.out, "{}{}.Store(", level, var_name)?;
write!(self.out, "{level}{var_name}.Store(")?;
self.write_storage_address(module, &chain, func_ctx)?;
write!(self.out, ", ")?;
self.write_store_value(module, &value, func_ctx)?;
Expand Down
12 changes: 6 additions & 6 deletions naga/src/back/hlsl/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -965,7 +965,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
let constant = &module.constants[handle];
self.write_type(module, constant.ty)?;
let name = &self.names[&NameKey::Constant(handle)];
write!(self.out, " {}", name)?;
write!(self.out, " {name}")?;
// Write size for array type
if let TypeInner::Array { base, size, .. } = module.types[constant.ty].inner {
self.write_array_size(module, base, size)?;
Expand Down Expand Up @@ -2383,11 +2383,11 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
// decimal part even it's zero
crate::Literal::F64(value) => write!(self.out, "{value:?}L")?,
crate::Literal::F32(value) => write!(self.out, "{value:?}")?,
crate::Literal::U32(value) => write!(self.out, "{}u", value)?,
crate::Literal::I32(value) => write!(self.out, "{}", value)?,
crate::Literal::U64(value) => write!(self.out, "{}uL", value)?,
crate::Literal::I64(value) => write!(self.out, "{}L", value)?,
crate::Literal::Bool(value) => write!(self.out, "{}", value)?,
crate::Literal::U32(value) => write!(self.out, "{value}u")?,
crate::Literal::I32(value) => write!(self.out, "{value}")?,
crate::Literal::U64(value) => write!(self.out, "{value}uL")?,
crate::Literal::I64(value) => write!(self.out, "{value}L")?,
crate::Literal::Bool(value) => write!(self.out, "{value}")?,
crate::Literal::AbstractInt(_) | crate::Literal::AbstractFloat(_) => {
return Err(Error::Custom(
"Abstract types should not appear in IR presented to backends".into(),
Expand Down
3 changes: 1 addition & 2 deletions naga/src/back/msl/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -437,8 +437,7 @@ impl Options {
})
}
LocationMode::Uniform => Err(Error::GenericValidation(format!(
"Unexpected Binding::Location({}) for the Uniform mode",
location
"Unexpected Binding::Location({location}) for the Uniform mode"
))),
},
}
Expand Down
7 changes: 3 additions & 4 deletions naga/src/back/msl/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3820,12 +3820,11 @@ impl<W: Write> Writer<W> {
writeln!(self.out)?;
writeln!(
self.out,
"{} {defined_func_name}({arg_type_name} arg) {{
"{struct_name} {defined_func_name}({arg_type_name} arg) {{
{other_type_name} other;
{arg_type_name} fract = {NAMESPACE}::{called_func_name}(arg, other);
return {}{{ fract, other }};
}}",
struct_name, struct_name
return {struct_name}{{ fract, other }};
}}"
)?;
}
&crate::PredeclaredType::AtomicCompareExchangeWeakResult { .. } => {}
Expand Down
18 changes: 9 additions & 9 deletions naga/src/back/wgsl/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1221,31 +1221,31 @@ impl<W: Write> Writer<W> {

match expressions[expr] {
Expression::Literal(literal) => match literal {
crate::Literal::F32(value) => write!(self.out, "{}f", value)?,
crate::Literal::U32(value) => write!(self.out, "{}u", value)?,
crate::Literal::F32(value) => write!(self.out, "{value}f")?,
crate::Literal::U32(value) => write!(self.out, "{value}u")?,
crate::Literal::I32(value) => {
// `-2147483648i` is not valid WGSL. The most negative `i32`
// value can only be expressed in WGSL using AbstractInt and
// a unary negation operator.
if value == i32::MIN {
write!(self.out, "i32({})", value)?;
write!(self.out, "i32({value})")?;
} else {
write!(self.out, "{}i", value)?;
write!(self.out, "{value}i")?;
}
}
crate::Literal::Bool(value) => write!(self.out, "{}", value)?,
crate::Literal::F64(value) => write!(self.out, "{:?}lf", value)?,
crate::Literal::Bool(value) => write!(self.out, "{value}")?,
crate::Literal::F64(value) => write!(self.out, "{value:?}lf")?,
crate::Literal::I64(value) => {
// `-9223372036854775808li` is not valid WGSL. The most negative `i64`
// value can only be expressed in WGSL using AbstractInt and
// a unary negation operator.
if value == i64::MIN {
write!(self.out, "i64({})", value)?;
write!(self.out, "i64({value})")?;
} else {
write!(self.out, "{}li", value)?;
write!(self.out, "{value}li")?;
}
}
crate::Literal::U64(value) => write!(self.out, "{:?}lu", value)?,
crate::Literal::U64(value) => write!(self.out, "{value:?}lu")?,
crate::Literal::AbstractInt(_) | crate::Literal::AbstractFloat(_) => {
return Err(Error::Custom(
"Abstract types should not appear in IR presented to backends".into(),
Expand Down
4 changes: 2 additions & 2 deletions naga/src/front/wgsl/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -790,11 +790,11 @@ impl<'a> Error<'a> {
Error::ConcretizationFailed(ref error) => {
let ConcretizationFailedError { expr_span, ref expr_type, ref scalar, ref inner } = **error;
ParseError {
message: format!("failed to convert expression to a concrete type: {}", inner),
message: format!("failed to convert expression to a concrete type: {inner}"),
labels: vec![
(
expr_span,
format!("this expression has type {}", expr_type).into(),
format!("this expression has type {expr_type}").into(),
)
],
notes: vec![
Expand Down
2 changes: 1 addition & 1 deletion player/src/bin/play.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ fn main() {
Some(queue_id),
);
if let Err(e) = res {
panic!("{:?}", e);
panic!("{e:?}");
}
(device_id, queue_id)
}
Expand Down
2 changes: 1 addition & 1 deletion player/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ impl GlobalPlay for wgc::global::Global {
let module = ron::de::from_str(&code).unwrap();
wgc::pipeline::ShaderModuleSource::Naga(module)
} else {
panic!("Unknown shader {}", data);
panic!("Unknown shader {data}");
};
let (_, error) = self.device_create_shader_module(device, &desc, source, Some(id));
if let Some(e) = error {
Expand Down
15 changes: 7 additions & 8 deletions player/tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ struct Test<'a> {

fn map_callback(status: Result<(), wgc::resource::BufferAccessError>) {
if let Err(e) = status {
panic!("Buffer map error: {}", e);
panic!("Buffer map error: {e}");
}
}

Expand Down Expand Up @@ -88,7 +88,7 @@ impl Test<'_> {
.iter()
.map(|feature| {
wgt::Features::from_name(feature)
.unwrap_or_else(|| panic!("Invalid feature flag {}", feature))
.unwrap_or_else(|| panic!("Invalid feature flag {feature}"))
})
.fold(wgt::Features::empty(), |a, b| a | b);
Test {
Expand Down Expand Up @@ -120,7 +120,7 @@ impl Test<'_> {
Some(queue_id),
);
if let Err(e) = res {
panic!("{:?}", e);
panic!("{e:?}");
}

let mut command_buffer_id_manager = wgc::identity::IdentityManager::new();
Expand Down Expand Up @@ -186,8 +186,7 @@ impl Test<'_> {

if &expected_data[..] != contents {
panic!(
"Test expectation is not met!\nBuffer content was:\n{:?}\nbut expected:\n{:?}",
contents, expected_data
"Test expectation is not met!\nBuffer content was:\n{contents:?}\nbut expected:\n{expected_data:?}"
);
}
}
Expand All @@ -209,7 +208,7 @@ const BACKENDS: &[wgt::Backend] = &[

impl Corpus {
fn run_from(path: PathBuf) {
println!("Corpus {:?}", path);
println!("Corpus {path:?}");
let dir = path.parent().unwrap();
let corpus: Corpus = ron::de::from_reader(File::open(&path).unwrap()).unwrap();

Expand All @@ -219,7 +218,7 @@ impl Corpus {
}
let mut test_num = 0;
for test_path in &corpus.tests {
println!("\t\tTest '{:?}'", test_path);
println!("\t\tTest '{test_path:?}'");

let global = wgc::global::Global::new(
"test",
Expand All @@ -243,7 +242,7 @@ impl Corpus {
Err(_) => continue,
};

println!("\tBackend {:?}", backend);
println!("\tBackend {backend:?}");
let supported_features = global.adapter_features(adapter);
let downlevel_caps = global.adapter_downlevel_capabilities(adapter);

Expand Down
7 changes: 3 additions & 4 deletions tests/src/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,11 +188,10 @@ pub async fn compare_image_output(
sanitize_for_path(&adapter_info.driver)
);
// Determine the paths to write out the various intermediate files
let actual_path = Path::new(&path).with_file_name(
OsString::from_str(&format!("{}-{}-actual.png", file_stem, renderer)).unwrap(),
);
let actual_path = Path::new(&path)
.with_file_name(OsString::from_str(&format!("{file_stem}-{renderer}-actual.png")).unwrap());
let difference_path = Path::new(&path).with_file_name(
OsString::from_str(&format!("{}-{}-difference.png", file_stem, renderer,)).unwrap(),
OsString::from_str(&format!("{file_stem}-{renderer}-difference.png",)).unwrap(),
);

let mut all_passed;
Expand Down
2 changes: 1 addition & 1 deletion tests/src/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ impl TestInfo {
let names: ArrayVec<_, 4> = reasons.iter_names().map(|(name, _)| name).collect();
let names_text = names.join(" | ");

format!("Skipped Failure: {}", names_text)
format!("Skipped Failure: {names_text}")
} else if !unsupported_reasons.is_empty() {
skip = true;
format!("Unsupported: {}", unsupported_reasons.join(" | "))
Expand Down
4 changes: 2 additions & 2 deletions tests/tests/subgroup_operations/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,10 +123,10 @@ static SUBGROUP_OPERATIONS: GpuTestConfiguration = GpuTestConfiguration::new()
.enumerate()
.filter(|(_, (r, e))| *r != e)
{
write!(&mut msg, "thread {} failed tests:", thread).unwrap();
write!(&mut msg, "thread {thread} failed tests:").unwrap();
let difference = result ^ expected;
for i in (0..u32::BITS).filter(|i| (difference & (1 << i)) != 0) {
write!(&mut msg, " {},", i).unwrap();
write!(&mut msg, " {i},").unwrap();
}
writeln!(&mut msg).unwrap();
}
Expand Down
5 changes: 1 addition & 4 deletions tests/tests/vertex_formats/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,10 +352,7 @@ async fn vertex_formats_common(ctx: TestingContext, tests: &[Test<'_>]) {

let mut deltas = data.iter().zip(expected.iter()).map(|(d, e)| (d - e).abs());
if deltas.any(|x| x > EPSILON) {
eprintln!(
"Failed: Got: {:?} Expected: {:?} - {case_name}",
data, expected,
);
eprintln!("Failed: Got: {data:?} Expected: {expected:?} - {case_name}",);
failed = true;
continue;
}
Expand Down
5 changes: 1 addition & 4 deletions tests/tests/vertex_indices/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -471,10 +471,7 @@ async fn vertex_index_common(ctx: TestingContext) {
test.case, test.id_source, test.draw_call_kind, test.encoder_kind
);
if data != expected {
eprintln!(
"Failed: Got: {:?} Expected: {:?} - {case_name}",
data, expected,
);
eprintln!("Failed: Got: {data:?} Expected: {expected:?} - {case_name}",);
failed = true;
} else {
eprintln!("Passed: {case_name}");
Expand Down
3 changes: 1 addition & 2 deletions wgpu-hal/src/vulkan/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2538,8 +2538,7 @@ impl super::DeviceShared {
}
None => {
crate::hal_usage_error(format!(
"no signals reached value {}",
wait_value
"no signals reached value {wait_value}"
));
}
}
Expand Down
4 changes: 2 additions & 2 deletions wgpu-info/src/human.rs
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ fn print_adapter(output: &mut impl io::Write, report: &AdapterReport, idx: usize
for format in TEXTURE_FORMAT_LIST {
let features = texture_format_features[&format];
let format_name = texture::texture_format_name(format);
write!(output, "\t\t{format_name:>0$}", max_format_name_size)?;
write!(output, "\t\t{format_name:>max_format_name_size$}")?;
for bit in wgpu::TextureUsages::all().iter() {
write!(output, " │ ")?;
if features.allowed_usages.contains(bit) {
Expand Down Expand Up @@ -259,7 +259,7 @@ fn print_adapter(output: &mut impl io::Write, report: &AdapterReport, idx: usize
let features = texture_format_features[&format];
let format_name = texture::texture_format_name(format);

write!(output, "\t\t{format_name:>0$}", max_format_name_size)?;
write!(output, "\t\t{format_name:>max_format_name_size$}")?;
for bit in wgpu::TextureFormatFeatureFlags::all().iter() {
write!(output, " │ ")?;
if features.flags.contains(bit) {
Expand Down
Loading

0 comments on commit 8e787eb

Please sign in to comment.