1 /*
2     Scan Tailor - Interactive post-processing tool for scanned pages.
3     Copyright (C)  Joseph Artsimovich <joseph.artsimovich@gmail.com>
4 
5     This program is free software: you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation, either version 3 of the License, or
8     (at your option) any later version.
9 
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14 
15     You should have received a copy of the GNU General Public License
16     along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 #ifndef VALUE_CONV_H_
20 #define VALUE_CONV_H_
21 
22 #include <cmath>
23 #include "NumericTraits.h"
24 
25 template <typename ToType>
26 class StaticCastValueConv {
27  public:
28   template <typename FromType>
operator()29   ToType operator()(FromType val) const {
30     return static_cast<ToType>(val);
31   }
32 };
33 
34 
35 template <typename ToType>
36 class RoundAndClipValueConv {
37  public:
38   explicit RoundAndClipValueConv(ToType min = NumericTraits<ToType>::min(), ToType max = NumericTraits<ToType>::max())
m_min(min)39       : m_min(min), m_max(max) {}
40 
41   template <typename FromType>
operator()42   ToType operator()(FromType val) const {
43     // To avoid possible "comparing signed to unsigned" warnings,
44     // we do the comparison with FromType.  It should be fine, as
45     // "Round" in the name of the class assumes it's a floating point type,
46     // and therefore should be "wider" than ToType.
47     if (val < FromType(m_min)) {
48       return m_min;
49     } else if (val > FromType(m_max)) {
50       return m_max;
51     } else {
52       return static_cast<ToType>(std::floor(val + 0.5));
53     }
54   }
55 
56  private:
57   ToType m_min;
58   ToType m_max;
59 };
60 
61 
62 #endif  // ifndef VALUE_CONV_H_
63