[rust-dev] Appeal for CORRECT, capable, future-proof math, pre-1.0
matthieu.monrocq at gmail.com
Tue Jan 14 11:35:07 PST 2014
On Tue, Jan 14, 2014 at 5:56 AM, comex <comexk at gmail.com> wrote:
> On Mon, Jan 13, 2014 at 4:06 PM, Tobias Müller <troplin at bluewin.ch> wrote:
> > int<l1,u1> + int<l2,u2> = int<l1+l2,u1+u2>
> > ...
> > If the result does not fit into an int the compiler throws an error.
> > To resolve an error, you can:
> > - annotate the operands with appropriate bounds
> > - use a bigger type for the operation and check the result.
> I remember wondering whether this type of solution would be feasible
> or too much of a hassle in practice. As I see it, many values which
> might be arithmetic operands are sizes or counts, and really ought to
> be size_t sized, and any mutable variable which is operated on in a
> loop can't be bounded with a lot more complexity, so it might lean
> toward the latter.
It's indeed a risk that such an annotation might be too annoying
(especially since addition is actually quite easy, the bounds grow faster
on multiplication)... but on the other hand, you do need dynamic checks
anyway to verify that the value of type "u32<0, 4_294_967_295>" won't
overflow if you multiply it by "3".
So as I see it, you can do either of: "let result = to<u32<0,
* 3;" OR "let result = to<u32>(to<u64>(size) * 3);".
Of course, compared to "let result = size * 3;" it seems the annotation tax
is high, however the latter may overflow (and wrap, certainly, but that is
still a bogus answer in most languages).
So, maybe it one could just use a couple primitives:
- wrapping integers (for hashes)
- saturating integers (useful for colors)
- fail-on-overflow integers
- compile-time range-checked integers
u32w, u32s, u32o and u32c ?
Note: as far as I know Rust *plans* on having non-type template parameters
but does not have them yet, so the compile-time range-checked integers are
out of question for now.
Note 2: having all those in the core language would be unnecessary if the
syntax 3u32c (<number><type>) was sugar coating for u32c::new(3) like C++
suffix literals; with "new" using some "default" integer type (I vote for
the fail-on-overflow, it catches the bugs) and the compiler verifying that
the "raw" number can be expressed in that "default" integer type perfectly.
Then libraries could add the other modes.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Rust-dev