Boost logo

Boost :

Subject: Re: [boost] a safe integer library
From: Robert Ramey (ramey_at_[hidden])
Date: 2016-01-12 15:50:59


On 1/12/16 11:31 AM, Brook Milligan wrote:
> On Jan 12, 2016, at 12:05 PM, Robert Ramey <ramey_at_[hidden]> wrote:
> int x = { /* something possibly large */ };
> safe_int<int8_t> y = x; // clearly this requires a run-time check and may fail
>
> Instead, I would like to be able to, for example, branch; something like this:
>
> int x = { /* something possibly large */ };
> if (is_convertible<safe_int<int8_t>>(x) {
> do_something_with small values();
> } else {
> do_something_with_large_values();
> }

It's going to be a little trickier than that. One basic problem is that
there more than two cases, yes, no, have to check at runtime.

Turns out that similar facilty is used by the library and is available
to users. Downside is there is no example/tutorial so one would
actually have to read the documentation. The general procedure would be:

// create an interval from the safe type
using namespace boost::numeric;
using interval_t = safe_integer<std::int8_t>>;
interval<std::int8_t> i = {
        std::numeric::limits<interval_t>::min(),
        std::numeric::limits<interval_t>::max()
};
... similar with j

now you could use the operations in the interval type

i < j
i.includes(j)
...

the above return a tribool

intersection(i, j)
add<std::int8_t>(i, j)
...

The above return a "checked_result<interval_t>" - which is decribed in
another part of the documentation. Basically its similar to "optional"
so it either returns a valid new interval or an error condition which
you can test for.

I believe this might be able to provide what you're looking for. If all
you're looking for is a runtime solution, the boost/numerics/interval
arithmetic library might be a better choice. Works for floating point
as well - not just integers.

Note that all of the above is constexpr so you can do it at compile time
and plug the result into a compile time expression,

Robert Ramey

> In some cases, e.g., if the positions of the int and safe_int<> were reversed above, no runtime checking is required but the appropriate branch is executed. In others, such as actually illustrated, runtime checking is required just as it would be in an assignment.
>
> In either case, however, the result leverages the type system you have developed to inquire about the relative ranges and values in (I feel) an expressive and compact way.
>
> Is this possible currently? Can it be incorporated given the design of the library? Don’t you already have the internals in place to do something equivalent that could be exposed in fashion like this?
>
> I hope that is clearer. Thanks again.
>
> Cheers,
> Brook
>
>
> _______________________________________________
> Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost
>


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk