NERDVANA has asked for the wisdom of the Perl Monks concerning the following question:

I occasionally want to publish perl modules that require 64-bit integers and "pack 'Q'" support. The modules can be expanded to work on old and 32-bit perls by using BigInt, but I don't want to encumber the main users of the module with that performance hit for such rarely encountered environments. I'm looking for a generic toolkit of functions to solve this, and if it doesn't exist, I'm looking for a good CPAN name to publish mine.

For example, here is the shim I made to support "pack 'Q'" for 32-bit perl and the test I use to usually avoid needing it.

I also want to be able to declare 64-bit constants, for which I created this: (not yet published)

sub _int64_native { $_[0] =~ /^(-?)0x(.*)/? hex($2)*($1? -1 : 1) : 0+$_[0] } sub _int64_bigint { Math::BigInt->new($_[0]) } # Can scalars hold 64-bit ints natively? if ((0x7FFFFFFE << 31) > 0 && (0x7FFFFFFE << 63) == 0) { *int64= \&_int64_native; } else { *int64= \&_int64_bigint; }

Which I can use like this:

int64('-0x10000000000');

Before I go too far here, is there a CPAN module I'm overlooking?

If not, I'd like to make one. What should I name it?

Replies are listed 'Best First'.
Re: Supporting 64-bit ints on 32-bit perl
by hippo (Archbishop) on Apr 19, 2023 at 22:40 UTC
    Before I go too far here, is there a CPAN module I'm overlooking?

    There's Math::Int64 which has the Math::Int64::native_if_available pragma which sounds like it might be similar. I've not used it though so may have misunderstood either it or indeed your post.


    🦛

      Well it was close. I could use it, but it is a non-core XS module that doesn't really provide much advantage over Math::BigInt. I was more looking for something that would use Math::BigInt if (and only if) it was needed.

      So for example, a name I might choose for my module could be "Math::MaybeBig" or "Scalar::Compat64" or something. And, maybe providing 'pack' for old perls doesn't belong in the same module as compatibility shims for modern 32-bit perl?

        but it is a non-core XS module that doesn't really provide much advantage over Math::BigInt

        Well, Math::Int64 does provide better performance than Math::BigInt.
        But if you're looking for something that's already part of perl's core, then I can't think of anything other than Math::BigInt.

        I take it you're aware that most 32-bit perls (especially the modern ones) have 64-bit IV/UVs and already support pack's "Q" template.
        In any case, you'll also find 32-bit builds whose IV/UVs are only 32-bits ... and I understand these are the builds that you're wanting to cater to.
        You distinguish between the 2 different configurations by checking to see whether $Config{ivsize} is 4 or 8. (Sorry ... you probably already know all about that.)

        Cheers,
        Rob