1 // SPDX-License-Identifier: 0BSD
3 ///////////////////////////////////////////////////////////////////////////////
5 /// \file vli_encoder.c
6 /// \brief Encodes variable-length integers
8 // Author: Lasse Collin
10 ///////////////////////////////////////////////////////////////////////////////
15 extern LZMA_API(lzma_ret
)
16 lzma_vli_encode(lzma_vli vli
, size_t *vli_pos
,
17 uint8_t *restrict out
, size_t *restrict out_pos
,
20 // If we haven't been given vli_pos, work in single-call mode.
21 size_t vli_pos_internal
= 0;
22 if (vli_pos
== NULL
) {
23 vli_pos
= &vli_pos_internal
;
25 // In single-call mode, we expect that the caller has
26 // reserved enough output space.
27 if (*out_pos
>= out_size
)
28 return LZMA_PROG_ERROR
;
30 // This never happens when we are called by liblzma, but
31 // may happen if called directly from an application.
32 if (*out_pos
>= out_size
)
33 return LZMA_BUF_ERROR
;
36 // Validate the arguments.
37 if (*vli_pos
>= LZMA_VLI_BYTES_MAX
|| vli
> LZMA_VLI_MAX
)
38 return LZMA_PROG_ERROR
;
40 // Shift vli so that the next bits to encode are the lowest. In
41 // single-call mode this never changes vli since *vli_pos is zero.
44 // Write the non-last bytes in a loop.
46 // We don't need *vli_pos during this function call anymore,
47 // but update it here so that it is ready if we need to
48 // return before the whole integer has been decoded.
50 assert(*vli_pos
< LZMA_VLI_BYTES_MAX
);
52 // Write the next byte.
53 out
[*out_pos
] = (uint8_t)(vli
) | 0x80;
56 if (++*out_pos
== out_size
)
57 return vli_pos
== &vli_pos_internal
58 ? LZMA_PROG_ERROR
: LZMA_OK
;
61 // Write the last byte.
62 out
[*out_pos
] = (uint8_t)(vli
);
66 return vli_pos
== &vli_pos_internal
? LZMA_OK
: LZMA_STREAM_END
;