vli_encoder.c 1.8 KB

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