diff --git a/taglib/toolkit/tbytevector.cpp b/taglib/toolkit/tbytevector.cpp index 55b66b3d..8663dd53 100644 --- a/taglib/toolkit/tbytevector.cpp +++ b/taglib/toolkit/tbytevector.cpp @@ -301,7 +301,7 @@ namespace { LittleEndian, BigEndian }; -} +} template inline T toNumber(const ByteVector &v, size_t offset) @@ -312,12 +312,7 @@ inline T toNumber(const ByteVector &v, size_t offset) static const bool swap = (ENDIAN == LittleEndian); #endif - if(offset + LENGTH > v.size()) { - debug("toNumber() -- offset is out of range. Returning 0."); - return 0; - } - - if(LENGTH >= sizeof(T)) { + if(LENGTH >= sizeof(T) && offset + LENGTH <= v.size()) { // Uses memcpy instead of reinterpret_cast to avoid an alignment exception. T tmp; ::memcpy(&tmp, v.data() + offset, sizeof(T)); @@ -328,9 +323,10 @@ inline T toNumber(const ByteVector &v, size_t offset) return tmp; } else { + const size_t length = std::min(LENGTH, v.size() - offset); T sum = 0; - for(size_t i = 0; i < LENGTH; i++) { - const size_t shift = (ENDIAN == LittleEndian ? i : LENGTH - 1 - i) * 8; + for(size_t i = 0; i < length; i++) { + const size_t shift = (ENDIAN == LittleEndian ? i : length - 1 - i) * 8; sum |= static_cast(static_cast(v[offset + i])) << shift; } diff --git a/tests/test_bytevector.cpp b/tests/test_bytevector.cpp index 2d31bfa9..555ae72b 100644 --- a/tests/test_bytevector.cpp +++ b/tests/test_bytevector.cpp @@ -163,10 +163,6 @@ public: CPPUNIT_ASSERT(n.toInt64LE(6) == -1268082884489200845ll); CPPUNIT_ASSERT(n.toInt64BE(4) == 2497865822736504285ll); - // Shows the message "toNumber() -- offset is out of range. Returning 0." 2 times. - CPPUNIT_ASSERT(n.toUInt32LE(13) == 0); - CPPUNIT_ASSERT(n.toUInt16BE(15) == 0); - CPPUNIT_ASSERT(ByteVector::fromUInt16LE(n.toInt16LE(5)) == n.mid(5, 2)); CPPUNIT_ASSERT(ByteVector::fromUInt16BE(n.toInt16BE(9)) == n.mid(9, 2)); CPPUNIT_ASSERT(ByteVector::fromUInt32LE(n.toUInt32LE(4)) == n.mid(4, 4));