Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Wandalen opened this issue Nov 6, 2021 · 1 comment
Open

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

Wandalen opened this issue Nov 6, 2021 · 1 comment

Comments

@Wandalen
Copy link

Wandalen commented Nov 6, 2021

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
Copy link
Author

Wandalen commented Nov 6, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant