Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
repetition of a symbol, and reports each unrecognized symbol once; #441
addressing #440 @billdenney

* Format units longer than 255 bytes in full instead of silently truncating
them, which made e.g. `convert_to_base()` fail on such units; @billdenney

# version 1.0-1

* Add internal workaround for udunits2 bug with parsing of units that contain
Expand Down
12 changes: 9 additions & 3 deletions src/udunits.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,13 @@ CharacterVector R_ut_format(xut_unit p, bool names = false,
if (definition)
opt = opt | UT_DEFINITION;
char buf[256];
if (ut_format(p, buf, sizeof(buf), opt) == sizeof(buf))
warning("buffer too small!"); // #nocov
return CharacterVector::create(buf);
int len = ut_format(p, buf, sizeof(buf), opt);
if (len < 0)
stop("cannot format unit"); // #nocov (r_error_fn throws first)
if (len < (int) sizeof(buf))
return CharacterVector::create(buf);
// ut_format() truncated the unit to fit, and returned the length it needs
std::vector<char> longer(len + 1);
ut_format(p, longer.data(), longer.size(), opt);
return CharacterVector::create(longer.data());
}
20 changes: 20 additions & 0 deletions tests/testthat/test_udunits.R
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,23 @@ test_that("ud_convert works with vectors", {
test_that("ud_convert returns Error for incompatible units", {
expect_error(ud_convert(100, "m", "kg"), "Units not convertible")
})

test_that("units longer than 255 bytes are formatted in full", {
# 50 base units whose product formats as "zqaa.zqab.<...>", len bytes in all
long_unit <- function(len) {
syms <- paste0("zq", apply(expand.grid(letters, letters)[1:50, 2:1], 1,
paste, collapse = ""))
syms[50] <- paste0(syms[50], strrep("z", len - 249))
syms
}
for (len in c(255, 256, 257, 300)) {
syms <- long_unit(len)
for (s in syms) install_unit(s)
u <- paste(syms, collapse = " ")
expect_identical(units:::ud_parse(u, definition = TRUE, ascii = TRUE),
paste(syms, collapse = "."))
x <- set_units(1, u, mode = "standard")
expect_identical(units(convert_to_base(x))$numerator, syms)
remove_unit(syms)
}
})
Loading