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
[]
= "0.1"
If your crate has an alloc feature, pass it through to flex:
[]
= ["flex/alloc"]
[]
= "0.1"
Quick Start
use Flex;
// Start with a borrowed slice
let borrowed = Lend;
assert_eq!;
#
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.