1
/* -*- mode: C; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2
// vim: expandtab:ts=8:sw=4:softtabstop=4:
3
///////////////////////////////////////////////////////////////////////////////
5
/// \file vli_decoder.c
6
/// \brief Decodes variable-length integers
8
// Author: Lasse Collin
10
// This file has been put into the public domain.
11
// You can do whatever you want with this file.
13
///////////////////////////////////////////////////////////////////////////////
18
extern LZMA_API(lzma_ret)
19
lzma_vli_decode(lzma_vli *restrict vli, size_t *vli_pos,
20
const uint8_t *restrict in, size_t *restrict in_pos,
23
// If we haven't been given vli_pos, work in single-call mode.
24
size_t vli_pos_internal = 0;
25
if (vli_pos == NULL) {
26
vli_pos = &vli_pos_internal;
29
// If there's no input, use LZMA_DATA_ERROR. This way it is
30
// easy to decode VLIs from buffers that have known size,
31
// and get the correct error code in case the buffer is
33
if (*in_pos >= in_size)
34
return LZMA_DATA_ERROR;
37
// Initialize *vli when starting to decode a new integer.
41
// Validate the arguments.
42
if (*vli_pos >= LZMA_VLI_BYTES_MAX
43
|| (*vli >> (*vli_pos * 7)) != 0)
44
return LZMA_PROG_ERROR;;
46
if (*in_pos >= in_size)
47
return LZMA_BUF_ERROR;
51
// Read the next byte. Use a temporary variable so that we
52
// can update *in_pos immediatelly.
53
const uint8_t byte = in[*in_pos];
56
// Add the newly read byte to *vli.
57
*vli += (lzma_vli)(byte & 0x7F) << (*vli_pos * 7);
60
// Check if this is the last byte of a multibyte integer.
61
if ((byte & 0x80) == 0) {
62
// We don't allow using variable-length integers as
63
// padding i.e. the encoding must use the most the
65
if (byte == 0x00 && *vli_pos > 1)
66
return LZMA_DATA_ERROR;
68
return vli_pos == &vli_pos_internal
69
? LZMA_OK : LZMA_STREAM_END;
72
// There is at least one more byte coming. If we have already
73
// read maximum number of bytes, the integer is considered
76
// If we need bigger integers in future, old versions liblzma
77
// will confusingly indicate the file being corrupt istead of
78
// unsupported. I suppose it's still better this way, because
79
// in the foreseeable future (writing this in 2008) the only
80
// reason why files would appear having over 63-bit integers
81
// is that the files are simply corrupt.
82
if (*vli_pos == LZMA_VLI_BYTES_MAX)
83
return LZMA_DATA_ERROR;
85
} while (*in_pos < in_size);
87
return vli_pos == &vli_pos_internal ? LZMA_DATA_ERROR : LZMA_OK;