Expand description
§flex
Flexible borrowing and ownership for Rust.
Flex is an enum that holds either a borrowed reference or an owned boxed value
of the same type. It is similar in concept to Cow and works seamlessly with
unsized types like dyn Trait, [T], and str.
§Installation
[dependencies]
flex = "0.1"If your crate has an alloc feature, pass it through to flex:
[features]
alloc = ["flex/alloc"]
[dependencies]
flex = "0.1"§Quick Start
use flex::Flex;
// Start with a borrowed slice
let borrowed = Flex::Lend(&[1, 2, 3][..]);
assert_eq!(&*borrowed, &[1, 2, 3]);
// Or own a slice
let owned = Flex::Give(vec![4, 5, 6].into_boxed_slice());
assert_eq!(&*owned, &[4, 5, 6]);
// Convert borrowed to owned
let claimed: Flex<'static, [i32]> = borrowed.claim();§Flex vs Cow
While both Flex and Cow deal with borrowed vs owned data, they serve
different purposes:
§Cow (Clone-on-Write)
- Works with type pairs (e.g.,
&str/String,&[T]/Vec<T>) - Uses
ToOwnedtrait for conversion - Requires
alloc- not available inno_std
§Flex (Flexible Ownership)
- Works with ownership models of the same type (
&TvsBox<T>) - Works seamlessly with like unsized types
dyn Trait,[u8]andstr - No
ToOwnedrequirement - Works in
no_stdwithoutalloc- produces consistent APIs
Example: Flex<'a, str> holds either &'a str or Box<str>, while
Cow<'a, str> holds either &'a str or String.
§Use Cases
Flex is particularly useful when:
- Working with trait objects:
Flex<'a, dyn Debug>holds&dyn DebugorBox<dyn Debug> - Building APIs that accept both borrowed and owned unsized types
- Flexible ownership without
ToOwnedconstraints - Deferring allocation decisions until runtime
§Features
alloc: Enables theGivevariant withBox<T>
Without alloc, Flex only supports the Lend variant, but APIs remain
compatible.
§License
Licensed under the MIT License.
Enums§
- Flex
- A flexible container that can hold either a borrowed reference or an owned boxed value.