addsub.c 708 B

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