gpt4 book ai didi

rust - 基于函数调用的条件常量定义

转载 作者:行者123 更新时间:2023-11-29 08:23:48 25 4
gpt4 key购买 nike

我想用 Rust 编写这段 C 代码:

#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

我可以创建一个返回我的 BITSINT 的函数,但我想避免运行时成本。我不知道如何在 Rust 的宏中表达 isize::max_value(),这可能吗?

这将是我的运行时代码:

fn bitsint() -> usize {
if ((isize::max_value() >> 15) >> 15) >= 1 {
32
} else {
16
}
}

最佳答案

目前,您不能根据函数调用定义conststatic 值。这需要 const functions feature待完成。

话虽这么说......

but I want to avoid runtime cost

tl;dr 这里没有运行时成本,这很好。

要避免运行时成本,您应该首先确保您运行时成本。为了检查,我使用了这段代码:

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

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

我切换了值,使它们更容易在程序集中找到。生成的程序集没有函数 bitsint,即使我要求它不被内联。很难停止优化编译器!

在程序集的其余部分,值 67890 甚至没有出现,尽管 12345 出现了。


另一种解决方案可能是使用条件编译。作为一个未经测试的例子:

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

您还可以使用构建脚本 根据您想要的任何条件生成 Rust 代码。这将创建一个常量,然后您可以将其include! 到您的代码中。

关于rust - 基于函数调用的条件常量定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43348043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com