ENH: provide narrowFloat, narrowInt32 definitions

- underflow/overflow handling for type narrowing.
  Eg, double -> float, int64 -> int32
This commit is contained in:
Mark Olesen
2020-02-18 16:17:56 +01:00
parent 4e1bc2d2f1
commit fedcbff6f4
2 changed files with 45 additions and 2 deletions

View File

@ -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

View File

@ -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