Elements 6.3.1
A C++ base framework for the Euclid Software.
Loading...
Searching...
No Matches
Storage.tpp
Go to the documentation of this file.
1
23// IWYU pragma: private, include "ElementsKernel/Storage.h"
24
25#ifndef ELEMENTSKERNEL_ELEMENTSKERNEL_STORAGE_IMPL_
26#error "This file should not be included directly! Use ElementsKernel/Storage.h instead"
27#else
28
29#include <cmath> // for log10, pow, round
30#include <cstddef> // for size_t
31#include <cstdint> // for int64_t
32#include <map> // for map
33
34#include "ElementsKernel/Number.h" // for numberCast
35
36namespace Elements {
37inline namespace Kernel {
38namespace Units {
39
40template <typename T>
41T roundToDigits(const T& value, const size_t& max_digits) {
42 std::int64_t factor = std::int64_t(std::pow(10, max_digits));
43 return std::round(value * static_cast<T>(factor)) / static_cast<T>(factor);
44}
45
46template <std::size_t max_digits, typename T>
47T storageConvert(const T& size, StorageType source_unit, StorageType target_unit) {
48
49 using std::log10;
50
51 T converted_value = size;
52
53 if (source_unit != target_unit) {
54 T size_in_bytes = size * T(StorageFactor[source_unit]);
55 int64_t target_factor = StorageFactor[target_unit];
56 double value = roundToDigits(static_cast<double>(size_in_bytes) / static_cast<double>(target_factor), max_digits);
57 converted_value = Elements::numberCast<T>(value);
58 }
59
60 return converted_value;
61}
62
63template <typename T>
64T storageConvert(const T& size, StorageType source_unit, StorageType target_unit) {
65
66 using std::log10;
67
68 T converted_value = size;
69
70 if (source_unit != target_unit) {
71 T size_in_bytes = size * T(StorageFactor[source_unit]);
72 int64_t target_factor = StorageFactor[target_unit];
73 double value = roundToDigits(static_cast<double>(size_in_bytes) / static_cast<double>(target_factor),
74 static_cast<size_t>(log10(static_cast<double>(target_factor))));
75 converted_value = Elements::numberCast<T>(value);
76 }
77
78 return converted_value;
79}
80
81} // namespace Units
82} // namespace Kernel
83} // namespace Elements
84
85#endif // ELEMENTSKERNEL_ELEMENTSKERNEL_STORAGE_IMPL_
Casting with the correct (closest) rounding.
ELEMENTS_API TargetType numberCast(const SourceType &s)
this function is a number cast. It behaves exactly as a static_cast except when casting from a floati...
T log10(T... args)
ELEMENTS_API T storageConvert(const T &size, StorageType source_unit, StorageType target_unit)
ELEMENTS_API T roundToDigits(const T &value, const std::size_t &max_digits)
ELEMENTS_API std::map< StorageType, std::int64_t > StorageFactor
Definition Storage.cpp:50
T pow(T... args)
T round(T... args)