huffman/src/buffer.c

45 lines
962 B
C
Raw Normal View History

2016-10-28 14:44:05 +00:00
#include "common.h"
2016-10-27 13:36:51 +00:00
#include "buffer.h"
2016-10-28 14:44:05 +00:00
2016-10-27 13:36:51 +00:00
#include <stdio.h>
Buffer createBuffer(FILE* file) {
Buffer buffer = {
.flushed_bytes = 0,
2016-10-27 13:36:51 +00:00
.data = 0,
.used_bits = 0,
.linked_file = file
};
return buffer;
}
size_t getFlushedBytes(Buffer* buffer) {
return buffer->flushed_bytes;
}
2016-10-27 13:36:51 +00:00
void flushBuffer(Buffer* buffer) {
// FIXME: gérer les erreurs d'écriture
2016-10-27 13:36:51 +00:00
// Alignement des données à gauche de l'octet
buffer->data <<= 8 - buffer->used_bits;
fputc(buffer->data, buffer->linked_file);
buffer->data = 0;
buffer->used_bits = 0;
buffer->flushed_bytes += 1;
2016-10-27 13:36:51 +00:00
}
void pushToBuffer(char bit, Buffer* buffer) {
2016-10-27 13:36:51 +00:00
// Si le tampon déborde, écriture dans le fichier
if (buffer->used_bits == 8) {
flushBuffer(buffer);
}
// Insertion de chaque bit de l'étiquette dans
// le tampon de sortie
buffer->data <<= 1;
buffer->data |= bit;
buffer->used_bits += 1;
}