aboutsummaryrefslogtreecommitdiff
path: root/contrib
diff options
context:
space:
mode:
authorAlexander Blair <snipa@jagtech.io>2020-08-16 12:53:50 -0700
committerAlexander Blair <snipa@jagtech.io>2020-08-16 12:53:50 -0700
commit10ad0d7eb274bcbad064eaa0de0483d6f94231d3 (patch)
treeba61cb2927188da0b873094a3f438b1514bacdc0 /contrib
parentMerge pull request #6716 (diff)
parentFix overflow issue in epee:misc_utils::rolling_median_t and median(), with un... (diff)
downloadmonero-10ad0d7eb274bcbad064eaa0de0483d6f94231d3.tar.xz
Merge pull request #6718
85efc88c1 Fix overflow issue in epee:misc_utils::rolling_median_t and median(), with unit test (koe)
Diffstat (limited to 'contrib')
-rw-r--r--contrib/epee/include/misc_language.h10
-rw-r--r--contrib/epee/include/rolling_median.h4
2 files changed, 12 insertions, 2 deletions
diff --git a/contrib/epee/include/misc_language.h b/contrib/epee/include/misc_language.h
index 5f7202150..a04c63231 100644
--- a/contrib/epee/include/misc_language.h
+++ b/contrib/epee/include/misc_language.h
@@ -106,6 +106,14 @@ namespace misc_utils
return true;
}
+ template <typename T>
+ T get_mid(const T &a, const T &b)
+ {
+ //returns the average of two numbers; overflow safe and works with at least all integral and floating point types
+ //(a+b)/2 = (a/2) + (b/2) + ((a - 2*(a/2)) + (b - 2*(b/2)))/2
+ return (a/2) + (b/2) + ((a - 2*(a/2)) + (b - 2*(b/2)))/2;
+ }
+
template<class type_vec_type>
type_vec_type median(std::vector<type_vec_type> &v)
{
@@ -122,7 +130,7 @@ namespace misc_utils
return v[n];
}else
{//2, 4, 6...
- return (v[n-1] + v[n])/2;
+ return get_mid<type_vec_type>(v[n-1],v[n]);
}
}
diff --git a/contrib/epee/include/rolling_median.h b/contrib/epee/include/rolling_median.h
index 11275aa70..088a71d3e 100644
--- a/contrib/epee/include/rolling_median.h
+++ b/contrib/epee/include/rolling_median.h
@@ -34,6 +34,8 @@
#pragma once
+#include "misc_language.h"
+
#include <stdlib.h>
#include <stdint.h>
@@ -226,7 +228,7 @@ public:
Item v = data[heap[0]];
if (minCt < maxCt)
{
- v = (v + data[heap[-1]]) / 2;
+ v = get_mid<Item>(v, data[heap[-1]]);
}
return v;
}