mhogrefe / malachite

An arbitrary-precision arithmetic library for Rust.
GNU Lesser General Public License v3.0
453 stars 18 forks source link

Implement constant conversion for integers and naturals #28

Closed novafacing closed 1 year ago

novafacing commented 1 year ago

This is just a first pass at the idea in #16. Basically, it enables you to write:

use malachite::{platform::Limb, Integer, Natural};
const SOME_POS_VAL: Integer = Integer::from_sign_and_abs_unchecked(true, Natural::from_limb(65537));
const SOME_NEG_VAL: Integer = Integer::from_sign_and_abs_unchecked(false, Natural::from_limb(65537));
assert_eq!(SOME_POS_VAL, 65537);
assert_eq!(SOME_NEG_VAL, -65537);

It's not very complete or ergonomic, but it does work for my use case at least :)

novafacing commented 1 year ago

A couple key annoyances with doing it this way...const traits and const fn in traits are still unstable, so you can't do:

const trait ConstFrom<T> {
    const fn from(val: T) -> Self;
}

IMHO, adding a simple way to do it now (it's a small code change) is good bang for the buck while Rust team works on the hard stuff :)

mhogrefe commented 1 year ago

Thanks for your change! I had already implemented it, and just pushed it out in 0.4.2. It's not exactly the same as your PR. I don't include conversion from Naturals to Integers (but I might include it in the future) and nothing is unchecked; I don't want Malachite to include unchecked functions.

novafacing commented 1 year ago

Oh fair enough! I hadn't even noticed that it was already implemented :) thanks for doing this, yours is certainly superior.

mhogrefe commented 1 year ago

To clarify, I only pushed it today, so you had no way of knowing!