src
u32lim.h
Go to the documentation of this file.
1 #ifndef _RE2C_UTIL_U32LIM_
2 #define _RE2C_UTIL_U32LIM_
3 
4 #include "src/util/c99_stdint.h"
5 
6 // uint32_t truncated to LIMIT
7 // any overflow (either result of a binary operation
8 // or conversion from another type) results in LIMIT
9 // LIMIT is a fixpoint
10 template<uint32_t LIMIT>
11 class u32lim_t
12 {
13  uint32_t value;
14  explicit u32lim_t (uint32_t x)
15  : value (x < LIMIT ? x : LIMIT)
16  {}
17  explicit u32lim_t (uint64_t x)
18  : value (x < LIMIT ? static_cast<uint32_t> (x) : LIMIT)
19  {}
20 
21 public:
22  // implicit conversion is forbidden, because
23  // operands should be converted before operation:
24  // uint32_t x, y; ... u32lim_t z = x + y;
25  // will result in 32-bit addition and may overflow
26  // Don't export overloaded constructors: it breaks OS X builds
27  // ('size_t' causes resolution ambiguity)
28  static u32lim_t from32 (uint32_t x) { return u32lim_t(x); }
29  static u32lim_t from64 (uint64_t x) { return u32lim_t(x); }
30 
31  static u32lim_t limit ()
32  {
33  return u32lim_t (LIMIT);
34  }
35 
36  uint32_t uint32 () const
37  {
38  return value;
39  }
40 
41  bool overflow () const
42  {
43  return value == LIMIT;
44  }
45 
47  {
48  const uint64_t z
49  = static_cast<uint64_t> (x.value)
50  + static_cast<uint64_t> (y.value);
51  return z < LIMIT
52  ? u32lim_t (z)
53  : u32lim_t (LIMIT);
54  }
55 
57  {
58  const uint64_t z
59  = static_cast<uint64_t> (x.value)
60  * static_cast<uint64_t> (y.value);
61  return z < LIMIT
62  ? u32lim_t (z)
63  : u32lim_t (LIMIT);
64  }
65 
66  friend bool operator < (u32lim_t x, u32lim_t y)
67  {
68  return x.value < y.value;
69  }
70 };
71 
72 #endif // _RE2C_UTIL_U32LIM_
static u32lim_t from32(uint32_t x)
Definition: u32lim.h:28
friend bool operator<(u32lim_t x, u32lim_t y)
Definition: u32lim.h:66
static u32lim_t limit()
Definition: u32lim.h:31
static u32lim_t from64(uint64_t x)
Definition: u32lim.h:29
friend u32lim_t operator+(u32lim_t x, u32lim_t y)
Definition: u32lim.h:46
uint32_t uint32() const
Definition: u32lim.h:36
bool overflow() const
Definition: u32lim.h:41
friend u32lim_t operator*(u32lim_t x, u32lim_t y)
Definition: u32lim.h:56