| 1 |
module imports.aXXXXX; |
| 2 |
|
| 3 |
auto min(A, B)(A a, B b) { return a < b ? a : b; } |
| 4 |
alias TypeTuple(T...) = T; |
| 5 |
|
| 6 |
private template CustomFloatParams(uint bits) |
| 7 |
{ |
| 8 |
static if (bits == 8) alias CustomFloatParams!( 4, 3) CustomFloatParams; |
| 9 |
static if (bits == 16) alias CustomFloatParams!(10, 5) CustomFloatParams; |
| 10 |
static if (bits == 32) alias CustomFloatParams!(23, 8) CustomFloatParams; |
| 11 |
static if (bits == 64) alias CustomFloatParams!(52, 11) CustomFloatParams; |
| 12 |
static if (bits == 80) alias CustomFloatParams!(64, 15) CustomFloatParams; |
| 13 |
} |
| 14 |
private template CustomFloatParams(uint precision, uint exponentWidth) |
| 15 |
{ |
| 16 |
alias TypeTuple!( |
| 17 |
precision, |
| 18 |
exponentWidth, |
| 19 |
) CustomFloatParams; |
| 20 |
} |
| 21 |
|
| 22 |
private union ToBinary(F) |
| 23 |
if (is(typeof(CustomFloatParams!(F.sizeof*8))) || is(F == real)) |
| 24 |
{ |
| 25 |
F set; |
| 26 |
|
| 27 |
// If on Linux or Mac, where 80-bit reals are padded, ignore the |
| 28 |
// padding. |
| 29 |
CustomFloat!(CustomFloatParams!(min(F.sizeof*8, 80))) get; |
| 30 |
|
| 31 |
// Convert F to the correct binary type. |
| 32 |
static typeof(get) opCall(F value) |
| 33 |
{ |
| 34 |
ToBinary r; |
| 35 |
r.set = value; |
| 36 |
return r.get; |
| 37 |
} |
| 38 |
alias get this; |
| 39 |
} |
| 40 |
|
| 41 |
struct CustomFloat(uint precision, uint exponentWidth) |
| 42 |
if ((1 + precision + exponentWidth) % 8 == 0 && precision + exponentWidth > 0) |
| 43 |
{ |
| 44 |
public: |
| 45 |
@property bool sign() { return 1; } |
| 46 |
@property void sign(bool) {} |
| 47 |
|
| 48 |
this(F)(F input) |
| 49 |
if (__traits(compiles, cast(real)input)) |
| 50 |
{ |
| 51 |
this = input; |
| 52 |
} |
| 53 |
|
| 54 |
void opAssign(F)(F input) |
| 55 |
if (__traits(compiles, cast(real)input)) |
| 56 |
{ |
| 57 |
static if (is(F == float) || is(F == double) || is(F == real)) |
| 58 |
auto value = ToBinary!(F)(input); |
| 59 |
else auto value = ToBinary!(real)(input); |
| 60 |
|
| 61 |
sign = value.sign; |
| 62 |
} |
| 63 |
|
| 64 |
@property F get(F)() |
| 65 |
if (is(F == float) || is(F == double) || is(F == real)) |
| 66 |
{ |
| 67 |
ToBinary result; |
| 68 |
return F.init; |
| 69 |
} |
| 70 |
|
| 71 |
T opCast(T)() |
| 72 |
if (__traits(compiles, get!T)) |
| 73 |
{ |
| 74 |
return get!T; |
| 75 |
} |
| 76 |
} |