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;
31 vli_pos = &vli_pos_internal;
33 // Initialize *vli when starting to decode a new integer.
37 // Validate the arguments.
38 if (*vli_pos >= LZMA_VLI_BYTES_MAX || *in_pos >= in_size
39 || (*vli >> (*vli_pos * 7)) != 0)
40 return LZMA_PROG_ERROR;;
43 // Read the next byte.
44 *vli |= (lzma_vli)(in[*in_pos] & 0x7F) << (*vli_pos * 7);
47 // Check if this is the last byte of a multibyte integer.
48 if (!(in[*in_pos] & 0x80)) {
49 // We don't allow using variable-length integers as
50 // padding i.e. the encoding must use the most the
52 if (in[(*in_pos)++] == 0x00 && *vli_pos > 1)
53 return LZMA_DATA_ERROR;
55 return vli_pos == &vli_pos_internal
56 ? LZMA_OK : LZMA_STREAM_END;
61 // There is at least one more byte coming. If we have already
62 // read maximum number of bytes, the integer is considered
65 // If we need bigger integers in future, old versions liblzma
66 // will confusingly indicate the file being corrupt istead of
67 // unsupported. I suppose it's still better this way, because
68 // in the foreseeable future (writing this in 2008) the only
69 // reason why files would appear having over 63-bit integers
70 // is that the files are simply corrupt.
71 if (*vli_pos == LZMA_VLI_BYTES_MAX)
72 return LZMA_DATA_ERROR;
74 } while (*in_pos < in_size);
76 return vli_pos == &vli_pos_internal ? LZMA_DATA_ERROR : LZMA_OK;