2 * @file ElementsKernel/_impl/Storage.tpp
5 * @author Hubert Degaudenzi
7 * @copyright 2012-2020 Euclid Science Ground Segment
9 * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General
10 * Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option)
13 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
14 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
17 * You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to
18 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 #ifndef ELEMENTSKERNEL_ELEMENTSKERNEL_STORAGE_IMPL_
24 #error "This file should not be included directly! Use ElementsKernel/Storage.h instead"
27 #include <cmath> // for pow, round
28 #include <cstdint> // for int64_t
30 #include "ElementsKernel/Number.h" // for numberCast
33 inline namespace Kernel {
37 ELEMENTS_API T roundToDigits(const T& value, const size_t& max_digits) {
38 std::int64_t factor = std::int64_t(std::pow(10, max_digits));
39 return std::round(value * static_cast<T>(factor)) / static_cast<T>(factor);
42 template <std::size_t max_digits, typename T>
43 ELEMENTS_API T storageConvert(const T& size, StorageType source_unit, StorageType target_unit) {
47 T converted_value = size;
49 if (source_unit != target_unit) {
50 T size_in_bytes = size * T(StorageFactor[source_unit]);
51 int64_t target_factor = StorageFactor[target_unit];
52 double value = roundToDigits(static_cast<double>(size_in_bytes) / static_cast<double>(target_factor), max_digits);
53 converted_value = Elements::numberCast<T>(value);
56 return converted_value;
60 ELEMENTS_API T storageConvert(const T& size, StorageType source_unit, StorageType target_unit) {
64 T converted_value = size;
66 if (source_unit != target_unit) {
67 T size_in_bytes = size * T(StorageFactor[source_unit]);
68 int64_t target_factor = StorageFactor[target_unit];
69 double value = roundToDigits(static_cast<double>(size_in_bytes) / static_cast<double>(target_factor),
70 static_cast<size_t>(log10(static_cast<double>(target_factor))));
71 converted_value = Elements::numberCast<T>(value);
74 return converted_value;
79 } // namespace Elements
81 #endif // ELEMENTSKERNEL_ELEMENTSKERNEL_STORAGE_IMPL_