Crate core_extensions[][src]

Extension traits for many standard/core library types/traits. and other miscelaneuous types / traits / functions / macros.

Adding as dependency

This crate requires cargo features for enabling items, to get all of them you can use:

[dependencies.core_extensions]
version = "1.0"
features = ["std", "all_items"]

The “std” feature is required to enable impls and items that use std types, otherwise only the core library is supported.

For enabling features individually, look here.

This crate currently requires cargo features to use newer language features,

Examples

Showcasing some features from this crate.

quasiconst, generic constants.

The quasiconst macro allows emulating generic constants by generating a zero-sized generic type that implements the ConstVal trait, the preferred way to get its value is the getconst macro.

This example demonstrates how you can use them to declare a generic VTABLE constant.

use core_extensions::{getconst, quasiconst};

use std::fmt::{self, Debug};


quasiconst!{
   pub const VTABLE<T: Debug>: &'static Vtable = &Vtable {
       size: std::mem::size_of::<T>(),
       align: std::mem::align_of::<T>(),
       drop: drop_erased::<T>,
       fmt: debug_fmt_erased::<T>,
   };
}

const VTABLE_U8: &'static Vtable = getconst!(VTABLE<u8>);
assert_eq!(VTABLE_U8.size, 1);
assert_eq!(VTABLE_U8.align, 1);

const VTABLE_USIZE: &'static Vtable = getconst!(VTABLE<usize>);
assert_eq!(VTABLE_USIZE.size, std::mem::size_of::<usize>());
assert_eq!(VTABLE_USIZE.align, std::mem::align_of::<usize>());

const VTABLE_STRING: &'static Vtable = getconst!(VTABLE<&str>);
assert_eq!(VTABLE_STRING.size, std::mem::size_of::<usize>() * 2);
assert_eq!(VTABLE_STRING.align, std::mem::align_of::<usize>());



pub struct Vtable {
   pub size: usize,
   pub align: usize,
   pub drop: unsafe fn(*mut ()),
   pub fmt: unsafe fn(*const (), &mut fmt::Formatter<'_>) -> fmt::Result,
}

unsafe fn drop_erased<T>(ptr: *mut ()) {
   std::ptr::drop_in_place(ptr as *mut T)
}

unsafe fn debug_fmt_erased<T>(ptr: *const (), f: &mut fmt::Formatter<'_>) -> fmt::Result 
where
   T: Debug,
{
   let this = unsafe{ &*(ptr as *const T) };
    
   Debug::fmt(this, f)
}

no-std support

This crate works in #![no_std] contexts by default.

Supported Rust versions

This crate support Rust back to 1.41.0, requiring cargo features to use language features from newer versions.

Cargo Features

crate features

The "all_items" feature enables all of these features, you can use it instead of the ones below if you don’t mind longer compile-times:

Rust Version numbers

These features enable code that require some Rust version past the minimum supported one:

  • “rust_1_46”: Makes TransparentNewtype and TypeIdentity associated functions that take Rc<Self> or Arc<Self> callable as methods.

  • “rust_1_51”: Enables the “rust_1_46” feature, and impls of traits for all array lengths.

Support for other crates

All of these are disabled by default:

  • "std": Enables std library support. Implies the "alloc" feature.

  • "alloc": Enables alloc library support.

  • "serde_": Enables serde support.

Miscelaneous features

"track_caller": Enables the “rust_1_46” feature. Changes ResultLike to allow getting the caller location in ResultLike::into_result_, and makes IsNoneError store where it was constructed.

"docsrs": Used to document the required features in docs.rs, requires Rust nightly. Doesn’t enable any items itself.

Re-exports

pub use self::callable::CallExt;
pub use self::callable::CallInto;
pub use self::callable::CallMut;
pub use self::callable::CallRef;
pub use self::integers::IntegerExt;
pub use self::integers::ToTime;
pub use self::iterators::IterCloner;
pub use self::iterators::IterConstructor;
pub use self::iterators::IteratorExt;
pub use self::iterators::LazyOnce;
pub use self::option_result_ext::OptionExt;
pub use self::option_result_ext::ResultExt;
pub use self::option_result_ext::ResultLike;
pub use self::option_result_ext::ResultLikeExt;
pub use self::option_result_ext::TransposeOption;
pub use self::phantom::AsPhantomData;
pub use self::phantom::AndPhantom;
pub use self::phantom::AndPhantomCov;
pub use self::phantom::as_phantom;
pub use self::phantom::as_covariant_phantom;
pub use self::phantom::ContraVariantPhantom;
pub use self::phantom::InvariantPhantom;
pub use self::phantom::InvariantRefPhantom;
pub use self::phantom::VariantDropPhantom;
pub use self::phantom::CovariantPhantom;
pub use self::strings::StringExt;
pub use self::slices::ValSliceExt;
pub use self::slices::SliceExt;
pub use self::transparent_newtype::TransparentNewtype;
pub use self::transparent_newtype::TransparentNewtypeExt;

Modules

callablecallable

Alternatives of the standard Fn/FnMut/FnOnce traits, implementable in stable Rust.

collectionscollections

Extension traits for collection types.

integersintegers

Extension traits for integers and types used in the traits.

iteratorsiterators

Iterator adaptors and constructors.

measure_time

Time measurement.

option_result_extoption_result

Contains extension traits for Option and Result

phantomphantom

PhantomData-related items.

slicesslices

Slice extension traits, and related items.

stringsslices

Extension trait for string types.

transparent_newtypetransparent_newtype

Traits for newtype wrappers.

type_assertstype_asserts

Type-level assertions, most useful for tests.

type_level_booltype_level_bool

Type level booleans

utils

Miscelaneous utility functions

Macros

compile_error_stringifymacro_utils

Stringifies the input tokens, and errors with compile_error.

const_defaultconst_default

Gets the ConstDefault::DEFAULT associated constant for a type.

count_ttsmacro_utils

Counts the amount of token trees passed to this macro, passing the amount to an (optional) callback macro.

expr_as_phantomphantom

Gets the type of an expression as a PhantomData, without evaluating the expression.

gen_ident_rangemacro_utils

Generates identifiers. passing them to a callback macro.

getconstconst_val

Gets the ConstVal::VAL associated constant for a type.

impl_callcallable

This macro allows more ergonomically implementing the CallRef / CallMut / CallInto traits .

impl_parse_genericsitem_parsing

For parsing impl blocks, transforming the generic parameters to a form easily parsable by the callback macro.

impl_splititem_parsing

For parsing impl blocks, passing the generic parameters unchanged to a callback macro.

impl_transparent_newtypetransparent_newtype

For implementing the TransparentNewtype trait.

iter_cloneriterators

Use this macro to create an IterCloner from an IntoIterator (this includes all Iterators).

map_phantomdataphantom

Maps a PhantomData<T> to a PhantomData<U> by using a FnOnce(T) -> U closure.

matches

Evaluates to true if the expression matches any of the patterns (this macro can have multiple patterns).

parenthesize_argsmacro_utils

Adaptor macro which passes arguments to a callback macro, wrapping them in parentheses.

parse_genericsgenerics_parsing

Transforms generic parameters for use in type definitions, impl blocks and generic arguments, passing them to a callback macro.

parse_generics_and_wheregenerics_parsing

For writing macros that parse item definitions, with the generic parameters transformed for use in type definitions, impl blocks and generic arguments.

parse_split_genericsgenerics_parsing

Transforms generic parameters to a form easily parsable by a callback macro.

parse_split_generics_and_wheregenerics_parsing

For parsing item definitions, transforming generics to a form easily parsable by a callback macro.

quasiconstconst_val

Declare types that emulate generic constants.

return_type_phantomphantom

Gets the return type of a parameterless closure as a PhantomData

rewrap_macro_parametersmacro_utils

Rewraps the tokens inside macro parameters into parentheses.

split_generics_and_wheregenerics_parsing

For parsing item definitions, passing the generic parameters unchanged to a callback macro.

tokens_methodmacro_utils

Does slice and iterator operations on tokens, passing the result to a callback macro.

Structs

RunOnDropon_drop

A wrapper type that runs a closure at the end of the scope.

Enums

Voidvoid

Type for impossible situations.

Traits

BoolExtbools

Extension trait for bool.

ConstDefaultconst_default

A const equivalent of the Default trait.

ConstValconst_val

For types that represent constants.

MarkerTypemarker_type

Represents a zero-sized marker type .

SelfOpsself_ops

Extension trait for every type.

TypeIdentitytype_identity

Allows converting Self to Self::Type by proving that both types are equal.

Type Definitions

TIdentitytype_identity

A type-level identity function

Attribute Macros

macro_attrmacro_utils

For using function-like macros as attributes.