~obeancomputer/bitter

62f2f0276b1b5a82ada47a7e604d2dd9602c9e31 — ocsmit 1 year, 2 months ago f91455d
Update add magic string, checks
3 files changed, 37 insertions(+), 6 deletions(-)

M src/bitarr.h
M src/bitarr_io.c
M src/bitarr_io.h
M src/bitarr.h => src/bitarr.h +2 -1
@@ 67,7 67,8 @@

typedef enum {
  BITARR_SUCCESS,
  OUT_OF_BOUNDS
  OUT_OF_BOUNDS,
  FILE_ERROR
} BITARR_ERROR;



M src/bitarr_io.c => src/bitarr_io.c +18 -3
@@ 1,16 1,21 @@
#include "bitarr_io.h"
#include "bitarr.h"
#include <stdio.h>
#include <stdint.h>
#include <string.h>


// TODO: Documentation
void BitArray_save(BitArray* bitarr, FILE *fp)
{

    // Write file identifier
    fwrite(&BIT_MAGIC_NUMBER, sizeof(char), strlen(BIT_MAGIC_NUMBER), fp);

    // BitArray metadata needed to construct data structure
    fwrite(&bitarr->l, sizeof(uint8_t), 1, fp);
    fwrite(&bitarr->width, sizeof(uint8_t), 1, fp);
    fwrite(&bitarr->n, sizeof(uint32_t), 1, fp);

    // Write out compressed array
    unsigned int n_entries = 1 + (((bitarr->l * bitarr->n) - 1) / WORD_SIZE);
    fwrite(&(bitarr->v), sizeof(unsigned int), n_entries, fp);
}


@@ 19,12 24,22 @@ BitArray* BitArray_open(FILE *fp)
{
    uint8_t l, width;
    uint32_t n; 
    char magic_number[strlen(BIT_MAGIC_NUMBER)]; // 3
    
    // Verify it is a correct file
    fread(&magic_number, sizeof(char), strlen(BIT_MAGIC_NUMBER), fp);
    if (strcmp(magic_number, BIT_MAGIC_NUMBER) != 0) {
        fprintf(stderr, "Incorrect file, magic string does not match\n");
        exit(FILE_ERROR);
    }

    // Read in data to allocate memory on heap
    fread(&l, sizeof(uint8_t), 1, fp);
    fread(&width, sizeof(uint8_t), 1, fp);
    fread(&n, sizeof(uint32_t), 1, fp);

    BitArray* bitarr = BitArray_calloc(n, l);

    // Read in compressed array
    fread(&(bitarr->v), WORD_SIZE, 1, fp);
    return bitarr;
}

M src/bitarr_io.h => src/bitarr_io.h +17 -2
@@ 1,11 1,26 @@
#ifndef BITARR_IO_H_
#define BITARR_IO_H_

#include <string.h>
#include "bitarr.h"

static const char BIT_MAGIC_NUMBER[] = { 'B', 'I', 'T' };

// TODO: Documentation
BitArray* BitArray_open(FILE *fp);
/**
 * @brief Save BitArray to disk
 *
 * @param bitarr    Pointer to bitarr
 * @param fp        Filepath to save to
 */
void BitArray_save(BitArray* bitarr, FILE *fp);


/**
 * @brief Opens bitarr saved to disk
 *
 * @param fp    Filepath to bitarr saved on disk
 * @return
 */
BitArray* BitArray_open(FILE *fp);

#endif // BITARR_IO_H_