NumericTools.h (1428B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 3 /* This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 #ifndef MOZILLA_GFX_NUMERICTOOLS_H_ 8 #define MOZILLA_GFX_NUMERICTOOLS_H_ 9 10 #include <cstdint> 11 12 namespace mozilla { 13 14 // XXX - Move these into mfbt/MathAlgorithms.h? 15 16 // Returns the largest multiple of aMultiplied that's <= x. 17 // Same as int32_t(floor(double(x) / aMultiplier)) * aMultiplier, 18 // but faster. 19 inline int32_t RoundDownToMultiple(int32_t x, int32_t aMultiplier) { 20 // We don't use float division + floor because that's hard for the compiler 21 // to optimize. 22 int mod = x % aMultiplier; 23 if (x > 0) { 24 return x - mod; 25 } 26 return mod ? x - aMultiplier - mod : x; 27 } 28 29 // Returns the smallest multiple of aMultiplied that's >= x. 30 // Same as int32_t(ceil(double(x) / aMultiplier)) * aMultiplier, 31 // but faster. 32 inline int32_t RoundUpToMultiple(int32_t x, int32_t aMultiplier) { 33 int mod = x % aMultiplier; 34 if (x > 0) { 35 return mod ? x + aMultiplier - mod : x; 36 } 37 return x - mod; 38 } 39 40 inline int32_t RoundToMultiple(int32_t x, int32_t aMultiplier) { 41 return RoundDownToMultiple(x + aMultiplier / 2, aMultiplier); 42 } 43 44 } // namespace mozilla 45 46 #endif /* MOZILLA_GFX_NUMERICTOOLS_H_ */