#allocator #fallback #standard #api #stable #polyfill #allocator-api

无std allocator-fallback

标准库分配器API的最小回退

9个版本

0.1.8 2022年12月20日
0.1.7 2022年12月18日
0.1.6 2022年11月11日
0.1.5 2022年8月27日
0.1.1 2022年4月29日

#119 in 无标准库


2 个包中使用

Apache-2.0

18KB
160 代码行

allocator-fallback

此包提供了标准库分配器API的最小回退,目前尚不稳定。

用法

由于allocator-fallback可以配置为重新导出实际的未稳定分配器API(参见包功能),使用此包的用户必须确保他们条件性地启用#![feature(allocator_api)]以准备这种情况;否则,可能会发生编译错误。即使对于从未直接启用allocator-fallback的allocator_api功能的包也是如此,因为可能存在也依赖于allocator-fallback的不同的包。

为了实现这一点,在Cargo.toml中,将allocator-fallback的依赖项在[build-dependencies]部分中重复,例如

[dependencies]
allocator-fallback = "0.1.7"

[build-dependencies]
allocator-fallback = "0.1.7"

然后,添加一个以下内容的构建脚本 (build.rs):[^1]

fn main() {
   if allocator_fallback::HAS_ALLOCATOR_API {
       println!("cargo:rustc-cfg=has_allocator_api");
   }
   println!("cargo:rerun-if-changed=build.rs");
}

最后,在您的包根目录顶部(可能是lib.rsmain.rs),添加以下内容

#![cfg_attr(has_allocator_api, feature(allocator_api))]

作为可选依赖项使用

如果将allocator-fallback声明为可选依赖项,则上述说明将不起作用。在这种情况下,按照以下说明调整

像以前一样,在[build-dependencies]中重复对allocator-fallback的依赖项,同时保留两个实例中的optional = true。例如

[dependencies.allocator-fallback]
version = "0.1.7"
optional = true

[build-dependencies.allocator-fallback]
version = "0.1.7"
optional = true

然后,使用以下内容作为构建脚本(build.rs)的内容:[^1]

fn main() {
   #[cfg(feature = "allocator-fallback")]
   if allocator_fallback::HAS_ALLOCATOR_API {
       println!("cargo:rustc-cfg=has_allocator_api");
   }
   println!("cargo:rerun-if-changed=build.rs");
}

最后,像以前一样,在包根目录顶部添加以下内容

#![cfg_attr(has_allocator_api, feature(allocator_api))]

[^1]: 这些构建脚本代码片段已发布到公有领域,使用的是CC0 1.0 公有领域承诺

包功能

如果启用了包功能 allocator_api,此包将简单地重新导出标准库中的实际分配器API。当然,这需要Rust夜间版。

如果启用了包功能 std(默认值),则包将使用std;否则,它将是 no_std。使用std允许AllocError实现std::error::Error

无运行时依赖