Skip to content

Commit 638f329

Browse files
committed
fix functions/sum.h
1 parent 0e79600 commit 638f329

File tree

3 files changed

+21
-6
lines changed

3 files changed

+21
-6
lines changed

inst/include/Rcpp/sugar/functions/sum.h

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
//
33
// sum.h: Rcpp R/C++ interface class library -- sum
44
//
5-
// Copyright (C) 2010 - 2011 Dirk Eddelbuettel and Romain Francois
5+
// Copyright (C) 2010 - 2025 Dirk Eddelbuettel and Romain Francois
6+
// Copyright (C) 2026 Dirk Eddelbuettel, Romain Francois and Iñaki Ucar
67
//
78
// This file is part of Rcpp.
89
//
@@ -42,7 +43,7 @@ class Sum : public Lazy< typename Rcpp::traits::storage_type<RTYPE>::type , Sum<
4243
current = object[i] ;
4344
if( Rcpp::traits::is_na<RTYPE>(current) )
4445
return Rcpp::traits::get_na<RTYPE>() ;
45-
result += current ;
46+
result = RCPP_SAFE_ADD(result, current);
4647
}
4748
return result ;
4849
}
@@ -84,7 +85,7 @@ class Sum<RTYPE,false,T> : public Lazy< typename Rcpp::traits::storage_type<RTYP
8485
STORAGE result = 0 ;
8586
R_xlen_t n = object.size() ;
8687
for( R_xlen_t i=0; i<n; i++){
87-
result += object[i] ;
88+
result = RCPP_SAFE_ADD(result, object[i]);
8889
}
8990
return result ;
9091
}

inst/tinytest/cpp/sugar.cpp

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -604,7 +604,12 @@ List runit_log1p( NumericVector xx){
604604
}
605605

606606
// [[Rcpp::export]]
607-
double runit_sum( NumericVector xx){
607+
double runit_sum_nv( NumericVector xx){
608+
return sum( xx ) ;
609+
}
610+
611+
// [[Rcpp::export]]
612+
int runit_sum_iv( IntegerVector xx){
608613
return sum( xx ) ;
609614
}
610615

inst/tinytest/test_sugar.R

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -645,14 +645,23 @@ expect_equal(fx(10:6,5:1),
645645
VP = psigamma( 10:6, 5 )))
646646

647647

648-
# test.sugar.sum <- function(){
649-
fx <- runit_sum
648+
# test.sugar.sum_nv <- function(){
649+
fx <- runit_sum_nv
650650
x <- rnorm( 10 )
651651
expect_equal( fx(x), sum(x) )
652652
x[4] <- NA
653653
expect_equal( fx(x), sum(x) )
654654

655655

656+
# test.sugar.sum_iv <- function() {
657+
expect_error(runit_sum_iv(c(2, .Machine$integer.max)), "overflow")
658+
fx <- runit_sum_iv
659+
x <- as.integer(rpois(10, 5))
660+
expect_equal(fx(x), sum(x))
661+
x[4] <- NA
662+
expect_equal(fx(x), sum(x))
663+
664+
656665
# test.sugar.cumsum_nv <- function(){
657666
fx <- runit_cumsum_nv
658667
x <- rnorm(10)

0 commit comments

Comments
 (0)