Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / ui / gfx / geometry / safe_integer_conversions.h
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 "ui/gfx/gfx_export.h"
12
13 namespace gfx {
14
15 inline int ClampToInt(float value) {
16   if (value != value)
17     return 0; // no int NaN.
18   if (value >= std::numeric_limits<int>::max())
19     return std::numeric_limits<int>::max();
20   if (value <= std::numeric_limits<int>::min())
21     return std::numeric_limits<int>::min();
22   return static_cast<int>(value);
23 }
24
25 inline int ToFlooredInt(float value) {
26   return ClampToInt(std::floor(value));
27 }
28
29 inline int ToCeiledInt(float value) {
30   return ClampToInt(std::ceil(value));
31 }
32
33 inline int ToFlooredInt(double value) {
34   return ClampToInt(std::floor(value));
35 }
36
37 inline int ToCeiledInt(double value) {
38   return ClampToInt(std::ceil(value));
39 }
40
41 inline int ToRoundedInt(float value) {
42   float rounded;
43   if (value >= 0.0f)
44     rounded = std::floor(value + 0.5f);
45   else
46     rounded = std::ceil(value - 0.5f);
47   return ClampToInt(rounded);
48 }
49
50 inline int ToRoundedInt(double value) {
51   double rounded;
52   if (value >= 0.0)
53     rounded = std::floor(value + 0.5);
54   else
55     rounded = std::ceil(value - 0.5);
56   return ClampToInt(rounded);
57 }
58
59 inline bool IsExpressibleAsInt(float value) {
60   if (value != value)
61     return false; // no int NaN.
62   if (value > std::numeric_limits<int>::max())
63     return false;
64   if (value < std::numeric_limits<int>::min())
65     return false;
66   return true;
67 }
68
69 }  // namespace gfx
70
71 #endif  // UI_GFX_GEOMETRY_SAFE_INTEGER_CONVERSIONS_H_