Commit b4cad620 by Rudolf

Write special EOF at the end of file

If the file has been padded with extra 0's (since file is written in total
bytes), there is no way to determine what should be the last value. Implement
special 0xFF for this case.

This also changes char to unsigned to avoid comparison failure.
parent 1ac64069
......@@ -27,9 +27,12 @@ void __printb(void *value, size_t size)
printf("\n");
}
void print_char(char c)
void print_char(unsigned char c)
{
switch (c) {
case EOF_CHAR:
printf("EOF\n");
break;
case '\n':
printf("\\n\n");
break;
......
......@@ -19,5 +19,5 @@ void __printb(void *value, size_t size);
__printb((typeof(_v) *) &_v, sizeof(_v)); \
})
void print_char(char c);
void print_char(unsigned char c);
void print_tree(struct tree *parent);
......@@ -43,7 +43,7 @@ struct tree *create_tree(FILE *file)
freq[c]++;
}
struct tree **forest = malloc(charcount * sizeof(struct tree));
struct tree **forest = malloc((charcount + 1) * sizeof(struct tree));
/* Create empty forest - whoah */
int ntrees = 0;
......@@ -53,6 +53,9 @@ struct tree *create_tree(FILE *file)
}
}
/* Insert our special EOF char. */
forest[ntrees++] = insert_simple_tree(EOF_CHAR, 1);
/* Sort ascending */
for (int i = 0; i < ntrees; i++) {
for (int j = i+1; j < ntrees; j++) {
......@@ -85,7 +88,8 @@ struct tree *create_tree(FILE *file)
* Encoding/Decodíng
*/
static int write_entry(struct BIT_BUFFER *bitbuf, struct tree *parent, char c)
static int write_entry(struct BIT_BUFFER *bitbuf, struct tree *parent,
unsigned char c)
{
while (parent != NULL) {
struct tree *left, *right;
......@@ -118,6 +122,9 @@ int encode_tree(struct BIT_BUFFER *bitbuf, struct tree *parent, char *buf,
write_entry(bitbuf, parent, buf[i]);
}
/* Insert our special EOF char. */
write_entry(bitbuf, parent, EOF_CHAR);
return 0;
}
......@@ -128,12 +135,20 @@ static int read_entries(struct BIT_BUFFER *bitbuf, FILE *out,
struct tree *leaf = parent;
while ((bit = bb_read(bitbuf, 1)) != NULL) {
if (*bit == 1) {
if (leaf->right->ch == EOF_CHAR) {
free(bit);
break;
}
fwrite(&leaf->right->ch, 1, 1, out);
leaf->right->freq++;
leaf = parent; /* Reset */
} else {
leaf = leaf->left;
if (!leaf->left) {
if (leaf->ch == EOF_CHAR) {
free(bit);
break;
}
fwrite(&leaf->ch, 1, 1, out);
leaf->freq++;
leaf = parent; /* Reset */
......
......@@ -3,10 +3,13 @@
#include "bit-buffer.h"
/* Our special EOF character. */
#define EOF_CHAR 0xff
struct tree {
struct tree *left;
struct tree *right;
char ch;
unsigned char ch;
int freq;
};
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment