rust-lang / rust-lang/rust

`impl fmt::Display for u32` compiles to large binary

Open
#118,940 1 comment 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-optimization I-heavy T-libs
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

My target is wasm32-unknown-unknown but I think it can be applied to any embedded systems. I just want to define panic handler, but formatting core::panic::Location costs amlost 3 KiB in binary. This is because inefficient impl Display for u32. Also see: https://github.com/dtolnay/itoa

[package]
name = "demo"
version = "0.1.0"
edition = "2021"

[lib]
name = "demo"
crate-type = ["cdylib"]

[dependencies]
arrayvec = { version = "0.7.4", default-features = false }

[profile.release]
opt-level = "z"
codegen-units = 1
lto = true
strip = true
#![no_std]
#![feature(panic_info_message)]

#[allow(improper_ctypes)]
extern "C" {
    pub fn sc_panic(msg: &str) -> !;
}

#[panic_handler]
fn panic(panic_info: &core::panic::PanicInfo) -> ! {
    use core::fmt::Write;

    let mut msg = arrayvec::ArrayString::<1024>::new();

    // 2_009 bytes binary:
    /*let _ = write!(&mut msg, "{}", unsafe {
        panic_info.message().unwrap_unchecked()
    });*/

    // 5_076 bytes binary:
    let _ = write!(&mut msg, "{}", unsafe {
        panic_info.location().unwrap_unchecked()
    });
    // ^^^ +3 KiB to print location in format {file}:{line}:{column}???

    // exit from smart contract with msg
    unsafe { sc_panic(&msg) }
}

#[no_mangle]
extern "C" fn entry_point() {
    panic!("msg");
}

This is mostly because this line: https://github.com/rust-lang/rust/blob/1aa6aefdc92555b3fbc5ae4c99365df9845a3e31/library/core/src/fmt/num.rs#L277
Could we have something like specialization for more simpler impl Display for $num?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the provided no_std crate for wasm32-unknown-unknown, then inspect library/core/src/fmt/num.rs at the referenced line and the panic handler's formatting path. Compare the release binary sizes and verify that the requested change reduces the location-formatting overhead while preserving {file}:{line}:{column} output.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust, wasm
Domain
embedded-iot, performance
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.