1 /* lzma encoding (ENCODING_LZMA) backend */
19 #include "encoding/encoding.h"
20 #include "encoding/lzma.h"
21 #include "util/memory.h"
23 #define ELINKS_BZ_BUFFER_LENGTH 5000
25 struct lzma_enc_data
{
26 lzma_stream flzma_stream
;
29 unsigned char buf
[ELINKS_BZ_BUFFER_LENGTH
];
33 lzma_open(struct stream_encoded
*stream
, int fd
)
35 struct lzma_enc_data
*data
= mem_alloc(sizeof(*data
));
43 copy_struct(&data
->flzma_stream
, &LZMA_STREAM_INIT_VAR
);
47 err
= lzma_auto_decoder(&data
->flzma_stream
, NULL
, NULL
);
59 lzma_read(struct stream_encoded
*stream
, unsigned char *buf
, int len
)
61 struct lzma_enc_data
*data
= (struct lzma_enc_data
*) stream
->data
;
68 if (data
->last_read
) return 0;
70 data
->flzma_stream
.avail_out
= len
;
71 data
->flzma_stream
.next_out
= buf
;
74 if (data
->flzma_stream
.avail_in
== 0) {
75 int l
= safe_read(data
->fdread
, data
->buf
,
76 ELINKS_BZ_BUFFER_LENGTH
);
82 return -1; /* I/O error */
84 /* EOF. It is error: we wait for more bytes */
88 data
->flzma_stream
.next_in
= data
->buf
;
89 data
->flzma_stream
.avail_in
= l
;
92 err
= lzma_code(&data
->flzma_stream
, LZMA_RUN
);
93 if (err
== LZMA_STREAM_END
) {
96 } else if (err
!= LZMA_OK
) {
99 } while (data
->flzma_stream
.avail_out
> 0);
101 assert(len
- data
->flzma_stream
.avail_out
== data
->flzma_stream
.next_out
- buf
);
102 return len
- data
->flzma_stream
.avail_out
;
105 static unsigned char *
106 lzma_decode_buffer(unsigned char *data
, int len
, int *new_len
)
108 lzma_stream stream
= LZMA_STREAM_INIT
;
109 unsigned char *buffer
= NULL
;
112 *new_len
= 0; /* default, left there if an error occurs */
114 stream
.next_in
= data
;
115 stream
.avail_in
= len
;
117 if (lzma_auto_decoder(&stream
, NULL
, NULL
) != LZMA_OK
)
121 unsigned char *new_buffer
;
122 size_t size
= stream
.total_out
+ MAX_STR_LEN
;
124 new_buffer
= mem_realloc(buffer
, size
);
126 error
= LZMA_MEM_ERROR
;
131 stream
.next_out
= buffer
+ stream
.total_out
;
132 stream
.avail_out
= MAX_STR_LEN
;
134 error
= lzma_code(&stream
, LZMA_RUN
);
135 if (error
== LZMA_STREAM_END
) {
139 } while (error
== LZMA_OK
&& stream
.avail_in
> 0);
143 if (error
== LZMA_OK
) {
144 *new_len
= stream
.total_out
;
147 if (buffer
) mem_free(buffer
);
153 lzma_close(struct stream_encoded
*stream
)
155 struct lzma_enc_data
*data
= (struct lzma_enc_data
*) stream
->data
;
158 lzma_end(&data
->flzma_stream
);
165 static const unsigned char *const lzma_extensions
[] = { ".lzma", NULL
};
167 const struct decoding_backend lzma_decoding_backend
= {