Skip to content

Instantly share code, notes, and snippets.

@asakura
Created August 27, 2019 06:17
Show Gist options
  • Save asakura/9edae447017a40478ac9e38310ec0b19 to your computer and use it in GitHub Desktop.
Save asakura/9edae447017a40478ac9e38310ec0b19 to your computer and use it in GitHub Desktop.
number
#include <stdint.h>
#include "algos_number.h"
void* algos_number_alloc(algos_number_kind kind, void* value) {
algos_number *number = (algos_number*)enif_alloc(sizeof(algos_number));
if (number == NULL) {
exit(1);
}
number->kind = kind;
switch (number->kind) {
case INTEGER:
number->value.integer = (int64_t)value;
break;
case UINTEGER:
number->value.uinteger = (uint64_t)value;
break;
case DECIMAL:
number->value.decimal = (double)value;
break;
default:
exit(1);
}
return number;
}
void *algos_number_alloc_from_eterm(algos_number *number) {
// ???
return NULL;
}
int8_t algos_number_cmp(algos_number *a, algos_number *b) {
switch (a->kind) {
case INTEGER:
switch (b->kind) {
case INTEGER:
return a->value.integer - b->value.integer;
case UINTEGER:
if (a->value.integer < 0) {
return -1;
}
return (uint64_t) a->value.integer - b->value.uinteger;
case DECIMAL:
// TODO: next line is wrong?
return (double) a->value.integer - b->value.uinteger;
default:
exit(1);
}
case UINTEGER:
switch (b->kind) {
case INTEGER:
if (b->value.integer < 0) {
return 1;
}
return a->value.uinteger - (uint64_t) b->value.integer;
case UINTEGER:
return a->value.uinteger - b->value.uinteger;
case DECIMAL:
if (b->value.decimal < 0) {
return 1;
}
// TODO: next line must be wrong
return a->value.uinteger - b->value.decimal;
default:
exit(1);
}
break;
case DECIMAL:
break;
default:
exit(1);
}
}
void algos_number_free(algos_number *number) {
enif_free(number);
}
#praga once
#include <stdint.h>
typedef enum algos_number_kind algos_number_kind;
typedef union algos_number_value algos_number_value;
typedef struct algos_number algos_number;
enum algos_number_kind {
INTEGER,
UINTEGER,
DECIMAL
};
union algos_number_value {
int64_t integer;
uint64_t uinteger;
double decimal;
};
struct algos_number {
algos_number_kind kind;
algos_number_value value;
};
void* algos_number_alloc(algos_number_kind kind, void *value);
void *algos_number_alloc_from_eterm(algos_number *number);
int8_t algos_number_cmp(algos_number *a, algos_number *b);
void algos_number_free(algos_number *number);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment