Expand description
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.5"
features = [
## enables items that use anything from the standard `std` or `alloc` crates.
"std",
## Requires the latest stable release, enables all the rust-version-dependent features
"rust_latest_stable",
## enables all the item features
"all_items",
]The "std" feature is required to enable impls and items that use std types,
otherwise only the core library is supported.
"rust_latest_stable" enables all the "rust_1_*" crate features
to use the newest stable language features,
here’s a list of all the "rust_1_*" features,
"all_items" enables all of the features for enabling items from this crate
(documented here):
Here is the expanded version of the above configuration:
[dependencies.core_extensions]
version = "1.5"
features = [
"std",
"rust_latest_stable"
## all of the features below are what "all_items" enables
"derive"
"bools",
"callable",
"collections",
"const_default",
"const_val",
"generics_parsing",
"integers",
"item_parsing",
"iterators",
"macro_utils",
"marker_type",
"on_drop",
"option_result",
"phantom",
"self_ops",
"slices",
"strings",
"transparent_newtype",
"type_asserts",
"type_identity",
"type_level_bool",
"void",
]§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)
}
§Cargo Features
§Item features
Item features enables items from this crate.
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.
The "all_items_no_derive" feature eanbles all the features below
except for the "derive" feature,
to reduce compile-times due to enabling the syn indirect dependency.
-
"derive": Enables derive macros for traits declared in core_extensions. If a trait has a derive macro it’ll mention and link to it. -
"bools": Enables theBoolExttrait, extension trait forbool. -
"callable": Enables thecallablemodule, with stably implementable equivalents of theFn*traits. -
"collections": Enables thecollectionsmodule, with traits for collection types. -
"const_default": Enables theConstDefaulttrait, andconst_defaultmacro, for aconstequivalent of theDefaulttrait. -
"const_val": Enables theConstValtrait (for types that represent constants),getconstmacro (for getting theConstVal::VALassociated constant), andquasiconstmacro (for declaring types that emulate generic constants). Enables the"generics_parsing"feature. -
"macro_utils: Enables therewrap_macro_parameters,count_tts,gen_ident_range,tokens_method,compile_error_stringify, andparenthesize_argsmacro. Also enables themacro_attrattribute. -
"generics_parsing": Enables theparse_generics,parse_generics_and_where,split_generics_and_where,parse_split_generics, andparse_split_generics_and_wheremacros. These allow macros to parse items with generic parameters. -
"item_parsing": Enables the"macro_utilsand"generics_parsing"features. Enables theimpl_parse_genericsandimpl_splitmacros. -
"integers": Enables theintegersmodule, with extension traits for integer types. -
"iterators": Enables theiteratorsmodule, with theIteratorExtextension trait for iterators, and a few iterator types. -
"marker_type": Enables theMarkerTypetrait, for trivially constructible, zero-sized, and aligned-to-1 types. -
"on_drop": Enables theRunOnDroptype, a wrapper type that runs a closure at the end of the scope. -
"option_result": Enables theoption_result_extmodule, with traits forOptionandResult-like types. -
"phantom": Enables thephantommodule(withPhantomData-related items),expr_as_phantommacro,map_phantomdatamacro, andreturn_type_phantommacro. -
"self_ops": Enables theSelfOpstrait, an extension trait for all types. It primarily has methods for calling free functions as methods. -
"slices": Enables theslicesmodule, with extension traits for[T]andstrslices. -
"strings": Enables thestringsmodule, with theStringExtextension trait for strings. -
"transparent_newtype": Enables thetransparent_newtypemodule, with extension traits and functions for#[repr(transparent)]newtypes with public fields.
Enables the"marker_type"feature. -
"type_asserts": Enables thetype_assertsmodule, with type-level assertiosn, most useful in tests. -
"type_identity": Enables theTypeIdentitytrait, for proving that two types are equal, and converting between them in a generic context. -
"type_level_bool": Enables thetype_level_boolmodule, which encodesbools on the type-level. -
"void": Enables theVoidtype, a type that can’t be constructed, for encodign impossible situations.
§Rust Version numbers
These features enable code that require some Rust version past the minimum supported one:
-
“rust_1_46”: Makes
TransparentNewtypeandTypeIdentityassociated functions that takeRc<Self>orArc<Self>callable as methods. -
“rust_1_51”: Enables the “rust_1_46” feature, and impls of traits for all array lengths. Enables the
"on_drop"feature becauseRunOnDropis used by the impls for arrays of all lengths. -
“rust_latest_stable”: Enables all the “rust_1_*” features. This requires the last stable release of Rust, since more
"rust_1_*"features can be added at any time.
§Support for other crates
All of these are disabled by default:
-
"std": Enablesstdlibrary support. Implies the"alloc"feature. -
"alloc": Enablesalloclibrary 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.
§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.
Re-exports§
pub use self::callable::CallExt;callablepub use self::callable::CallInto;callablepub use self::callable::CallMut;callablepub use self::callable::CallRef;callablepub use self::integers::IntegerExt;integerspub use self::integers::ToTime;integerspub use self::iterators::IterCloner;iteratorspub use self::iterators::IterConstructor;iteratorspub use self::iterators::IteratorExt;iteratorspub use self::iterators::LazyOnce;iteratorspub use self::option_result_ext::OptionExt;option_resultpub use self::option_result_ext::ResultExt;option_resultpub use self::option_result_ext::ResultLike;option_resultpub use self::option_result_ext::ResultLikeExt;option_resultpub use self::option_result_ext::TransposeOption;option_resultpub use self::phantom::AsPhantomData;phantompub use self::phantom::AndPhantom;phantompub use self::phantom::AndPhantomCov;phantompub use self::phantom::as_phantom;phantompub use self::phantom::as_covariant_phantom;phantompub use self::phantom::ContraVariantPhantom;phantompub use self::phantom::InvariantPhantom;phantompub use self::phantom::InvariantRefPhantom;phantompub use self::phantom::VariantDropPhantom;phantompub use self::phantom::CovariantPhantom;phantompub use self::strings::StringExt;slicespub use self::slices::ValSliceExt;slicespub use self::slices::SliceExt;slicespub use self::transparent_newtype::TransparentNewtype;transparent_newtypepub use self::transparent_newtype::TransparentNewtypeExt;transparent_newtypepub use self::void::Void;void
Modules§
- callable
callable - Alternatives of the standard
Fn/FnMut/FnOncetraits, implementable in stable Rust. - collections
collections - Extension traits for collection types.
- integers
integers - Extension traits for integers and types used in the traits.
- iterators
iterators - Iterator adaptors and constructors.
- measure_
time - Time measurement.
- option_
result_ ext option_result - Contains extension traits for Option and Result
- phantom
phantom PhantomData-related items.- slices
slices - Slice extension traits, and related items.
- strings
slices - Extension trait for string types.
- transparent_
newtype transparent_newtype - Traits for newtype wrappers.
- type_
asserts type_asserts - Type-level assertions, most useful for tests.
- type_
level_ bool type_level_bool - Type level booleans
- utils
- Miscelaneous utility functions
- void
void - Contains types and functions for impossible situations.
Macros§
- __
priv_ usize_ const - compile_
error_ stringify macro_utils - Stringifies the input tokens, and errors with
compile_error. - const_
default const_default - Gets the
ConstDefault::DEFAULTassociated constant for a type. - count_
tts macro_utils - Counts the amount of token trees passed to this macro, passing the amount to an (optional) callback macro.
- delegate_
transparent_ newtype_ impl transparent_newtype - For delegating the implementation of the
TransparentNewtypetrait to a field. - expr_
as_ phantom phantom - Gets the type of an expression as a
PhantomData, without evaluating the expression. - gen_
ident_ range macro_utils - Generates identifiers. passing them to a callback macro.
- getconst
const_val - Gets the
ConstVal::VALassociated constant for a type. - impl_
call callable - This macro allows more ergonomically implementing the
CallRef/CallMut/CallIntotraits . - impl_
parse_ generics item_parsing - For parsing impl blocks, transforming the generic parameters to a form easily parsable by the callback macro.
- impl_
split item_parsing - For parsing impl blocks, passing the generic parameters unchanged to a callback macro.
- impl_
transparent_ newtype transparent_newtype - For implementing the
TransparentNewtypetrait, to cast between a field andSelf. - iter_
cloner iterators - Use this macro to create an
IterClonerfrom anIntoIterator(this includes allIterators). - map_
phantomdata phantom - Maps a
PhantomData<T>to aPhantomData<U>by using aFnOnce(T) -> Uclosure. - matches
- Evaluates to true if the expression matches any of the patterns (this macro can have multiple patterns).
- parenthesize_
args macro_utils - Adaptor macro which passes arguments to a callback macro, wrapping them in parentheses.
- parse_
generics generics_parsing - Transforms generic parameters for use in type definitions, impl blocks and generic arguments, passing them to a callback macro.
- parse_
generics_ and_ where generics_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_ generics generics_parsing - Transforms generic parameters to a form easily parsable by a callback macro.
- parse_
split_ generics_ and_ where generics_parsing - For parsing item definitions, transforming generics to a form easily parsable by a callback macro.
- quasiconst
const_val - Declare types that emulate generic constants.
- return_
type_ phantom phantom - Gets the return type of a parameterless closure as a
PhantomData - rewrap_
macro_ parameters macro_utils - Rewraps the tokens inside macro parameters into parentheses.
- split_
generics_ and_ where generics_parsing - For parsing item definitions, passing the generic parameters unchanged to a callback macro.
- tokens_
method macro_utils - Does slice and iterator operations on tokens, passing the result to a callback macro.
Structs§
- RunOn
Drop on_drop - A wrapper type that runs a closure at the end of the scope.
Traits§
- BoolExt
bools - Extension trait for
bool. - Const
Default const_default - A const equivalent of the
Defaulttrait. - Const
Val const_val - For types that represent constants.
- Marker
Type marker_type - Represents a zero-sized marker type .
- SelfOps
self_ops - Extension trait for every type.
- Type
Identity type_identity - Allows converting
SelftoSelf::Typeby proving that both types are equal.
Type Aliases§
- TIdentity
type_identity - A type-level identity function
Attribute Macros§
- macro_
attr macro_utils - For using function-like macros as attributes.
Derive Macros§
- Const
Default deriveandconst_default - Derives the
ConstDefaulttrait for structs and enums. - Transparent
Newtype deriveandtransparent_newtype - Derives the
TransparentNewtypetrait.