#maybe #std #alloc #helper #optional #libraries #work #exports

maybe-std

Helper crate for writing rust libraries with an optional dependency on the standard library

3 releases

0.1.2 Oct 5, 2020
0.1.1 Oct 5, 2020
0.1.0 Sep 27, 2020

#226 in Memory management

Download history 17/week @ 2022-07-31 28/week @ 2022-08-07 14/week @ 2022-08-14 22/week @ 2022-08-21 12/week @ 2022-08-28 24/week @ 2022-09-04 17/week @ 2022-09-11 15/week @ 2022-09-18 20/week @ 2022-09-25 36/week @ 2022-10-02 15/week @ 2022-10-09 11/week @ 2022-10-16 23/week @ 2022-10-23 24/week @ 2022-10-30 30/week @ 2022-11-06 20/week @ 2022-11-13

97 downloads per month
Used in 5 crates (4 directly)

CC-PDDC license

8KB
130 lines

Maybe-std

A rust crate that helps writing libraries that work without alloc and/or std but can provide extra functionality if they are available. Writing such libraries involves some namespace-juggling which this crate takes care of. It exports all the items from core, alloc or std, depending on which features are enabled.

Usage

Depend on this crate by adding it to your Cargo.toml file:

[dependencies]
maybe-std = "0.1.0"
# If the library always requires the `alloc` crate, directly enable the feature:
# maybe-std = { version = "0.1.0", features = [ "alloc" ] }

Define the feature flags that control whether your library uses alloc and/or std, and forward them to the maybe_std crate:

[features]
alloc = [ "maybe-std/alloc" ] # Remove if the library always requires `alloc`
std = [ "maybe-std/std" ]

In the crate root, disable the standard library and import this crate - optionally rename it to something short to keep things more readable.

#![no_std]
extern crate maybe_std as base;

// `base` contains the same items as `core`, `alloc` or `std`, depending on
// the enabled features.

In all files, import the prelude:

use base::prelude::v1::*;

When using std functionality, gate it with #[cfg(feature = "std")], and when using alloc functionality that should be available even without std, gate it with #[cfg(any(feature = "alloc", feature = "std"))]:

#[cfg(feature = "std")]
pub const HOME: base::net::Ipv4Addr = base::net::Ipv4Addr::LOCALHOST;

#[cfg(any(feature = "alloc", feature = "std"))]
pub fn empty_string() -> String {
    String::new()
}

Accessing unstable functionality

By default, this crate does not export any unstable features of alloc. These can be enabled via the unstable feature flag.

No runtime deps

Features

  • alloc
  • std
  • unstable