MySQL 9.1.0
Source Code Documentation
add_with_saturate.h
Go to the documentation of this file.
1#ifndef INCLUDE_ADD_WITH_SATURATE_H_
2#define INCLUDE_ADD_WITH_SATURATE_H_
3
4/*
5 Copyright (c) 2018, 2024, Oracle and/or its affiliates.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License, version 2.0,
9 as published by the Free Software Foundation.
10
11 This program is designed to work with certain software (including
12 but not limited to OpenSSL) that is licensed under separate terms,
13 as designated in a particular file or component or in included license
14 documentation. The authors of MySQL hereby grant you an additional
15 permission to link the program and your derivative works with the
16 separately licensed software that they have either included with
17 the program or referenced in the documentation.
18
19 This program is distributed in the hope that it will be useful,
20 but WITHOUT ANY WARRANTY; without even the implied warranty of
21 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 GNU General Public License, version 2.0, for more details.
23
24 You should have received a copy of the GNU General Public License
25 along with this program; if not, write to the Free Software
26 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
27
28/**
29 @file include/add_with_saturate.h
30 Some utilities for saturating add.
31 */
32
33#include <limits>
34#include <type_traits>
35
36// Returns a + b, saturated to the range of a.
37template <class T, class U>
38inline T AddWithSaturate(T a, U b) {
39 static_assert(!std::is_signed<T>::value, "values must be unsigned");
40 static_assert(!std::is_signed<U>::value, "values must be unsigned");
41
42 auto result = a + b;
43 if (result < a || result > std::numeric_limits<T>::max()) {
44 // Value wrapped around or was promoted to a larger type; saturate to the
45 // maximum value.
46 return std::numeric_limits<T>::max();
47 }
48 return result;
49}
50
51// Effectively does b += a; with saturation.
52template <class T, class U>
53inline void AddWithSaturate(T a, U *b) {
54 *b = AddWithSaturate(*b, a);
55}
56
57#endif // INCLUDE_ADD_WITH_SATURATE_H_
T AddWithSaturate(T a, U b)
Definition: add_with_saturate.h:38
struct result result
Definition: result.h:34
Definition: result.h:30
Definition: dtoa.cc:595