Thrift-1171: Perl write/readDouble assumes little-endian platform
authorJake Farrell <jfarrell@apache.org>
Fri, 3 Jun 2011 17:03:00 +0000 (17:03 +0000)
committerJake Farrell <jfarrell@apache.org>
Fri, 3 Jun 2011 17:03:00 +0000 (17:03 +0000)
Client: perl
Patch: Andy Grundman

The code for handling doubles uses pack 'd' (pack to native byte order) and then reverses the bytes. This works on little-endian systems but will produce backwards data on big-endian systems.

git-svn-id: https://svn.apache.org/repos/asf/thrift/trunk@1131110 13f79535-47bb-0310-9956-ffa450edef68

lib/perl/lib/Thrift/BinaryProtocol.pm

index 64d7958..c638ead 100644 (file)
@@ -38,6 +38,7 @@ use base('Thrift::Protocol');
 
 use constant VERSION_MASK   => 0xffff0000;
 use constant VERSION_1      => 0x80010000;
+use constant IS_BIG_ENDIAN  => unpack("h*", pack("s", 1)) =~ /01/;
 
 sub new
 {
@@ -211,7 +212,12 @@ sub writeDouble
     my $value= shift;
 
     my $data = pack('d', $value);
-    $self->{trans}->write(scalar reverse($data), 8);
+    if (IS_BIG_ENDIAN) {
+      $self->{trans}->write($data, 8);
+    }
+    else {
+      $self->{trans}->write(scalar reverse($data), 8);
+    }
     return 8;
 }
 
@@ -434,7 +440,14 @@ sub readDouble
     my $self  = shift;
     my $value = shift;
 
-    my $data = scalar reverse($self->{trans}->readAll(8));
+    my $data;
+    if (IS_BIG_ENDIAN) {
+      $data = $self->{trans}->readAll(8);
+    }
+    else {
+      $data = scalar reverse($self->{trans}->readAll(8));
+    }
+    
     my @arr = unpack('d', $data);
 
     $$value = $arr[0];