msgpack-perl icon indicating copy to clipboard operation
msgpack-perl copied to clipboard

Potential issue in casting numbers

Open akotlar opened this issue 7 years ago • 2 comments

I've noticed some odd behavior, which may simply be the way Perl works, but which could be useful for msgpack-perl to take into account.

Also, once again I would ask that we have some handling for lower-precision floats. It doesn't matter that Perl doesn't separate a double from a float, what matters is how much space the msgpack representation takes. Spending 9 bytes for 1.0 is a waste.

use Data::MessagePack;
use Test::More;
use Scalar::Util qw/looks_like_number/;

sub toNumber {
  if (!looks_like_number($_[0])) {
    return $_[0];
  }

  return $_[0] + 0;
}

my $mp = Data::MessagePack->new();
$mp->prefer_integer();

my $numThatShouldBeInt = "-1.000000";

$converted = toNumber($numThatShouldBeInt);

$packed = $mp->pack($converted);
ok(length($packed) == 1, "Perl does something bizarre when returning numbers from subs");

# Something is very weird
$packed = $mp->pack($numThatShouldBeInt+ 0);
ok(length($packed) == 9, "The string $numThatShouldBeInt takes 9 bytes in msgpack when cast to number, as expected");

# Note that this doesn't occur with a positive number
$packed = $mp->pack("1.000000" + 0);
ok(length($packed) == 9, "The string 1.000000 takes 9 bytes in msgpack when cast to number, as expected");


$packed = $mp->pack(CORE::int($numThatShouldBeInt));
ok(length($packed) == 1, "The string $numThatShouldBeInt takes 1 bytes when cast as int, as expected");

akotlar avatar Feb 09 '17 18:02 akotlar