On Sunday, 29 August 2021 at 15:57:18 UTC, Paul Backus wrote:
On Sunday, 29 August 2021 at 15:42:18 UTC, Ali Çehreli wrote:
Depending on the situation, you may want to use std.conv.to,
which does a value range check and throws an exception to
prevent an error:
byte foo(byte a, byte b) {
import std.conv : to;
return (a + b).to!byte;
}
void main() {
foo(42, 42); // Works
foo(100, 100); // Throws ConvOverflowException
}
I was going to suggest `std.experimental.checkedint` as an
alternative here, but it turns out that it does integer
promotion too--`Checked!byte + Checked!byte == Checked!int`.
This seems obviously wrong to me, but according to run.dlang.io
it's always worked that way.
(a.checked + b).get is int, but this works:
```d
import std.experimental.checkedint;
byte foo(byte a, byte b) {
auto c = a.checked;
c += b;
return c.get;
}
unittest {
import std.exception : assertThrown;
import core.exception : AssertError;
foo(42, 42);
assertThrown!AssertError(foo(100, 100));
}
```
... after Phobos is patched.
```
error: undefined identifier ‘Lhs’, did you mean alias ‘Rhs’?
```