addsub.c 566 B

1234567891011121314151617181920
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. #include "lib/intmath/addsub.h"
  6. #include "lib/cc/compat_compiler.h"
  7. /* Helper: safely add two uint32_t's, capping at UINT32_MAX rather
  8. * than overflow */
  9. uint32_t
  10. tor_add_u32_nowrap(uint32_t a, uint32_t b)
  11. {
  12. /* a+b > UINT32_MAX check, without overflow */
  13. if (PREDICT_UNLIKELY(a > UINT32_MAX - b)) {
  14. return UINT32_MAX;
  15. } else {
  16. return a+b;
  17. }
  18. }