Commit fedcbff6 authored by Mark Olesen's avatar Mark Olesen
Browse files

ENH: provide narrowFloat, narrowInt32 definitions

- underflow/overflow handling for type narrowing.
  Eg, double -> float, int64 -> int32
parent 4e1bc2d2
......@@ -6,7 +6,7 @@
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2016 OpenFOAM Foundation
Copyright (C) 2017-2019 OpenCFD Ltd.
Copyright (C) 2017-2020 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
......@@ -153,6 +153,31 @@ namespace Foam
#endif
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Type conversions (narrowing)
namespace Foam
{
//- Type narrowing from double to float
// Overflow: silently fix, or raise error?
inline float narrowFloat(const double val)
{
// Single statement - future constexpr?
return
(
(val <= -floatScalarVGREAT) ? -floatScalarVGREAT
: (val >= floatScalarVGREAT) ? floatScalarVGREAT
: (val > -floatScalarVSMALL && val < floatScalarVSMALL) // underflow
? 0
: static_cast<float>(val)
);
}
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Additional transcendental functions and specialisations
......
......@@ -6,7 +6,7 @@
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2014 OpenFOAM Foundation
Copyright (C) 2018-2019 OpenCFD Ltd.
Copyright (C) 2018-2020 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
......@@ -169,6 +169,24 @@ struct labelOp<int64_t>
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Type conversions (narrowing)
//- Type narrowing from int64_t to int32_t
// Overflow: silently fix, or raise error?
inline int32_t narrowInt32(const int64_t val)
{
// Single statement - future constexpr?
return
(
(val < INT32_MIN) ? INT32_MIN
: (val > INT32_MAX) ? INT32_MAX
: static_cast<int32_t>(val)
);
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment