tor  0.4.2.0-alpha-dev
muldiv.c
Go to the documentation of this file.
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 
12 #include "lib/intmath/muldiv.h"
13 #include "lib/err/torerr.h"
14 
15 #include <stdlib.h>
16 
20 unsigned
21 round_to_next_multiple_of(unsigned number, unsigned divisor)
22 {
23  raw_assert(divisor > 0);
24  if (UINT_MAX - divisor + 1 < number)
25  return UINT_MAX;
26  number += divisor - 1;
27  number -= number % divisor;
28  return number;
29 }
30 
34 uint32_t
35 round_uint32_to_next_multiple_of(uint32_t number, uint32_t divisor)
36 {
37  raw_assert(divisor > 0);
38  if (UINT32_MAX - divisor + 1 < number)
39  return UINT32_MAX;
40 
41  number += divisor - 1;
42  number -= number % divisor;
43  return number;
44 }
45 
49 uint64_t
50 round_uint64_to_next_multiple_of(uint64_t number, uint64_t divisor)
51 {
52  raw_assert(divisor > 0);
53  if (UINT64_MAX - divisor + 1 < number)
54  return UINT64_MAX;
55  number += divisor - 1;
56  number -= number % divisor;
57  return number;
58 }
59 
60 /* Helper: return greatest common divisor of a,b */
61 static uint64_t
62 gcd64(uint64_t a, uint64_t b)
63 {
64  while (b) {
65  uint64_t t = b;
66  b = a % b;
67  a = t;
68  }
69  return a;
70 }
71 
72 /* Given a fraction *<b>numer</b> / *<b>denom</b>, simplify it.
73  * Requires that the denominator is greater than 0. */
74 void
75 simplify_fraction64(uint64_t *numer, uint64_t *denom)
76 {
77  raw_assert(denom);
78  uint64_t gcd = gcd64(*numer, *denom);
79  *numer /= gcd;
80  *denom /= gcd;
81 }
unsigned round_to_next_multiple_of(unsigned number, unsigned divisor)
Definition: muldiv.c:21
uint64_t round_uint64_to_next_multiple_of(uint64_t number, uint64_t divisor)
Definition: muldiv.c:50
Header for muldiv.c.
Headers for torerr.c.
uint32_t round_uint32_to_next_multiple_of(uint32_t number, uint32_t divisor)
Definition: muldiv.c:35