Skip to content

Commit 7efbb97

Browse files
authored
Fix Issue 24142 - Allow casting Int128 to integral and floating types (#8810)
1 parent d7e79f0 commit 7efbb97

File tree

1 file changed

+45
-1
lines changed

1 file changed

+45
-1
lines changed

std/int128.d

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,14 +147,58 @@ public struct Int128
147147

148148
/** Support casting to a bool
149149
* Params: T = bool
150-
* Returns: boolean result
150+
* Returns: true if value is not zero
151151
*/
152152
bool opCast(T : bool)() const
153153
{
154154
return tst(this.data);
155155
}
156156
} // @safe pure nothrow @nogc
157157

158+
/** Support casting to an integral type
159+
* Params: T = integral type
160+
* Returns: low bits of value reinterpreted as T
161+
*/
162+
T opCast(T : long)() const
163+
if (is(byte : T))
164+
{
165+
return cast(T) this.data.lo;
166+
}
167+
168+
///
169+
@safe unittest
170+
{
171+
const Int128 a = Int128(0xffff_ffff_ffff_ffffL, 0x0123_4567_89ab_cdefL);
172+
assert(cast(long) a == 0x0123_4567_89ab_cdefL);
173+
assert(cast(int) a == 0x89ab_cdef);
174+
assert(cast(byte) a == cast(byte) 0xef);
175+
}
176+
177+
/** Support casting to floating point type
178+
* Params: T = floating point type
179+
* Returns: value cast to floating point with environment-dependent
180+
* rounding if the value is not exactly representable
181+
*/
182+
T opCast(T : real)() const
183+
{
184+
import core.math : ldexp;
185+
if (cast(long) this.data.hi >= 0)
186+
return ldexp(cast(T) this.data.hi, 64) + this.data.lo;
187+
else
188+
{
189+
const absData = neg(this.data);
190+
return -ldexp(cast(T) absData.hi, 64) - absData.lo;
191+
}
192+
}
193+
194+
///
195+
@safe unittest
196+
{
197+
const Int128 a = Int128(-1L << 60);
198+
assert(cast(double) a == -(2.0 ^^ 60));
199+
assert(cast(double) (a * a) == 2.0 ^^ 120);
200+
}
201+
158202
/** Support binary arithmetic operators + - * / % & | ^ << >> >>>
159203
* Params:
160204
* op = one of the arithmetic binary operators

0 commit comments

Comments
 (0)