Home | History | Annotate | Download | only in geometry
      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 
     16 inline int ToFlooredInt(float value) {
     17   return base::saturated_cast<int>(std::floor(value));
     18 }
     19 
     20 inline int ToCeiledInt(float value) {
     21   return base::saturated_cast<int>(std::ceil(value));
     22 }
     23 
     24 inline int ToFlooredInt(double value) {
     25   return base::saturated_cast<int>(std::floor(value));
     26 }
     27 
     28 inline int ToCeiledInt(double value) {
     29   return base::saturated_cast<int>(std::ceil(value));
     30 }
     31 
     32 inline 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 
     41 inline 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 
     50 inline 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