2 * LiZaRd -- Reading and writing to a fastbuf
4 * (c) 2004, Robert Spalek <robert@ucw.cz>
8 #include "lib/lizard.h"
10 #include "lib/fastbuf.h"
11 #include "lib/bucket.h"
16 static float liz_min_compr;
18 static bb_t bb_in, bb_out;
21 lizard_set_type(uns type, float min_compr)
24 liz_min_compr = min_compr;
28 lizard_bwrite(struct fastbuf *fb_out, byte *ptr_in, uns len_in)
33 if (type == BUCKET_TYPE_V33_LIZARD && liz_min_compr)
35 uns est_out = len_in * LIZARD_MAX_MULTIPLY + LIZARD_MAX_ADD + 16;
36 uns aval_out = bdirect_write_prepare(fb_out, &ptr_out);
37 if (aval_out < est_out)
39 bb_grow(&bb_out, est_out);
44 len_out = lizard_compress(ptr_in, len_in, ptr_out);
45 if (len_out + 8 > len_in * liz_min_compr)
47 type = BUCKET_TYPE_V33;
58 bputl(fb_out, len_out);
59 if (type == BUCKET_TYPE_V33_LIZARD)
61 bputl(fb_out, len_in);
62 bputl(fb_out, adler32(ptr_in, len_in));
64 if (ptr_out == bb_out.ptr || ptr_out == ptr_in)
65 bwrite(fb_out, ptr_out, len_out);
67 bdirect_write_commit(fb_out, ptr_out + len_out);
68 return len_out + 8 + (type == BUCKET_TYPE_V33_LIZARD ? 8 : 0);
72 lizard_bbcopy_compress(struct fastbuf *fb_out, struct fastbuf *fb_in, uns len_in)
75 uns i = bdirect_read_prepare(fb_in, &ptr_in);
78 bb_grow(&bb_in, len_in);
79 bread(fb_in, bb_in.ptr, len_in);
83 bdirect_read_commit(fb_in, ptr_in + len_in);
84 return lizard_bwrite(fb_out, ptr_in, len_in);
88 decompress(struct lizard_buffer *liz_buf, byte *ptr_in, byte **ptr_out)
90 uns orig_len = GET_U32(ptr_in);
91 uns orig_adler = GET_U32(ptr_in + 4);
93 *ptr_out = lizard_decompress_safe(ptr_in, liz_buf, orig_len);
96 if (adler32(*ptr_out, orig_len) != orig_adler)
105 lizard_memread(struct lizard_buffer *liz_buf, byte *ptr_in, byte **ptr_out, uns *type)
107 *type = GET_U32(ptr_in);
108 if (*type < BUCKET_TYPE_PLAIN || *type > BUCKET_TYPE_V33_LIZARD)
113 uns stored_len = GET_U32(ptr_in + 4);
115 if (*type == BUCKET_TYPE_V33_LIZARD)
116 return decompress(liz_buf, ptr_in, ptr_out);
125 lizard_bread(struct lizard_buffer *liz_buf, struct fastbuf *fb_in, byte **ptr_out, uns *type)
127 *type = bgetl(fb_in);
128 if (*type < BUCKET_TYPE_PLAIN || *type > BUCKET_TYPE_V33_LIZARD)
130 if (*type == ~0U) // EOF
136 uns stored_len = bgetl(fb_in);
137 uns want_len = stored_len + (*type == BUCKET_TYPE_V33_LIZARD ? 8 : 0);
139 uns i = bdirect_read_prepare(fb_in, &ptr_in);
142 bb_grow(&bb_in, want_len);
143 bread(fb_in, bb_in.ptr, want_len);
147 bdirect_read_commit(fb_in, ptr_in + want_len);
148 if (*type == BUCKET_TYPE_V33_LIZARD)
149 return decompress(liz_buf, ptr_in, ptr_out);