Infinity Calculator implementation for Assignment 2 in Computer Organization.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

111 lines
2.6 KiB

infint_t *infint_new(size_t init_cap) {
infint_t *ii = (infint_t *) malloc(sizeof(infint_t));
ii->capacity = init_cap;
ii->size = 1;
ii->data = (uint8_t *) calloc(init_cap, sizeof(uint8_t));
ii->sign = 0;
return ii;
}
infint_t *infint_clone(infint_t *ii) {
infint_t *iic = (infint_t *) malloc(sizeof(infint_t));
iic->capacity = ii->capacity;
iic->size = ii->size;
iic->data = (uint8_t *) calloc(ii->capacity, sizeof(uint8_t));
iic->sign = ii->sign;
memcpy(iic->data, ii->data, ii->capacity);
return iic;
}
infint_t *infint_slice(infint_t *ii, size_t start, size_t len) {
if (start >= ii->size)
len = 0;
else if (start + len >= ii->size)
len = ii->size - start;
infint_t *slice = (infint_t *) malloc(sizeof(infint_t));
slice->capacity = len;
slice->size = len;
slice->sign = 0;
slice->data = (uint8_t *) calloc(len, sizeof(uint8_t));
memcpy(slice->data, ii->data + start, len);
return slice;
}
void infint_free(infint_t *ii) {
free(ii->data);
free(ii);
}
char infint_grow_to(infint_t *ii, size_t size) {
if (ii->size < size) {
if (size > ii->capacity) {
size_t new_cap = ii->capacity * 2;
while (size > new_cap) new_cap *= 2;
uint8_t *new_data = realloc(ii->data, new_cap * sizeof(uint8_t));
if (new_data != NULL) {
memset(new_data + ii->capacity, 0, new_cap - ii->capacity);
ii->data = new_data;
ii->capacity = new_cap;
} else {
return -1;
}
}
ii->size = size;
}
return 0;
}
void infint_comp(infint_t *ii) {
char sign = ii->sign;
for (int i = 0; i < ii->size; ++i) {
ii->data[i] = 99 - ii->data[i];
}
ii->sign = 0;
infint_add(ii,1);
ii->sign = sign;
}
char infint_abs_less_than(infint_t *ii, uint8_t n) {
return ii->size == 1 && ii->data[0] < n;
}
char infint_abs_less_than2(infint_t *ii1, infint_t *ii2) {
if (ii1->size < ii2->size) {
return 1;
} else if (ii1->size > ii2->size) {
return 0;
} else {
return ii1->data[ii1->size-1] < ii2->data[ii1->size-1];
}
}
void infint_shift_right(infint_t *ii, size_t n) {
size_t old_size = ii->size;
if(n > 0) {
infint_grow_to(ii, old_size + n);
memmove(ii->data + n, ii->data, old_size);
memset(ii->data, 0, n);
}
}
char *infint_to_string(infint_t *ii) {
char *str = malloc(ii->size * 2 * sizeof(char) + 2);
size_t si = 0;
uint8_t *ii_ptr = ii->data + ii->size - 1;
if (ii->sign) str[si++] = '-';
if (*ii_ptr >= 10) {
str[si++] = *ii_ptr / 10 + '0';
str[si++] = *ii_ptr % 10 + '0';
} else {
str[si++] = *ii_ptr + '0';
}
--ii_ptr;
while (ii_ptr >= ii->data) {
str[si++] = *ii_ptr / 10 + '0';
str[si++] = *ii_ptr % 10 + '0';
--ii_ptr;
}
str[si] = 0;
return str;
}