1 ///////////////////////////////////////////////////////////////////////////////
3 /// \file stream_buffer_decoder.c
4 /// \brief Single-call .xz Stream decoder
6 // Copyright (C) 2009 Lasse Collin
8 // This library is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU Lesser General Public
10 // License as published by the Free Software Foundation; either
11 // version 2.1 of the License, or (at your option) any later version.
13 // This library is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 // Lesser General Public License for more details.
18 ///////////////////////////////////////////////////////////////////////////////
20 #include "stream_decoder.h"
23 extern LZMA_API(lzma_ret)
24 lzma_stream_buffer_decode(uint64_t *memlimit, uint32_t flags,
25 lzma_allocator *allocator,
26 const uint8_t *in, size_t *in_pos, size_t in_size,
27 uint8_t *out, size_t *out_pos, size_t out_size)
30 if (in_pos == NULL || (in == NULL && *in_pos != in_size)
31 || *in_pos > in_size || out_pos == NULL
32 || (out == NULL && *out_pos != out_size)
33 || *out_pos > out_size)
34 return LZMA_PROG_ERROR;
36 // Catch flags that are not allowed in buffer-to-buffer decoding.
37 if (flags & LZMA_TELL_ANY_CHECK)
38 return LZMA_PROG_ERROR;
40 // Initialize the Stream decoder.
41 // TODO: We need something to tell the decoder that it can use the
42 // output buffer as workspace, and thus save significant amount of RAM.
43 lzma_next_coder stream_decoder = LZMA_NEXT_CODER_INIT;
44 lzma_ret ret = lzma_stream_decoder_init(
45 &stream_decoder, allocator, *memlimit, flags);
48 // Save the positions so that we can restore them in case
50 const size_t in_start = *in_pos;
51 const size_t out_start = *out_pos;
53 // Do the actual decoding.
54 ret = stream_decoder.code(stream_decoder.coder, allocator,
55 in, in_pos, in_size, out, out_pos, out_size,
58 if (ret == LZMA_STREAM_END) {
61 // Something went wrong, restore the positions.
66 // Either the input was truncated or the
67 // output buffer was too small.
68 assert(*in_pos == in_size
69 || *out_pos == out_size);
71 // If all the input was consumed, then the
72 // input is truncated, even if the output
73 // buffer is also full. This is because
74 // processing the last byte of the Stream
75 // never produces output.
76 if (*in_pos == in_size)
77 ret = LZMA_DATA_ERROR;
81 } else if (ret == LZMA_MEMLIMIT_ERROR) {
82 // Let the caller know how much memory would
85 (void)stream_decoder.memconfig(
87 memlimit, &memusage, 0);
92 // Free the decoder memory. This needs to be done even if
93 // initialization fails, because the internal API doesn't
94 // require the initialization function to free its memory on error.
95 lzma_next_end(&stream_decoder, allocator);