Chapter 5 Rust Type to R with RPtr

pub use rustr::rptr::*;
pub use util::*;

// #[rustr_export]
pub fn rsvec_new() -> RPtr<Vec<f64>> {
    let res = RPtr::init()
                    .finalizer(Some(finalz))
                    .done(Box::new(vec![1.0, 2.0, 3.0]));
    res
}

// #[rustr_export]
pub fn rsvec_push(x : RPtr<Vec<f64>>, z : f64) ->RResult<()>{

    let mut y =x;

    let rr = try!(y.get());

    rr.push(z);
    r_printf(format!("{:?}",(*rr)).as_ref());
    
    Ok(())
}

pub extern "C" fn finalz(x: SEXP) {

    if RTYPEOF(x) == EXTPTRSXP {
        r_printf("drop a vector\n");
        rprint(x);
        unsafe {
            Box::<Vec<f64>>::from_raw(::std::mem::transmute(R_ExternalPtrAddr(x)));
        }
    }

}
vec = rsvec_new()

rsvec_push(vec, 12)

rsvec_push(vec, 12)

rsvec_push(vec, 1)

rm(vec)

gc()
rust('
pub use rustr::rptr::*;

// #[rustr_export]
pub fn rsvec_new() -> RPtr<Vec<f64>> {
    let res = RPtr::init()
                    .finalizer(Some(finalz))
                    .done(Box::new(vec![1.0, 2.0, 3.0]));
    res
}

// #[rustr_export]
pub fn rsvec_push(x : RPtr<Vec<f64>>, z : f64) ->RResult<()>{

    let mut y =x;

    let rr = try!(y.get());

    rr.push(z);
    r_printf(format!("{:?}",(*rr)).as_ref());
    
    Ok(())
}

pub extern "C" fn finalz(x: SEXP) {

    if RTYPEOF(x) == EXTPTRSXP {
        r_printf("drop a vector\n");
        rprint(x);
        unsafe {
            Box::<Vec<f64>>::from_raw(::std::mem::transmute(R_ExternalPtrAddr(x)));
        }
    }

}
')


vec = rsvec_new()

rsvec_push(vec, 12)
#> [1, 2, 3, 12]

rsvec_push(vec, 12)
#> [1, 2, 3, 12, 12]

rsvec_push(vec, 1)
#> [1, 2, 3, 12, 12, 1]

rm(vec)

gc()
#> drop a vector
#> <pointer: 0x2c830a0>
#>          used (Mb) gc trigger (Mb) max used (Mb)
#> Ncells 502557 26.9     940480 50.3   940480 50.3
#> Vcells 701186  5.4    1308461 10.0  1034666  7.9