1

I would like to write this C code in Rust:

#include <limits.h>
#if ((INT_MAX >> 15) >> 15) >= 1
#define LUAI_BITSINT    32
#else
/* 'int' always must have at least 16 bits */
#define LUAI_BITSINT    16
#endif

I could create a function returning my BITSINT but I want to avoid runtime cost. I don't know how to express isize::max_value() inside a macro in Rust, is it possible?

This would be my runtime code:

fn bitsint() -> usize {
    if ((isize::max_value() >> 15) >> 15) >= 1 {
        32
    } else {
        16
    }
}
1
  • 4
    Have you checked the compiled output? I'd expect your "runtime" soultion to be optimized out into a constant. Commented Apr 11, 2017 at 13:58

1 Answer 1

4

Currently, you cannot define a const or static value based on a function call. That requires the const functions feature to be completed.

That being said...

but I want to avoid runtime cost

tl;dr There is no runtime cost here, this is fine.

To avoid runtime cost, you should first ensure that you have runtime cost. To check, I used this code:

#[inline(never)]
fn bitsint() -> usize {
    if ((isize::max_value() >> 15) >> 15) >= 1 {
        12345
    } else {
        67890
    }
}

fn main() {
    println!("{}", bitsint());
}

I switched the values to make them easier to find in the assembly. The generated assembly does not have a function bitsint, even though I asked for it to not be inlined. It's hard to stop an optimizing compiler!

In the rest of the assembly, the value 67890 does not even occur, even though 12345 does.


An alternate solution may be to use conditional compilation. As an untested example:

#[cfg(target_pointer_width = "64")]
const LUAI_BITSINT: usize = 32;
#[cfg(not(target_pointer_width = "64"))]
const LUAI_BITSINT: usize = 16;

You could also use a build script to generate Rust code based on whatever conditions you want. This would create a constant that you could then include! into your code.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.