Skip to content

Commit

Permalink
fix keep_in_bounds so we dont use internal API
Browse files Browse the repository at this point in the history
  • Loading branch information
berndbischl committed Jun 24, 2024
1 parent ebdcf1d commit 1cba917
Showing 1 changed file with 21 additions and 38 deletions.
59 changes: 21 additions & 38 deletions src/keep_in_bounds.c
Original file line number Diff line number Diff line change
@@ -1,48 +1,31 @@
#define R_NO_REMAP
#include <R.h>
#include <Rinternals.h>

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;
}

0 comments on commit 1cba917

Please sign in to comment.