1
/* -*- mode: C; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2
// vim: expandtab:ts=8:sw=4:softtabstop=4:
3
///////////////////////////////////////////////////////////////////////////////
5
/// \file vli_encoder.c
6
/// \brief Encodes 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_encode(lzma_vli vli, size_t *vli_pos,
20
uint8_t *restrict out, size_t *restrict out_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;
28
// In single-call mode, we expect that the caller has
29
// reserved enough output space.
30
if (*out_pos >= out_size)
31
return LZMA_PROG_ERROR;
33
// This never happens when we are called by liblzma, but
34
// may happen if called directly from an application.
35
if (*out_pos >= out_size)
36
return LZMA_BUF_ERROR;
39
// Validate the arguments.
40
if (*vli_pos >= LZMA_VLI_BYTES_MAX || vli > LZMA_VLI_MAX)
41
return LZMA_PROG_ERROR;
43
// Shift vli so that the next bits to encode are the lowest. In
44
// single-call mode this never changes vli since *vli_pos is zero.
47
// Write the non-last bytes in a loop.
49
// We don't need *vli_pos during this function call anymore,
50
// but update it here so that it is ready if we need to
51
// return before the whole integer has been decoded.
53
assert(*vli_pos < LZMA_VLI_BYTES_MAX);
55
// Write the next byte.
56
out[*out_pos] = (uint8_t)(vli) | 0x80;
59
if (++*out_pos == out_size)
60
return vli_pos == &vli_pos_internal
61
? LZMA_PROG_ERROR : LZMA_OK;
64
// Write the last byte.
65
out[*out_pos] = (uint8_t)(vli);
69
return vli_pos == &vli_pos_internal ? LZMA_OK : LZMA_STREAM_END;