#reference #owning #sibling #field

owning_ref_async

A library for creating references that carry their owner with them

2 releases

0.4.5 Jun 15, 2022
0.4.4 Dec 10, 2021
0.4.3 Dec 9, 2021

#4 in #owning

Download history 1/week @ 2024-07-22 20/week @ 2024-07-29 7/week @ 2024-08-05 9/week @ 2024-08-12 21/week @ 2024-08-26 17/week @ 2024-09-09 35/week @ 2024-09-23 6/week @ 2024-09-30 1/week @ 2024-10-14 27/week @ 2024-10-21 32/week @ 2024-10-28 16/week @ 2024-11-04

76 downloads per month
Used in chashmap-async

MIT license

74KB
1.5K SLoC

Build Status Crate Docs

owning-ref-rs

This is a fork integrating the upstream MR #68 which adds async support.

A library for creating references that carry their owner with them.

This can sometimes be useful because Rust borrowing rules normally prevent moving a type that has been borrowed from. For example, this kind of code gets rejected:

fn return_owned_and_referenced<'a>() -> (Vec<u8>, &'a [u8]) {
    let v = vec![1, 2, 3, 4];
    let s = &v[1..3];
    (v, s)
}

This library enables this safe usage by keeping the owner and the reference bundled together in a wrapper type that ensure that lifetime constraint:

fn return_owned_and_referenced() -> OwningRef<Vec<u8>, [u8]> {
    let v = vec![1, 2, 3, 4];
    let or = OwningRef::new(v);
    let or = or.map(|v| &v[1..3]);
    or
}

Getting Started

To get started, add the following to Cargo.toml.

owning_ref = "0.4.1"

...and see the docs for how to use it.

Example

extern crate owning_ref;
use owning_ref::BoxRef;

fn main() {
    // Create an array owned by a Box.
    let arr = Box::new([1, 2, 3, 4]) as Box<[i32]>;

    // Transfer into a BoxRef.
    let arr: BoxRef<[i32]> = BoxRef::new(arr);
    assert_eq!(&*arr, &[1, 2, 3, 4]);

    // We can slice the array without losing ownership or changing type.
    let arr: BoxRef<[i32]> = arr.map(|arr| &arr[1..3]);
    assert_eq!(&*arr, &[2, 3]);

    // Also works for Arc, Rc, String and Vec!
}

Dependencies