1 ///////////////////////////////////////////////////////////////////////////////
3 /// \file vli_decoder.c
4 /// \brief Decodes variable-length integers
6 // Copyright (C) 2007-2008 Lasse Collin
8 // This library is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU Lesser General Public
10 // License as published by the Free Software Foundation; either
11 // version 2.1 of the License, or (at your option) any later version.
13 // This library is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 // Lesser General Public License for more details.
18 ///////////////////////////////////////////////////////////////////////////////
23 extern LZMA_API lzma_ret
24 lzma_vli_decode(lzma_vli *restrict vli, size_t *restrict vli_pos,
25 const uint8_t *restrict in, size_t *restrict in_pos,
28 // If we haven't been given vli_pos, work in single-call mode.
29 size_t vli_pos_internal = 0;
30 if (vli_pos == NULL) {
31 vli_pos = &vli_pos_internal;
34 // If there's no input, use LZMA_DATA_ERROR. This way it is
35 // easy to decode VLIs from buffers that have known size,
36 // and get the correct error code in case the buffer is
38 if (*in_pos >= in_size)
39 return LZMA_DATA_ERROR;
42 // Initialize *vli when starting to decode a new integer.
46 // Validate the arguments.
47 if (*vli_pos >= LZMA_VLI_BYTES_MAX
48 || (*vli >> (*vli_pos * 7)) != 0)
49 return LZMA_PROG_ERROR;;
51 if (*in_pos >= in_size)
52 return LZMA_BUF_ERROR;
56 // Read the next byte.
57 *vli |= (lzma_vli)(in[*in_pos] & 0x7F) << (*vli_pos * 7);
60 // Check if this is the last byte of a multibyte integer.
61 if (!(in[*in_pos] & 0x80)) {
62 // We don't allow using variable-length integers as
63 // padding i.e. the encoding must use the most the
65 if (in[(*in_pos)++] == 0x00 && *vli_pos > 1)
66 return LZMA_DATA_ERROR;
68 return vli_pos == &vli_pos_internal
69 ? LZMA_OK : LZMA_STREAM_END;
74 // There is at least one more byte coming. If we have already
75 // read maximum number of bytes, the integer is considered
78 // If we need bigger integers in future, old versions liblzma
79 // will confusingly indicate the file being corrupt istead of
80 // unsupported. I suppose it's still better this way, because
81 // in the foreseeable future (writing this in 2008) the only
82 // reason why files would appear having over 63-bit integers
83 // is that the files are simply corrupt.
84 if (*vli_pos == LZMA_VLI_BYTES_MAX)
85 return LZMA_DATA_ERROR;
87 } while (*in_pos < in_size);
89 return vli_pos == &vli_pos_internal ? LZMA_DATA_ERROR : LZMA_OK;