THRIFT-2757: py - checkIntegerLimits optimized
Client: Python
diff --git a/lib/py/src/protocol/TProtocol.py b/lib/py/src/protocol/TProtocol.py
index bd69067..e8ee799 100644
--- a/lib/py/src/protocol/TProtocol.py
+++ b/lib/py/src/protocol/TProtocol.py
@@ -403,11 +403,18 @@
writer(val)
def checkIntegerLimits(i, bits):
- lo = -(2 ** (bits - 1))
- hi = 2 ** (bits - 1) - 1
- if not lo <= i <= hi:
+ if bits == 8 and (n < -128 or n > 127):
raise TProtocolException(TProtocolException.INVALID_DATA,
- "i%d value: %d is outside range: [%d, %d]" % (bits, i, lo, hi))
+ "i8 requires -128 <= number <= 127")
+ elif bits == 16 and (n < -32768 or n > 32767):
+ raise TProtocolException(TProtocolException.INVALID_DATA,
+ "i16 requires -32768 <= number <= 32767")
+ elif bits == 32 and (n < -2147483648 or n > 2147483647):
+ raise TProtocolException(TProtocolException.INVALID_DATA,
+ "i32 requires -2147483648 <= number <= 2147483647")
+ elif bits == 64 and (n < -9223372036854775808 or n > 9223372036854775807):
+ raise TProtocolException(TProtocolException.INVALID_DATA,
+ "i64 requires -9223372036854775808 <= number <= 9223372036854775807")
class TProtocolFactory:
def getProtocol(self, trans):
diff --git a/test/py/SerializationTest.py b/test/py/SerializationTest.py
index 946f848..40a52e6 100755
--- a/test/py/SerializationTest.py
+++ b/test/py/SerializationTest.py
@@ -267,6 +267,16 @@
rep = repr(self.compact_struct)
self.assertTrue(len(rep) > 0)
+ def testIntegerLimits(self):
+ bad_values = [CompactProtoTestStruct(a_byte=128), CompactProtoTestStruct(a_byte=-129),
+ CompactProtoTestStruct(a_i16=32768), CompactProtoTestStruct(a_i16=-32769),
+ CompactProtoTestStruct(a_i32=2147483648), CompactProtoTestStruct(a_i32=-2147483649),
+ CompactProtoTestStruct(a_i64=9223372036854775808), CompactProtoTestStruct(a_i64=-9223372036854775809)
+ ]
+
+ for value in bad_values:
+ self.assertRaises(Exception, self._serialize, value)
+
class NormalBinaryTest(AbstractTest):
protocol_factory = TBinaryProtocol.TBinaryProtocolFactory()