Bump version to 6.4-15
[LibreOffice.git] / include / tools / helpers.hxx
blob1d00bad7112e81df6e2e3e7c453fe1678cba5e87
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 */
9 #ifndef INCLUDED_TOOLS_HELPERS_HXX
10 #define INCLUDED_TOOLS_HELPERS_HXX
12 #include <sal/config.h>
13 #include <sal/types.h>
14 #include <o3tl/safeint.hxx>
15 #include <cassert>
16 #include <type_traits>
18 template<typename T>
19 inline
20 typename std::enable_if<
21 std::is_signed<T>::value || std::is_floating_point<T>::value, long >::type
22 MinMax(T nVal, long nMin, long nMax)
24 assert(nMin <= nMax);
25 if (nVal >= nMin)
27 if (nVal <= nMax)
28 return static_cast<long>(nVal);
29 else
30 return nMax;
32 else
34 return nMin;
38 template<typename T>
39 inline
40 typename std::enable_if<
41 std::is_unsigned<T>::value, long >::type
42 MinMax(T nVal, long nMin, long nMax)
44 assert(nMin <= nMax);
45 if (nMax < 0)
47 return nMax;
49 else
51 if (nMin < 0 || nVal >= static_cast<unsigned long>(nMin))
53 if (nVal <= static_cast<unsigned long>(nMax))
54 return static_cast<long>(nVal);
55 else
56 return nMax;
58 else
60 return nMin;
65 inline sal_uInt32 AlignedWidth4Bytes(sal_uInt32 nWidthBits)
67 if (nWidthBits > SAL_MAX_UINT32 - 31)
68 nWidthBits = SAL_MAX_UINT32;
69 else
70 nWidthBits += 31;
71 return (nWidthBits >> 5) << 2;
74 inline long FRound( double fVal )
76 return fVal > 0.0 ? static_cast<long>( fVal + 0.5 ) : -static_cast<long>( -fVal + 0.5 );
79 //valid range: (-180,180]
80 template <typename T>
81 [[nodiscard]] inline typename std::enable_if<std::is_signed<T>::value, T>::type
82 NormAngle180(T angle)
84 while (angle <= -180)
85 angle += 360;
86 while (angle > 180)
87 angle -= 360;
88 return angle;
91 //valid range: [0,360)
92 template <typename T> [[nodiscard]] inline T NormAngle360(T angle)
94 while (angle < 0)
95 angle += 360;
96 while (angle >= 360)
97 angle -= 360;
98 return angle;
101 /** Convert 100th-mm to twips
103 A twip is 1/20 of a point, one inch is equal to 72 points, and
104 one inch is 2,540 100th-mm.
106 Thus:
107 twips = n * 72 / 2,540 / 20
108 = n * 72 / 127
110 Adding 63 (half of 127) fixes truncation issues in int arithmetic.
112 This formula is (n>=0) ? (n*72+63) / 127 : (n*72-63) / 127
114 inline sal_Int64 sanitiseMm100ToTwip(sal_Int64 n)
116 if (n >= 0)
118 if (o3tl::checked_multiply<sal_Int64>(n, 72, n) || o3tl::checked_add<sal_Int64>(n, 63, n))
119 n = SAL_MAX_INT64;
121 else
123 if (o3tl::checked_multiply<sal_Int64>(n, 72, n) || o3tl::checked_sub<sal_Int64>(n, 63, n))
124 n = SAL_MIN_INT64;
126 return n / 127; // 127 is 2,540 100th-mm divided by 20pts
129 #endif
131 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */