|
13 | 13 | #include "msgpack/v1/zbuffer_decl.hpp" |
14 | 14 | #include "msgpack/assert.hpp" |
15 | 15 |
|
| 16 | +#include <limits> |
16 | 17 | #include <stdexcept> |
17 | 18 | #include <zlib.h> |
18 | 19 |
|
@@ -51,19 +52,26 @@ class zbuffer { |
51 | 52 | if (!buf) return; |
52 | 53 |
|
53 | 54 | m_stream.next_in = reinterpret_cast<Bytef*>(const_cast<char*>(buf)); |
54 | | - m_stream.avail_in = static_cast<uInt>(len); |
55 | 55 |
|
56 | | - while(m_stream.avail_in > 0) { |
57 | | - if(m_stream.avail_out < MSGPACK_ZBUFFER_RESERVE_SIZE) { |
58 | | - if(!expand()) { |
59 | | - throw std::bad_alloc(); |
| 56 | + // avail_in is narrower than size_t on 64-bit platforms |
| 57 | + const size_t max_avail = std::numeric_limits<uInt>::max(); |
| 58 | + do { |
| 59 | + uInt chunk = (len > max_avail) ? std::numeric_limits<uInt>::max() : static_cast<uInt>(len); |
| 60 | + m_stream.avail_in = chunk; |
| 61 | + len -= chunk; |
| 62 | + |
| 63 | + while(m_stream.avail_in > 0) { |
| 64 | + if(m_stream.avail_out < MSGPACK_ZBUFFER_RESERVE_SIZE) { |
| 65 | + if(!expand()) { |
| 66 | + throw std::bad_alloc(); |
| 67 | + } |
60 | 68 | } |
61 | | - } |
62 | 69 |
|
63 | | - if(deflate(&m_stream, Z_NO_FLUSH) != Z_OK) { |
64 | | - throw std::bad_alloc(); |
| 70 | + if(deflate(&m_stream, Z_NO_FLUSH) != Z_OK) { |
| 71 | + throw std::bad_alloc(); |
| 72 | + } |
65 | 73 | } |
66 | | - } |
| 74 | + } while(len > 0); |
67 | 75 | } |
68 | 76 |
|
69 | 77 | char* flush() |
@@ -139,9 +147,13 @@ class zbuffer { |
139 | 147 | return false; |
140 | 148 | } |
141 | 149 |
|
| 150 | + const size_t avail = nsize - used; |
| 151 | + const size_t max_avail = std::numeric_limits<uInt>::max(); |
| 152 | + |
142 | 153 | m_data = tmp; |
143 | 154 | m_stream.next_out = reinterpret_cast<Bytef*>(tmp + used); |
144 | | - m_stream.avail_out = static_cast<uInt>(nsize - used); |
| 155 | + // avail_out is narrower than size_t on 64-bit platforms |
| 156 | + m_stream.avail_out = (avail > max_avail) ? std::numeric_limits<uInt>::max() : static_cast<uInt>(avail); |
145 | 157 |
|
146 | 158 | return true; |
147 | 159 | } |
|
0 commit comments