Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recycle ext argument of path() correctly #446

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion R/path.R
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ NULL
#' path("foo", letters[1:3], ext = "txt")
path <- function(..., ext = "") {
args <- list(...)
assert_recyclable(args)
assert_recyclable(c(args, list(ext)))

path_tidy(.Call(fs_path_, lapply(args, function(x) enc2utf8(as.character(x))), ext))
}
Expand Down
11 changes: 10 additions & 1 deletion src/path.cc
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ extern "C" SEXP fs_path_(SEXP paths, SEXP ext_sxp) {
R_xlen_t max_col = Rf_xlength(paths);
char buf[PATH_MAX];
char* b = buf;
if (max_col == 0) {
return Rf_allocVector(STRSXP, 0);
}
for (R_xlen_t c = 0; c < max_col; ++c) {
R_xlen_t len = Rf_xlength(VECTOR_ELT(paths, c));
if (len == 0) {
Expand All @@ -45,7 +48,12 @@ extern "C" SEXP fs_path_(SEXP paths, SEXP ext_sxp) {
}
}

const char* ext = CHAR(STRING_ELT(ext_sxp, 0));
R_xlen_t ext_len = Rf_xlength(ext_sxp);
if (ext_len == 0) {
return Rf_allocVector(STRSXP, 0);
} else if (ext_len > max_row) {
max_row = ext_len;
}

SEXP out = PROTECT(Rf_allocVector(STRSXP, max_row));
for (R_xlen_t r = 0; r < max_row; ++r) {
Expand Down Expand Up @@ -81,6 +89,7 @@ extern "C" SEXP fs_path_(SEXP paths, SEXP ext_sxp) {
if (has_na) {
SET_STRING_ELT(out, r, NA_STRING);
} else {
const char* ext = CHAR(STRING_ELT(ext_sxp, r % ext_len));
if (strlen(ext) > 0) {
*b++ = '.';
strcpy(b, ext);
Expand Down
14 changes: 14 additions & 0 deletions tests/testthat/test-path.R
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,20 @@ describe("path", {
)

expect_error(path(c("foo", "qux", "foo2"), c("bar", "baz")), "Arguments must have consistent lengths", class = "invalid_argument")

expect_equal(path(ext = character()), fs_path(character()))
expect_equal(path("foo", ext = character()), fs_path(character()))
expect_equal(path("foo", ext = "bar"), fs_path("foo.bar"))
expect_equal(
path("foo", ext = c("bar", "baz")),
fs_path(c("foo.bar", "foo.baz"))
)
expect_equal(
path(c("foo", "qux"), ext = c("bar", "baz")),
fs_path(c("foo.bar", "qux.baz"))
)

expect_error(path(c("foo", "qux", "foo2"), ext = c("bar", "baz")), "Arguments must have consistent lengths", class = "invalid_argument")
})
})

Expand Down