block_buffer_decoder.c 2.3 KB

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