Changing the size of allocated buffer during compilation

I just started to review the rustc compiler code.
I want to change the allocated buffer size for my-string variable in the below code.
I mean instead of 12 I want to allocate a buffer with the length of 20.

#[link_section ="my-string"]
pub static data: [u8; 12] = *b"Hello, World";

Can you help me how I can apply this change to the rustc compiler?


If it's just about initializing a buffer using a string that has a different size, you could try something like this:

#[link_section = "my-string"]
pub static DATA: [u8; 20] = array_backed_string("Hello, World!");

const fn array_backed_string<const LEN: usize>(s: &str) -> [u8; LEN] {
    let mut buffer = [0_u8; LEN];
    assert!(s.len() <= LEN);
    let bytes = s.as_bytes();

    let mut i = 0;

    while i < bytes.len() {
        buffer[i] = bytes[i];
        i += 1;



For-loops and [T]::copy_from_slice() aren't available inside const functions yet, so I had to use a while-loop to copy the string's bytes across one-by-one :disappointed:

1 Like

Thanks for your reply. But, I am developing a system and I want to hide this complexity from the users.
So, I want to apply this in compiler level or any reasonable method that allows user to only define their string. I should receive the string and change the allocated buffer size and fill the rest with some specific chars.

The simplest way will be to provide a macro or const fn which the user will annotate their literal with.

Most likely, what will fit your use case best is a custom attribute macro, so users can write something like

pub static DATA: str = "Hello, World";
1 Like

can I still use #[link_section ] attribute?
Because I use it to put my data into a custom section in wasm.

Procedural macros cat emit whatever they need, including new attributes on items.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.