Is there a way to use ALTREP with Rcpp?

Viewed 186

Example:

// [[Rcpp::export]]
size_t z1(SEXP x) {
  return Rf_xlength(x);
}

// [[Rcpp::export]]
size_t z2(NumericVector x) {
  // do anything or nothing
  return 1;
}

R:

x <- seq(1,1e10)
z1(x)
[1] 1e+10

z2(x)
# computer hard crash

Suppose as example, I just wanted to take the first 10 elements of an ALTREP vector. What would be the best way to do so in C++?

1 Answers

Rcpp is currently not ALTREP aware. The conversion from an ALTREP SEXP to NumericVector will therefore materialize it. In my case R stops telling me it cannot the allocate required memory, but that's a minor difference.

For now you have to handle ALTREP object without the niceties of Rcpp, for example for your final question:

#include <Rcpp.h>

// [[Rcpp::export]]
SEXP get_region(SEXP x, R_xlen_t i, R_xlen_t n) {
  SEXP result;
  switch (TYPEOF(x)) {
    case INTSXP: {
      result = PROTECT(Rf_allocVector(INTSXP, n));
      INTEGER_GET_REGION(x, i, n, INTEGER(result));
      UNPROTECT(1);
      break;
    }
    case REALSXP: {
      result = PROTECT(Rf_allocVector(REALSXP, n));
      REAL_GET_REGION(x, i, n, REAL(result));
      UNPROTECT(1);
      break;
    }
    default: {
      Rcpp::stop("Invalid SEXPTYPE %d (%s).\n", TYPEOF(x), Rcpp::type2name(x));
    }
  }
  return result;
}

/*** R
x <- seq(1,1e10)
.Internal(inspect(x)) # @5623ba0b65f0 14 REALSXP g0c0 [NAM(3)]  1 : 10000000000 (compact)
get_region(x, 0, 10)  # [1]  1  2  3  4  5  6  7  8  9 10

x <- seq(1,1e9)
.Internal(inspect(x)) # @5623ba143ff0 13 INTSXP g0c0 [NAM(3)]  1 : 1000000000 (compact)
get_region(x, 0, 10)  # [1]  1  2  3  4  5  6  7  8  9 10
*/

This uses run-time polymorphism from http://gallery.rcpp.org/articles/rcpp-wrap-and-recurse/.

Related