warn about exotic protocols as well
[LibreOffice.git] / include / o3tl / unit_conversion.hxx
blob27fb184d52a468a32342fb11cc01cdf6f70f6211
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
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 */
10 #pragma once
12 #include <o3tl/safeint.hxx>
13 #include <sal/macros.h>
14 #include <sal/types.h>
16 #include <array>
17 #include <cassert>
18 #include <numeric>
19 #include <utility>
20 #include <type_traits>
22 namespace o3tl
24 // Length units
25 enum class Length
27 mm100 = 0, // 1/100th mm
28 mm10, // 1/10 mm, corresponds to MapUnit::Map10thMM
29 mm, // millimeter
30 cm, // centimeter
31 m, // meter
32 km, // kilometer
33 emu, // English Metric Unit: 1/360000 cm, 1/914400 in
34 twip, // "Twentieth of a point" aka "dxa": 1/20 pt
35 pt, // Point: 1/72 in
36 pc, // Pica: 1/6 in, corresponds to FieldUnit::PICA and MeasureUnit::PICA
37 in1000, // 1/1000 in, corresponds to MapUnit::Map1000thInch
38 in100, // 1/100 in, corresponds to MapUnit::Map100thInch
39 in10, // 1/10 in, corresponds to MapUnit::Map10thInch
40 in, // inch
41 ft, // foot
42 mi, // mile
43 master, // PPT Master Unit: 1/576 in
44 px, // "pixel" unit: 15 twip (96 ppi), corresponds to MeasureUnit::PIXEL
45 ch, // "char" unit: 210 twip (14 px), corresponds to FieldUnit::CHAR
46 line, // "line" unit: 312 twip, corresponds to FieldUnit::LINE
47 count, // <== add new units above this last entry
48 invalid = -1
51 // If other categories of units would be needed (like time), a separate scoped enum
52 // should be created, respective conversion array prepared in detail namespace, and
53 // respective md(NewUnit, NewUnit) overload introduced, which would allow using
54 // o3tl::convert(), o3tl::convertSaturate() and o3tl::getConversionMulDiv() with the
55 // new category in a type-safe way, without mixing unrelated units.
57 namespace detail
59 // Common utilities
61 // A special function to avoid compiler warning comparing signed and unsigned values
62 template <typename I> constexpr bool isBetween(I n, sal_Int64 min, sal_Int64 max)
64 assert(max > 0 && min < 0);
65 if constexpr (std::is_signed_v<I>)
66 return n >= min && n <= max;
67 else
68 return n <= sal_uInt64(max);
71 // Ensure correct rounding for both positive and negative integers
72 template <typename I, std::enable_if_t<std::is_integral_v<I>, int> = 0>
73 constexpr sal_Int64 MulDiv(I n, sal_Int64 m, sal_Int64 d)
75 assert(m > 0 && d > 0);
76 assert(isBetween(n, (SAL_MIN_INT64 + d / 2) / m, (SAL_MAX_INT64 - d / 2) / m));
77 return (n >= 0 ? (n * m + d / 2) : (n * m - d / 2)) / d;
79 template <typename F, std::enable_if_t<std::is_floating_point_v<F>, int> = 0>
80 constexpr double MulDiv(F f, sal_Int64 m, sal_Int64 d)
82 assert(m > 0 && d > 0);
83 return f * (double(m) / d);
86 template <typename I, std::enable_if_t<std::is_integral_v<I>, int> = 0>
87 constexpr sal_Int64 MulDiv(I n, sal_Int64 m, sal_Int64 d, bool& bOverflow, sal_Int64 nDefault)
89 if (!isBetween(n, (SAL_MIN_INT64 + d / 2) / m, (SAL_MAX_INT64 - d / 2) / m))
91 bOverflow = true;
92 return nDefault;
94 bOverflow = false;
95 return MulDiv(n, m, d);
98 template <typename I, std::enable_if_t<std::is_integral_v<I>, int> = 0>
99 constexpr sal_Int64 MulDivSaturate(I n, sal_Int64 m, sal_Int64 d)
101 if (!isBetween(n, (SAL_MIN_INT64 + d / 2) / m, (SAL_MAX_INT64 - d / 2) / m))
103 if (m > d && !isBetween(n, SAL_MIN_INT64 / m * d + d / 2, SAL_MAX_INT64 / m * d - d / 2))
104 return n > 0 ? SAL_MAX_INT64 : SAL_MIN_INT64; // saturate
105 return (n >= 0 ? n + d / 2 : n - d / 2) / d * m; // divide before multiplication
107 return MulDiv(n, m, d);
110 // Packs integral multiplier and divisor for conversion from one unit to another
111 struct m_and_d
113 sal_Int64 m; // multiplier
114 sal_Int64 d; // divisor
115 constexpr m_and_d(sal_Int64 _m, sal_Int64 _d)
116 : m(_m / std::gcd(_m, _d)) // make sure to use smallest quotients here because
117 , d(_d / std::gcd(_m, _d)) // they will be multiplied when building final table
119 assert(_m > 0 && _d > 0);
123 // Resulting static array N x N of all quotients to convert between all units. The
124 // quotients are minimal to allow largest range of converted numbers without overflow.
125 // Maybe o3tl::enumarray could be used here, but it's not constexpr yet.
126 template <int N> constexpr auto prepareMDArray(const m_and_d (&mdBase)[N])
128 std::array<std::array<sal_Int64, N>, N> a{};
129 for (int i = 0; i < N; ++i)
131 a[i][i] = 1;
132 for (int j = 0; j < i; ++j)
134 assert(mdBase[i].m < SAL_MAX_INT64 / mdBase[j].d);
135 assert(mdBase[i].d < SAL_MAX_INT64 / mdBase[j].m);
136 const sal_Int64 m = mdBase[i].m * mdBase[j].d, d = mdBase[i].d * mdBase[j].m;
137 const sal_Int64 g = std::gcd(m, d);
138 a[i][j] = m / g;
139 a[j][i] = d / g;
142 return a;
145 // A generic template used for fundamental arithmetic types
146 template <typename U> constexpr sal_Int64 md(U i, U /*j*/) { return i; }
148 // Length units implementation
150 // Array of conversion quotients for mm, used to build final conversion table. Entries
151 // are { multiplier, divider } to convert respective unit *to* mm. Order of elements
152 // corresponds to order in o3tl::Length enum (Length::count and Length::invalid omitted).
153 constexpr m_and_d mdBaseLen[] = {
154 { 1, 100 }, // mm100 => mm
155 { 1, 10 }, // mm10 => mm
156 { 1, 1 }, // mm => mm
157 { 10, 1 }, // cm => mm
158 { 1000, 1 }, // m => mm
159 { 1000000, 1 }, // km => mm
160 { 1, 36000 }, // emu => mm
161 { 254, 10 * 1440 }, // twip => mm
162 { 254, 10 * 72 }, // pt => mm
163 { 254, 10 * 6 }, // pc => mm
164 { 254, 10000 }, // in1000 => mm
165 { 254, 1000 }, // in100 => mm
166 { 254, 100 }, // in10 => mm
167 { 254, 10 }, // in => mm
168 { 254 * 12, 10 }, // ft => mm
169 { 254 * 12 * 5280, 10 }, // mi => mm
170 { 254, 10 * 576 }, // master => mm
171 { 254 * 15, 10 * 1440 }, // px => mm
172 { 254 * 210, 10 * 1440 }, // ch => mm
173 { 254 * 312, 10 * 1440 }, // line => mm
175 static_assert(SAL_N_ELEMENTS(mdBaseLen) == static_cast<int>(Length::count),
176 "mdBaseL must have an entry for each unit in o3tl::Length");
178 // The resulting multipliers and divisors array
179 constexpr auto aLengthMDArray = prepareMDArray(mdBaseLen);
181 // an overload taking Length
182 constexpr sal_Int64 md(Length i, Length j)
184 const int nI = static_cast<int>(i), nJ = static_cast<int>(j);
185 assert(nI >= 0 && o3tl::make_unsigned(nI) < aLengthMDArray.size());
186 assert(nJ >= 0 && o3tl::make_unsigned(nJ) < aLengthMDArray.size());
187 return aLengthMDArray[nI][nJ];
190 // here might go overloads of md() taking other units ...
193 // Unchecked conversion. Takes a number value, multiplier and divisor
194 template <typename N> constexpr auto convert(N n, sal_Int64 mul, sal_Int64 div)
196 return detail::MulDiv(n, mul, div);
199 // Unchecked conversion. Takes a number value and units defined in this header
200 template <typename N, typename U> constexpr auto convert(N n, U from, U to)
202 return convert(n, detail::md(from, to), detail::md(to, from));
205 // Convert to twips - for convenience as we do this a lot
206 template <typename N> constexpr auto toTwips(N number, Length from)
208 return convert(number, from, Length::twip);
211 // Returns nDefault if intermediate multiplication overflows sal_Int64 (only for integral types).
212 // On return, bOverflow indicates if overflow happened. nDefault is returned when overflow occurs.
213 template <typename N, typename U>
214 constexpr auto convert(N n, U from, U to, bool& bOverflow, sal_Int64 nDefault = 0)
216 return detail::MulDiv(n, detail::md(from, to), detail::md(to, from), bOverflow, nDefault);
219 // Conversion with saturation (only for integral types). For too large input returns SAL_MAX_INT64.
220 // When intermediate multiplication would overflow, but the end result is in sal_Int64 range, the
221 // precision is decreased because of inversion of multiplication and division.
222 template <typename N, typename U> constexpr auto convertSaturate(N n, U from, U to)
224 return detail::MulDivSaturate(n, detail::md(from, to), detail::md(to, from));
227 // Conversion with saturation (only for integral types), optimized for return types smaller than
228 // sal_Int64. In this case, it's easier to clamp input values to known bounds, than to do some
229 // preprocessing to handle too large input values, just to clamp the result anyway. Use it like:
231 // sal_Int32 n = convertNarrowing<sal_Int32, o3tl::Length::mm100, o3tl::Length::emu>(m);
232 template <typename Out, auto from, auto to, typename N,
233 std::enable_if_t<
234 std::is_integral_v<N> && std::is_integral_v<Out> && sizeof(Out) < sizeof(sal_Int64),
235 int> = 0>
236 constexpr Out convertNarrowing(N n)
238 constexpr sal_Int64 nMin = convertSaturate(std::numeric_limits<Out>::min(), to, from);
239 constexpr sal_Int64 nMax = convertSaturate(std::numeric_limits<Out>::max(), to, from);
240 if (static_cast<sal_Int64>(n) > nMax)
241 return std::numeric_limits<Out>::max();
242 if (static_cast<sal_Int64>(n) < nMin)
243 return std::numeric_limits<Out>::min();
244 return convert(n, from, to);
247 // Return a pair { multiplier, divisor } for a given conversion
248 template <typename U> constexpr std::pair<sal_Int64, sal_Int64> getConversionMulDiv(U from, U to)
250 return { detail::md(from, to), detail::md(to, from) };
254 /* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */