feexceptErsatz.H
Go to the documentation of this file.
1 // ============================================================================
2 // Generic handling of floating point exceptions
3 //
4 // 2018 Alexey Matveichev
5 // ----------------------------------------------------------------------------
6 //
7 // Original Author
8 // David N. Williams
9 //
10 // License
11 // Public Domain
12 //
13 // Description
14 // Alternate, nondefault handling of IEEE 754 floating-point exceptions
15 // in OS X, based on the GNU functions feenableexcept(), fedisableeexcept()
16 // and fegetexcept() [in libm]
17 //
18 // http://www-personal.umich.edu/~williams/archive/computation/fe-handling-example.c
19 // ============================================================================
20 
21 #ifndef feexceptErsatz_H
22 #define feexceptErsatz_H
23 
24 #ifdef __APPLE__
25 #include <fenv.h>
26 
27 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
28 
29 inline int feenableexcept(unsigned int excepts)
30 {
31  static fenv_t fenv;
32  unsigned int new_excepts = excepts & FE_ALL_EXCEPT;
33  unsigned int old_excepts; // previous masks
34 
35  if (fegetenv(&fenv))
36  {
37  return -1;
38  }
39  old_excepts = fenv.__control & FE_ALL_EXCEPT;
40 
41  // unmask
42  fenv.__control &= ~new_excepts;
43  fenv.__mxcsr &= ~(new_excepts << 7);
44 
45  return fesetenv(&fenv) ? -1 : old_excepts;
46 }
47 
48 
49 inline int fedisableexcept(unsigned int excepts)
50 {
51  static fenv_t fenv;
52  unsigned int new_excepts = excepts & FE_ALL_EXCEPT;
53  unsigned int old_excepts; // all previous masks
54 
55  if (fegetenv(&fenv))
56  {
57  return -1;
58  }
59 
60  old_excepts = fenv.__control & FE_ALL_EXCEPT;
61 
62  // mask
63  fenv.__control |= new_excepts;
64  fenv.__mxcsr |= new_excepts << 7;
65 
66  return fesetenv(&fenv) ? -1 : old_excepts;
67 }
68 
69 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
70 
71 #endif // __APPLE__
72 #endif
73 
74 // ************************************************************************* //