From 1cba917b34902839295e34d4ca0af14b616daf16 Mon Sep 17 00:00:00 2001 From: Bernd Bischl Date: Mon, 24 Jun 2024 19:31:17 +0200 Subject: [PATCH] fix keep_in_bounds so we dont use internal API --- src/keep_in_bounds.c | 59 ++++++++++++++++---------------------------- 1 file changed, 21 insertions(+), 38 deletions(-) diff --git a/src/keep_in_bounds.c b/src/keep_in_bounds.c index b2d9623e..8f2f7c24 100644 --- a/src/keep_in_bounds.c +++ b/src/keep_in_bounds.c @@ -1,48 +1,31 @@ -#define R_NO_REMAP #include #include -SEXP c_keep_in_bounds(SEXP in, SEXP lower, SEXP upper) { - const int * x = INTEGER(in); - const int ll = INTEGER(lower)[0]; - const int lu = INTEGER(upper)[0]; - const R_xlen_t n = Rf_xlength(in); - R_xlen_t i; +SEXP c_keep_in_bounds(SEXP s_in, SEXP s_lower, SEXP s_upper) { + const int *x = INTEGER(s_in); + const int ll = asInteger(s_lower); + const int lu = asInteger(s_upper); + const R_xlen_t n = LENGTH(s_in); + R_xlen_t i, j; - // fast-forward to first element not in bounds - for (i = 0; i < n; i++) { - if (x[i] == NA_INTEGER || x[i] < ll || x[i] > lu) { - break; - } - } - - // everything ok, in == out - if (i == n) { - return(in); - } + // count the number of elements within bounds + int count = 0; + for (i = 0; i < n; i++) + if (x[i] != NA_INTEGER && x[i] >= ll && x[i] <= lu) count++; - // allocate output vector - SEXP out = PROTECT(Rf_allocVector(INTSXP, n)); - int * y = INTEGER(out); - R_xlen_t j; + // if all ok, immediatly return without alloc and copy + if (count == n) return(s_in); - // copy everything up to the first element out of bounds - for (j = 0; j < i; j++) { - y[j] = x[j]; - } + // create a new vector to store the filtered elements + SEXP s_out = PROTECT(allocVector(REALSXP, count)); + double *out = REAL(s_out); - // process remaining elements - for (i = i + 1; i < n; i++) { - if (x[i] != NA_INTEGER && x[i] >= ll && x[i] <= lu) { - y[j] = x[i]; - j++; - } + // Copy the elements within bounds to the new vector + j = 0; + for (i = 0; i < n; i++) { + if (x[i] != NA_INTEGER && x[i] >= ll && x[i] <= lu) + out[j++] = x[i]; } - - // resize the vector to the right length - SETLENGTH(out, j); - - // unprotect + return UNPROTECT(1); - return out; + return s_out; }