aboutsummaryrefslogtreecommitdiff
path: root/src/liblzma/common/vli_reverse_decoder.c
blob: 68ca6a4205ceb36279bd75bf917530929a1574bb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
///////////////////////////////////////////////////////////////////////////////
//
/// \file       vli_reverse_decoder.c
/// \brief      Decodes variable-length integers starting at end of the buffer
//
//  Copyright (C) 2007 Lasse Collin
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
///////////////////////////////////////////////////////////////////////////////

#include "common.h"


extern LZMA_API lzma_ret
lzma_vli_reverse_decode(lzma_vli *vli, const uint8_t *in, size_t *in_size)
{
	if (*in_size == 0)
		return LZMA_BUF_ERROR;

	size_t i = *in_size - 1;
	*vli = in[i] & 0x7F;

	if (!(in[i] & 0x80)) {
		*in_size = i;
		return LZMA_OK;
	}

	const size_t end = *in_size > LZMA_VLI_BYTES_MAX
			? *in_size - LZMA_VLI_BYTES_MAX : 0;

	do {
		if (i-- == end) {
			if (*in_size < LZMA_VLI_BYTES_MAX)
				return LZMA_BUF_ERROR;

			return LZMA_DATA_ERROR;
		}

		*vli <<= 7;
		*vli = in[i] & 0x7F;

	} while (!(in[i] & 0x80));

	*in_size = i;
	return LZMA_OK;
}