Skip to content

Reduce duplication: growVector() vs. copyAsPlain()? #6908

Description

@MichaelChirico

Both these routines have very similar implementations hingeing on memcpy():

data.table/src/dogroups.c

Lines 544 to 558 in 7c3800f

case RAWSXP: memcpy(RAW(newx), RAW(x), len*SIZEOF(x)); break;
case LGLSXP: memcpy(LOGICAL(newx), LOGICAL(x), len*SIZEOF(x)); break;
case INTSXP: memcpy(INTEGER(newx), INTEGER(x), len*SIZEOF(x)); break;
case REALSXP: memcpy(REAL(newx), REAL(x), len*SIZEOF(x)); break;
case CPLXSXP: memcpy(COMPLEX(newx), COMPLEX(x), len*SIZEOF(x)); break;
case STRSXP : {
const SEXP *xd = SEXPPTR_RO(x);
for (int i=0; i<len; ++i)
SET_STRING_ELT(newx, i, xd[i]);
} break;
case VECSXP : {
const SEXP *xd = SEXPPTR_RO(x);
for (int i=0; i<len; ++i)
SET_VECTOR_ELT(newx, i, xd[i]);
} break;

data.table/src/utils.c

Lines 233 to 259 in 7c3800f

switch (TYPEOF(x)) {
case RAWSXP:
memcpy(RAW(ans), RAW(x), n*sizeof(Rbyte));
break;
case LGLSXP:
memcpy(LOGICAL(ans), LOGICAL(x), n*sizeof(int));
break;
case INTSXP:
memcpy(INTEGER(ans), INTEGER(x), n*sizeof(int)); // covered by 10:1 after test 178
break;
case REALSXP:
memcpy(REAL(ans), REAL(x), n*sizeof(double)); // covered by as.Date("2013-01-01")+seq(1,1000,by=10) after test 1075
break;
case CPLXSXP:
memcpy(COMPLEX(ans), COMPLEX(x), n*sizeof(Rcomplex));
break;
case STRSXP: {
const SEXP *xp=STRING_PTR_RO(x); // covered by as.character(as.hexmode(1:500)) after test 642
for (int64_t i=0; i<n; ++i) SET_STRING_ELT(ans, i, xp[i]);
} break;
case VECSXP: {
const SEXP *xp=SEXPPTR_RO(x);
for (int64_t i=0; i<n; ++i) SET_VECTOR_ELT(ans, i, copyAsPlain(xp[i]));
} break;
default: // # nocov
internal_error(__func__, "type '%s' not supported in %s", type2char(TYPEOF(x)), "copyAsPlain()"); // # nocov
}

Should they be unified in any way?

Activity

  1. aitap commented on Apr 18, 2025

    @aitap
    Member

    Makes sense. Perhaps copyAsPlain(x) could delegate to growVector(x, length(x)) (which is really allocateLonger, the original vector is not grown) after checking that it is dealing with a vector type.

  2. ben-schwen commented on Jan 17, 2026

    @ben-schwen
    Member

    I have implemented the dedup in #7602 but I'm not sure that is superior over adding comment to both functions, linking to each other...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions