Kimundi / owning-ref-rs

A library for creating references that carry their owner with them.
MIT License
361 stars 50 forks source link

Help: returning owner and borrowed from a function? #75

Open Wandalen opened 2 years ago

Wandalen commented 2 years ago

Is it possible to use the crate to solve the problem:

use byte_slice_cast::*;

fn main() {
    let context = context_make();
    dbg!(&context);
}

//

fn context_make<'a>() -> Context<'a> {
    Context::<'a>::new()
}

//

#[derive(Debug)]
struct Context<'a> {
    pub dst_buffer: Box<[f32]>,
    pub dst_buffer_bytes: &'a [u8],
}

//

impl<'a> Context<'a> {
    fn new() -> Context<'a> {
        let len: usize = 13;
        let dst_buffer: Box<[f32]> = vec![0_f32; len].into_boxed_slice();
        let dst_buffer_bytes = dst_buffer.as_byte_slice();
        Context {
            dst_buffer,
            dst_buffer_bytes,
        }
    }
}

Note: it depends of byte-slice-cast = "1.2.0"

Playground

Wandalen commented 2 years ago

Here is solution:

use byte_slice_cast::*;
use owning_ref::*;

fn main()
{
  let context = context_make();
  dbg!( &context );
  dbg!( context.dst.as_owner() );
  dbg!( &*context.dst );
}

//

fn context_make<>() -> Context<>
{
  Context::<>::new()
}

//

#[ derive( Debug ) ]
struct Context<>
{
  // pub dst_buffer : Box::< [ f32 ] >,
  // pub dst_buffer_bytes : &'a [ u8 ],
  pub dst : OwningRef< Box::< [ f32 ] >, [ u8 ] >
}

//

impl<> Context<>
{
  fn new<>() -> Context<>
  {
    let len : usize = 2;
    let dst_buffer : Box<[ f32 ]> = vec![ 0_f32; len ].into_boxed_slice();
    // let dst_buffer_bytes = dst_buffer.as_byte_slice();

    let dst = OwningRef::new( dst_buffer );
    let dst = dst.map( | dst_buffer | dst_buffer.as_byte_slice() );

    Context { dst }
    // Context { dst_buffer, dst_buffer_bytes }
  }
}

Playground

Thanks anyway.