/src/CMake/Utilities/cmliblzma/liblzma/common/vli_encoder.c
Line | Count | Source |
1 | | // SPDX-License-Identifier: 0BSD |
2 | | |
3 | | /////////////////////////////////////////////////////////////////////////////// |
4 | | // |
5 | | /// \file vli_encoder.c |
6 | | /// \brief Encodes variable-length integers |
7 | | // |
8 | | // Author: Lasse Collin |
9 | | // |
10 | | /////////////////////////////////////////////////////////////////////////////// |
11 | | |
12 | | #include "common.h" |
13 | | |
14 | | |
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) |
19 | 0 | { |
20 | | // If we haven't been given vli_pos, work in single-call mode. |
21 | 0 | size_t vli_pos_internal = 0; |
22 | 0 | if (vli_pos == NULL) { |
23 | 0 | vli_pos = &vli_pos_internal; |
24 | | |
25 | | // In single-call mode, we expect that the caller has |
26 | | // reserved enough output space. |
27 | 0 | if (*out_pos >= out_size) |
28 | 0 | return LZMA_PROG_ERROR; |
29 | 0 | } else { |
30 | | // This never happens when we are called by liblzma, but |
31 | | // may happen if called directly from an application. |
32 | 0 | if (*out_pos >= out_size) |
33 | 0 | return LZMA_BUF_ERROR; |
34 | 0 | } |
35 | | |
36 | | // Validate the arguments. |
37 | 0 | if (*vli_pos >= LZMA_VLI_BYTES_MAX || vli > LZMA_VLI_MAX) |
38 | 0 | return LZMA_PROG_ERROR; |
39 | | |
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 | 0 | vli >>= *vli_pos * 7; |
43 | | |
44 | | // Write the non-last bytes in a loop. |
45 | 0 | 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 | 0 | ++*vli_pos; |
50 | 0 | assert(*vli_pos < LZMA_VLI_BYTES_MAX); |
51 | | |
52 | | // Write the next byte. |
53 | 0 | out[*out_pos] = (uint8_t)(vli) | 0x80; |
54 | 0 | vli >>= 7; |
55 | |
|
56 | 0 | if (++*out_pos == out_size) |
57 | 0 | return vli_pos == &vli_pos_internal |
58 | 0 | ? LZMA_PROG_ERROR : LZMA_OK; |
59 | 0 | } |
60 | | |
61 | | // Write the last byte. |
62 | 0 | out[*out_pos] = (uint8_t)(vli); |
63 | 0 | ++*out_pos; |
64 | 0 | ++*vli_pos; |
65 | |
|
66 | 0 | return vli_pos == &vli_pos_internal ? LZMA_OK : LZMA_STREAM_END; |
67 | |
|
68 | 0 | } |