block_buffer_decoder.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // SPDX-License-Identifier: 0BSD
  2. ///////////////////////////////////////////////////////////////////////////////
  3. //
  4. /// \file block_buffer_decoder.c
  5. /// \brief Single-call .xz Block decoder
  6. //
  7. // Author: Lasse Collin
  8. //
  9. ///////////////////////////////////////////////////////////////////////////////
  10. #include "block_decoder.h"
  11. extern LZMA_API(lzma_ret)
  12. lzma_block_buffer_decode(lzma_block *block, const lzma_allocator *allocator,
  13. const uint8_t *in, size_t *in_pos, size_t in_size,
  14. uint8_t *out, size_t *out_pos, size_t out_size)
  15. {
  16. if (in_pos == NULL || (in == NULL && *in_pos != in_size)
  17. || *in_pos > in_size || out_pos == NULL
  18. || (out == NULL && *out_pos != out_size)
  19. || *out_pos > out_size)
  20. return LZMA_PROG_ERROR;
  21. // Initialize the Block decoder.
  22. lzma_next_coder block_decoder = LZMA_NEXT_CODER_INIT;
  23. lzma_ret ret = lzma_block_decoder_init(
  24. &block_decoder, allocator, block);
  25. if (ret == LZMA_OK) {
  26. // Save the positions so that we can restore them in case
  27. // an error occurs.
  28. const size_t in_start = *in_pos;
  29. const size_t out_start = *out_pos;
  30. // Do the actual decoding.
  31. ret = block_decoder.code(block_decoder.coder, allocator,
  32. in, in_pos, in_size, out, out_pos, out_size,
  33. LZMA_FINISH);
  34. if (ret == LZMA_STREAM_END) {
  35. ret = LZMA_OK;
  36. } else {
  37. if (ret == LZMA_OK) {
  38. // Either the input was truncated or the
  39. // output buffer was too small.
  40. assert(*in_pos == in_size
  41. || *out_pos == out_size);
  42. // If all the input was consumed, then the
  43. // input is truncated, even if the output
  44. // buffer is also full. This is because
  45. // processing the last byte of the Block
  46. // never produces output.
  47. //
  48. // NOTE: This assumption may break when new
  49. // filters are added, if the end marker of
  50. // the filter doesn't consume at least one
  51. // complete byte.
  52. if (*in_pos == in_size)
  53. ret = LZMA_DATA_ERROR;
  54. else
  55. ret = LZMA_BUF_ERROR;
  56. }
  57. // Restore the positions.
  58. *in_pos = in_start;
  59. *out_pos = out_start;
  60. }
  61. }
  62. // Free the decoder memory. This needs to be done even if
  63. // initialization fails, because the internal API doesn't
  64. // require the initialization function to free its memory on error.
  65. lzma_next_end(&block_decoder, allocator);
  66. return ret;
  67. }