1 | // Copyright 2013 The Flutter Authors. All rights reserved. |
---|---|
2 | // Use of this source code is governed by a BSD-style license that can be |
3 | // found in the LICENSE file. |
4 | |
5 | #ifndef FLUTTER_LIB_UI_FLOATING_POINT_H_ |
6 | #define FLUTTER_LIB_UI_FLOATING_POINT_H_ |
7 | |
8 | #include <algorithm> |
9 | #include <limits> |
10 | |
11 | namespace flutter { |
12 | |
13 | /// Converts a double to a float, truncating finite values that are larger than |
14 | /// FLT_MAX or smaller than FLT_MIN to those values. |
15 | static float SafeNarrow(double value) { |
16 | if (std::isinf(lcpp_x: value) || std::isnan(lcpp_x: value)) { |
17 | return static_cast<float>(value); |
18 | } else { |
19 | // Avoid truncation to inf/-inf. |
20 | return std::clamp(v: static_cast<float>(value), |
21 | lo: std::numeric_limits<float>::lowest(), |
22 | hi: std::numeric_limits<float>::max()); |
23 | } |
24 | } |
25 | |
26 | } // namespace flutter |
27 | |
28 | #endif // FLUTTER_LIB_UI_FLOATING_POINT_H_ |
29 |