/indra/llmath/llmodularmath.h

https://bitbucket.org/lindenlab/viewer-beta/ · C++ Header · 52 lines · 12 code · 4 blank · 36 comment · 0 complexity · 60644ba70eedd810cc6a7f657c22b64c MD5 · raw file

  1. /**
  2. * @file llmodularmath.h
  3. * @brief Useful modular math functions.
  4. *
  5. * $LicenseInfo:firstyear=2008&license=viewerlgpl$
  6. * Second Life Viewer Source Code
  7. * Copyright (C) 2010, Linden Research, Inc.
  8. *
  9. * This library is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU Lesser General Public
  11. * License as published by the Free Software Foundation;
  12. * version 2.1 of the License only.
  13. *
  14. * This library is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * Lesser General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Lesser General Public
  20. * License along with this library; if not, write to the Free Software
  21. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  22. *
  23. * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
  24. * $/LicenseInfo$
  25. */
  26. #ifndef LLMODULARMATH_H
  27. #define LLMODULARMATH_H
  28. namespace LLModularMath
  29. {
  30. // Return difference between lhs and rhs
  31. // treating the U32 operands and result
  32. // as unsigned values of given width.
  33. template<int width>
  34. inline U32 subtract(U32 lhs, U32 rhs)
  35. {
  36. // Generate a bit mask which will truncate
  37. // unsigned values to given width at compile time.
  38. const U32 mask = (1 << width) - 1;
  39. // Operands are unsigned, so modular
  40. // arithmetic applies. If lhs < rhs,
  41. // difference will wrap in to lower
  42. // bits of result, which is then masked
  43. // to give a value that can be represented
  44. // by an unsigned value of width bits.
  45. return mask & (lhs - rhs);
  46. }
  47. }
  48. #endif