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