Merge branch 'tor-gitlab/mr/568'
[tor.git] / src / lib / intmath / addsub.c
blobcdc259b74d62e9303723072efcb9f0d4a6b0ec56
1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2021, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 /**
7 * \file addsub.c
9 * \brief Helpers for addition and subtraction.
11 * Currently limited to non-wrapping (saturating) addition.
12 **/
14 #include "lib/intmath/addsub.h"
15 #include "lib/cc/compat_compiler.h"
17 /* Helper: safely add two uint32_t's, capping at UINT32_MAX rather
18 * than overflow */
19 uint32_t
20 tor_add_u32_nowrap(uint32_t a, uint32_t b)
22 /* a+b > UINT32_MAX check, without overflow */
23 if (PREDICT_UNLIKELY(a > UINT32_MAX - b)) {
24 return UINT32_MAX;
25 } else {
26 return a+b;