liblzma: CRC CLMUL: Omit is_arch_extension_supported() when not needed
[xz/debian.git] / src / liblzma / common / vli_encoder.c
blob3859006a94f11b532fd7c9ea1ce08c8f03be8d1f
1 // SPDX-License-Identifier: 0BSD
3 ///////////////////////////////////////////////////////////////////////////////
4 //
5 /// \file vli_encoder.c
6 /// \brief Encodes variable-length integers
7 //
8 // Author: Lasse Collin
9 //
10 ///////////////////////////////////////////////////////////////////////////////
12 #include "common.h"
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,
18 size_t out_size)
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;
29 } else {
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.
42 vli >>= *vli_pos * 7;
44 // Write the non-last bytes in a loop.
45 while (vli >= 0x80) {
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.
49 ++*vli_pos;
50 assert(*vli_pos < LZMA_VLI_BYTES_MAX);
52 // Write the next byte.
53 out[*out_pos] = (uint8_t)(vli) | 0x80;
54 vli >>= 7;
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);
63 ++*out_pos;
64 ++*vli_pos;
66 return vli_pos == &vli_pos_internal ? LZMA_OK : LZMA_STREAM_END;