Write len bytes from buf to file. Return the number of bytes written. If the returned value is less than len, then there was an error. */
| 171 | /* Write len bytes from buf to file. Return the number of bytes written. If |
| 172 | the returned value is less than len, then there was an error. */ |
| 173 | local z_size_t gz_write(gz_statep state, voidpc buf, z_size_t len) { |
| 174 | z_size_t put = len; |
| 175 | |
| 176 | /* if len is zero, avoid unnecessary operations */ |
| 177 | if (len == 0) |
| 178 | return 0; |
| 179 | |
| 180 | /* allocate memory if this is the first time through */ |
| 181 | if (state->size == 0 && gz_init(state) == -1) |
| 182 | return 0; |
| 183 | |
| 184 | /* check for seek request */ |
| 185 | if (state->seek) { |
| 186 | state->seek = 0; |
| 187 | if (gz_zero(state, state->skip) == -1) |
| 188 | return 0; |
| 189 | } |
| 190 | |
| 191 | /* for small len, copy to input buffer, otherwise compress directly */ |
| 192 | if (len < state->size) { |
| 193 | /* copy to input buffer, compress when full */ |
| 194 | do { |
| 195 | unsigned have, copy; |
| 196 | |
| 197 | if (state->strm.avail_in == 0) |
| 198 | state->strm.next_in = state->in; |
| 199 | have = (unsigned)((state->strm.next_in + state->strm.avail_in) - |
| 200 | state->in); |
| 201 | copy = state->size - have; |
| 202 | if (copy > len) |
| 203 | copy = (unsigned)len; |
| 204 | memcpy(state->in + have, buf, copy); |
| 205 | state->strm.avail_in += copy; |
| 206 | state->x.pos += copy; |
| 207 | buf = (const char *)buf + copy; |
| 208 | len -= copy; |
| 209 | if (len && gz_comp(state, Z_NO_FLUSH) == -1) |
| 210 | return 0; |
| 211 | } while (len); |
| 212 | } |
| 213 | else { |
| 214 | /* consume whatever's left in the input buffer */ |
| 215 | if (state->strm.avail_in && gz_comp(state, Z_NO_FLUSH) == -1) |
| 216 | return 0; |
| 217 | |
| 218 | /* directly compress user buffer to file */ |
| 219 | state->strm.next_in = (z_const Bytef *)buf; |
| 220 | do { |
| 221 | unsigned n = (unsigned)-1; |
| 222 | if (n > len) |
| 223 | n = (unsigned)len; |
| 224 | state->strm.avail_in = n; |
| 225 | state->x.pos += n; |
| 226 | if (gz_comp(state, Z_NO_FLUSH) == -1) |
| 227 | return 0; |
| 228 | len -= n; |
| 229 | } while (len); |
| 230 | } |