• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

src/H03-May-2022-2,0171,145

.cargo-checksum.jsonH A D03-May-202289 11

.cargo_vcs_info.jsonH A D27-Feb-202074 65

.gitignoreH A D10-Oct-201918 32

.travis.ymlH A D10-Oct-20191 KiB2221

CHANGELOG.mdH A D27-Feb-2020119 96

Cargo.tomlH A D27-Feb-2020990 2523

Cargo.toml.orig-cargoH A D27-Feb-2020460 1612

LICENSEH A D10-Oct-20191.1 KiB2217

README.mdH A D27-Feb-20201.7 KiB6547

README.md

1[![Build Status](https://travis-ci.org/Kimundi/owning-ref-rs.svg)](https://travis-ci.org/Kimundi/owning-ref-rs)
2[![Crate](https://img.shields.io/crates/v/owning_ref.svg)](https://crates.io/crates/owning_ref)
3[![Docs](https://docs.rs/owning_ref/badge.svg)](https://docs.rs/owning_ref)
4
5owning-ref-rs
6==============
7
8A library for creating references that carry their owner with them.
9
10This can sometimes be useful because Rust borrowing rules normally prevent
11moving a type that has been borrowed from. For example, this kind of code gets rejected:
12
13```rust
14fn return_owned_and_referenced<'a>() -> (Vec<u8>, &'a [u8]) {
15    let v = vec![1, 2, 3, 4];
16    let s = &v[1..3];
17    (v, s)
18}
19```
20
21This library enables this safe usage by keeping the owner and the reference
22bundled together in a wrapper type that ensure that lifetime constraint:
23
24```rust
25fn return_owned_and_referenced() -> OwningRef<Vec<u8>, [u8]> {
26    let v = vec![1, 2, 3, 4];
27    let or = OwningRef::new(v);
28    let or = or.map(|v| &v[1..3]);
29    or
30}
31```
32
33## Getting Started
34
35To get started, add the following to `Cargo.toml`.
36
37```toml
38owning_ref = "0.4.1"
39```
40
41...and see the [docs](http://kimundi.github.io/owning-ref-rs/owning_ref/index.html) for how to use it.
42
43
44## Example
45
46```rust
47extern crate owning_ref;
48use owning_ref::BoxRef;
49
50fn main() {
51    // Create an array owned by a Box.
52    let arr = Box::new([1, 2, 3, 4]) as Box<[i32]>;
53
54    // Transfer into a BoxRef.
55    let arr: BoxRef<[i32]> = BoxRef::new(arr);
56    assert_eq!(&*arr, &[1, 2, 3, 4]);
57
58    // We can slice the array without losing ownership or changing type.
59    let arr: BoxRef<[i32]> = arr.map(|arr| &arr[1..3]);
60    assert_eq!(&*arr, &[2, 3]);
61
62    // Also works for Arc, Rc, String and Vec!
63}
64```
65