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>
|
|
|
|
|
2016-11-19 14:53:43 +00:00
|
|
|
WriteBuffer createWriteBuffer(FILE* file) {
|
|
|
|
WriteBuffer buffer = {
|
|
|
|
.dest_file = file
|
2016-10-27 13:36:51 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
return buffer;
|
|
|
|
}
|
|
|
|
|
2016-11-19 14:53:43 +00:00
|
|
|
void putBuffer(char bit, WriteBuffer* buffer) {
|
|
|
|
// Si le tampon déborde, écriture dans le fichier
|
|
|
|
if (buffer->pending_bits == 8) {
|
|
|
|
flushBuffer(buffer);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Insertion de chaque bit de l'étiquette dans
|
|
|
|
// le tampon de sortie
|
|
|
|
buffer->data <<= 1;
|
|
|
|
buffer->data |= bit;
|
|
|
|
buffer->pending_bits += 1;
|
2016-11-19 13:58:05 +00:00
|
|
|
}
|
|
|
|
|
2016-11-19 14:53:43 +00:00
|
|
|
void flushBuffer(WriteBuffer* buffer) {
|
2016-10-27 16:19:44 +00:00
|
|
|
// FIXME: gérer les erreurs d'écriture
|
2016-10-27 13:36:51 +00:00
|
|
|
|
|
|
|
// Alignement des données à gauche de l'octet
|
2016-11-19 14:53:43 +00:00
|
|
|
buffer->data <<= 8 - buffer->pending_bits;
|
|
|
|
fputc(buffer->data, buffer->dest_file);
|
2016-10-27 13:36:51 +00:00
|
|
|
|
|
|
|
buffer->data = 0;
|
2016-11-19 14:53:43 +00:00
|
|
|
buffer->pending_bits = 0;
|
2016-11-19 20:36:31 +00:00
|
|
|
buffer->flushed_count++;
|
|
|
|
}
|
|
|
|
|
|
|
|
size_t getFlushedCount(WriteBuffer* buffer) {
|
|
|
|
return buffer->flushed_count;
|
2016-10-27 13:36:51 +00:00
|
|
|
}
|
|
|
|
|
2016-11-19 14:53:43 +00:00
|
|
|
ReadBuffer createReadBuffer(FILE* file) {
|
|
|
|
ReadBuffer buffer = {
|
|
|
|
.data = fgetc(file),
|
|
|
|
.next_bit = 7,
|
|
|
|
.source_file = file
|
|
|
|
};
|
|
|
|
|
|
|
|
return buffer;
|
|
|
|
}
|
|
|
|
|
|
|
|
char getBuffer(ReadBuffer* buffer) {
|
2016-11-20 00:29:24 +00:00
|
|
|
if (feof(buffer->source_file)) {
|
|
|
|
return -1;
|
2016-10-27 13:36:51 +00:00
|
|
|
}
|
|
|
|
|
2016-11-19 14:53:43 +00:00
|
|
|
// Lecture du n-ième bit dans le dernier octet lu
|
|
|
|
char result = (
|
|
|
|
buffer->data &
|
|
|
|
(1 << buffer->next_bit)
|
|
|
|
) != 0;
|
|
|
|
|
|
|
|
if (buffer->next_bit > 0) {
|
|
|
|
// Il reste des bits à lire, décalage du compteur
|
|
|
|
buffer->next_bit--;
|
|
|
|
} else {
|
|
|
|
// Besoin de lire le prochain octet depuis le fichier
|
|
|
|
buffer->data = fgetc(buffer->source_file);
|
|
|
|
buffer->next_bit = 7;
|
|
|
|
}
|
|
|
|
|
|
|
|
return result;
|
2016-10-27 13:36:51 +00:00
|
|
|
}
|