1 // Copyright (c) 2012 The Chromium 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 UI_GFX_GEOMETRY_SAFE_INTEGER_CONVERSIONS_H_ 6 #define UI_GFX_GEOMETRY_SAFE_INTEGER_CONVERSIONS_H_ 7 8 #include <cmath> 9 #include <limits> 10 11 #include "base/numerics/safe_conversions.h" 12 #include "ui/gfx/gfx_export.h" 13 14 namespace gfx { 15 ToFlooredInt(float value)16inline int ToFlooredInt(float value) { 17 return base::saturated_cast<int>(std::floor(value)); 18 } 19 ToCeiledInt(float value)20inline int ToCeiledInt(float value) { 21 return base::saturated_cast<int>(std::ceil(value)); 22 } 23 ToFlooredInt(double value)24inline int ToFlooredInt(double value) { 25 return base::saturated_cast<int>(std::floor(value)); 26 } 27 ToCeiledInt(double value)28inline int ToCeiledInt(double value) { 29 return base::saturated_cast<int>(std::ceil(value)); 30 } 31 ToRoundedInt(float value)32inline int ToRoundedInt(float value) { 33 float rounded; 34 if (value >= 0.0f) 35 rounded = std::floor(value + 0.5f); 36 else 37 rounded = std::ceil(value - 0.5f); 38 return base::saturated_cast<int>(rounded); 39 } 40 ToRoundedInt(double value)41inline int ToRoundedInt(double value) { 42 double rounded; 43 if (value >= 0.0) 44 rounded = std::floor(value + 0.5); 45 else 46 rounded = std::ceil(value - 0.5); 47 return base::saturated_cast<int>(rounded); 48 } 49 IsExpressibleAsInt(float value)50inline bool IsExpressibleAsInt(float value) { 51 if (value != value) 52 return false; // no int NaN. 53 if (value > std::numeric_limits<int>::max()) 54 return false; 55 if (value < std::numeric_limits<int>::min()) 56 return false; 57 return true; 58 } 59 60 } // namespace gfx 61 62 #endif // UI_GFX_GEOMETRY_SAFE_INTEGER_CONVERSIONS_H_ 63