2019-09-23 05:48:14 +03:00
|
|
|
/*
|
|
|
|
DESCRIPTION
|
|
|
|
helpers.c provides C helper functions for interfacing with C code used for
|
|
|
|
testing in this package.
|
|
|
|
|
|
|
|
AUTHORS
|
|
|
|
Saxon A. Nelson-Milton <saxon@ausocean.org>
|
|
|
|
|
|
|
|
LICENSE
|
|
|
|
Copyright (C) 2019 the Australian Ocean Lab (AusOcean).
|
|
|
|
|
|
|
|
It is free software: you can redistribute it and/or modify them
|
|
|
|
under the terms of the GNU General Public License as published by the
|
|
|
|
Free Software Foundation, either version 3 of the License, or (at your
|
|
|
|
option) any later version.
|
|
|
|
|
|
|
|
It is distributed in the hope that it will be useful, but WITHOUT
|
|
|
|
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
|
|
|
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
|
|
|
for more details.
|
|
|
|
|
|
|
|
You should have received a copy of the GNU General Public License
|
|
|
|
in gpl.txt. If not, see http://www.gnu.org/licenses.
|
|
|
|
*/
|
|
|
|
|
|
|
|
#include "helpers.h"
|
|
|
|
|
|
|
|
typedef struct BitReader BitReader;
|
|
|
|
typedef struct Reader Reader;
|
|
|
|
|
|
|
|
BitReader* new_BitReader(char* d, int l){
|
|
|
|
Reader* r = (Reader*)malloc(sizeof(Reader));
|
2020-01-29 02:56:24 +03:00
|
|
|
if(r == NULL){
|
2019-10-20 02:06:55 +03:00
|
|
|
return NULL;
|
|
|
|
}
|
2019-09-23 05:48:14 +03:00
|
|
|
r->data = d;
|
|
|
|
r->curr = 0;
|
|
|
|
r->len = l;
|
|
|
|
r->err = 0;
|
|
|
|
|
|
|
|
BitReader* br = (BitReader*)malloc(sizeof(BitReader));
|
2020-01-29 02:56:24 +03:00
|
|
|
if(br == NULL){
|
2019-10-20 02:06:55 +03:00
|
|
|
return NULL;
|
|
|
|
}
|
2019-09-23 05:48:14 +03:00
|
|
|
br->r = r;
|
|
|
|
br->n = 0;
|
|
|
|
br->bits = 0;
|
|
|
|
br->nRead = 0;
|
|
|
|
br->err = 0;
|
|
|
|
return br;
|
|
|
|
}
|
|
|
|
|
|
|
|
char next_byte(Reader *r) {
|
|
|
|
if(r->curr >= r->len){
|
|
|
|
r->err = 1;
|
|
|
|
}
|
|
|
|
char next = r->data[r->curr];
|
|
|
|
r->curr++;
|
|
|
|
return next;
|
|
|
|
}
|
|
|
|
|
|
|
|
uint64_t read_bits(BitReader *br, int n) {
|
|
|
|
while( n > br->bits ){
|
|
|
|
char b = next_byte(br->r);
|
|
|
|
if(br->r->err != 0){
|
|
|
|
br->err = 1;
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
br->nRead++;
|
|
|
|
br->n <<= 8;
|
|
|
|
br->n |= (uint64_t)b;
|
|
|
|
br->bits += 8;
|
|
|
|
}
|
|
|
|
|
|
|
|
uint64_t r = (br->n >> (br->bits-n)) & ((1 << n) - 1);
|
|
|
|
br->bits -= n;
|
|
|
|
return r;
|
|
|
|
}
|