repo
stringlengths
5
75
commit
stringlengths
40
40
message
stringlengths
6
18.2k
diff
stringlengths
60
262k
jan-kuechler/unitlib
8f29b603a6098e43ebc39b4087b92a691c3aecaf
Renamed status.putc to put_char, as 'putc' may get trashed due to macro substitution from stdio.h
diff --git a/format.c b/format.c index 24a35df..0ca05d9 100644 --- a/format.c +++ b/format.c @@ -1,389 +1,389 @@ #include <assert.h> #include <stdio.h> #include <string.h> #include "intern.h" #include "unitlib.h" struct status { - bool (*putc)(char c, void *info); + bool (*put_char)(char c, void *info); void *info; const unit_t *unit; ul_format_t format; ul_fmtops_t *fmtp; void *extra; }; typedef bool (*printer_t)(struct status*,int,int,bool*); struct f_info { FILE *out; }; static bool f_putc(char c, void *i) { struct f_info *info = i; return fputc(c, info->out) == c; } struct sn_info { char *buffer; int idx; int size; }; static bool sn_putc(char c, void *i) { struct sn_info *info = i; if (info->idx >= info->size) { return false; } info->buffer[info->idx++] = c; return true; } struct cnt_info { size_t count; }; static bool cnt_putc(char c, void *i) { (void)c; struct cnt_info *info = i; info->count++; return true; } -#define _putc(s,c) (s)->putc((c),(s)->info) +#define _putc(s,c) (s)->put_char((c),(s)->info) #define CHECK(x) do { if (!(x)) return false; } while (0) static bool _puts(struct status *s, const char *str) { while (*str) { char c = *str++; if (!_putc(s, c)) return false; } return true; } static bool _putd(struct status *stat, int n) { char buffer[1024]; snprintf(buffer, 1024, "%d", n); return _puts(stat, buffer); } static bool _putn(struct status *stat, ul_number n) { char buffer[1024]; snprintf(buffer, 1024, N_FMT, n); return _puts(stat, buffer); } static void getnexp(ul_number n, ul_number *mantissa, int *exp) { bool neg = false; if (n < 0) { neg = true; n = -n; } if ((ncmp(n, 10.0) == -1) && (ncmp(n, 1.0) == 1)) { *mantissa = neg ? -n : n; *exp = 0; return; } else if (ncmp(n, 10.0) > -1) { int e = 0; do { e++; n /= 10; } while (ncmp(n, 10.0) == 1); *exp = e; *mantissa = neg ? -n : n; } else if (ncmp(n, 1.0) < 1) { int e = 0; while (ncmp(n, 1.0) == -1) { e--; n *= 10; } *exp = e; *mantissa = neg ? -n : n; } } // global for testing purpose, it's not declared in the header void _ul_getnexp(ul_number n, ul_number *m, int *e) { getnexp(n, m, e); } static bool print_sorted(struct status *stat, printer_t func, bool *first) { bool printed[NUM_BASE_UNITS] = {0}; bool _first = true; bool *fptr = first ? first : &_first; // Print any sorted order for (int i=0; i < NUM_BASE_UNITS; ++i) { int unit = stat->fmtp->order[i]; if (unit == U_ANY) { break; } int exp = stat->unit->exps[unit]; CHECK(func(stat, unit, exp , fptr)); printed[unit] = true; } // Print the rest for (int i=0; i < NUM_BASE_UNITS; ++i) { if (!printed[i]) { int exp = stat->unit->exps[i]; if (exp != 0) { CHECK(func(stat, i, exp , fptr)); } } } return true; } static bool print_normal(struct status *stat, printer_t func, bool *first) { bool _first = true; bool *fptr = first ? first : &_first; for (int i=0; i < NUM_BASE_UNITS; ++i) { CHECK(func(stat,i,stat->unit->exps[i], fptr)); } return true; } // Begin - plain static bool _plain_one(struct status* stat, int unit, int exp, bool *first) { if (exp == 0) return true; if (!*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, _ul_symbols[unit])); // and the exponent if (exp != 1) { CHECK(_putc(stat, '^')); CHECK(_putd(stat, exp)); } *first = false; return true; } static bool p_plain(struct status *stat) { CHECK(_putn(stat, stat->unit->factor)); CHECK(_putc(stat, ' ')); if (stat->fmtp && stat->fmtp->sort) { return print_sorted(stat, _plain_one, NULL); } else { return print_normal(stat, _plain_one, NULL); } return true; } // End - plain // Begin - LaTeX static bool _latex_one(struct status *stat, int unit, int exp, bool *first) { if (exp == 0) return true; if (stat->extra) { bool pos = *(bool*)stat->extra; if (exp > 0 && !pos) return true; if (exp < 0) { if (pos) return true; exp = -exp; } } if (!*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, "\\text{")); if (!*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, _ul_symbols[unit])); CHECK(_puts(stat, "}")); if (exp != 1) { CHECK(_putc(stat, '^')); CHECK(_putc(stat, '{')); CHECK(_putd(stat, exp)); CHECK(_putc(stat, '}')); } *first = false; return true; } static bool p_latex_frac(struct status *stat) { bool first = true; bool positive = true; stat->extra = &positive; ul_number m; int e; getnexp(stat->unit->factor, &m, &e); CHECK(_puts(stat, "\\frac{")); if (e >= 0) { CHECK(_putn(stat, m)); if (e > 0) { CHECK(_puts(stat, " \\cdot 10^{")); CHECK(_putd(stat, e)); CHECK(_putc(stat, '}')); } first = false; } if (stat->fmtp && stat->fmtp->sort) { print_sorted(stat, _latex_one, &first); } else { print_normal(stat, _latex_one, &first); } if (first) { // nothing up there... CHECK(_putc(stat, '1')); } CHECK(_puts(stat, "}{")); first = true; positive = false; if (e < 0) { e = -e; CHECK(_putn(stat, m)); if (e > 0) { CHECK(_puts(stat, " \\cdot 10^{")); CHECK(_putd(stat, e)); CHECK(_putc(stat, '}')); } first = false; } if (stat->fmtp && stat->fmtp->sort) { print_sorted(stat, _latex_one, &first); } else { print_normal(stat, _latex_one, &first); } if (first) { CHECK(_putc(stat, '1')); } CHECK(_putc(stat, '}')); return true; } static bool p_latex_inline(struct status *stat) { bool first = false; CHECK(_putc(stat, '$')); ul_number m; int e; getnexp(stat->unit->factor, &m, &e); CHECK(_putn(stat, m)); if (e != 0) { CHECK(_puts(stat, " \\cdot 10^{")); CHECK(_putd(stat, e)); CHECK(_putc(stat, '}')); } for (int i=0; i < NUM_BASE_UNITS; ++i) { int exp = stat->unit->exps[i]; if (exp != 0) { CHECK(_latex_one(stat, i, exp, &first)); } } CHECK(_putc(stat, '$')); return true; } // End - LaTeX static bool _print(struct status *stat) { switch (stat->format) { case UL_FMT_PLAIN: return p_plain(stat); case UL_FMT_LATEX_FRAC: return p_latex_frac(stat); case UL_FMT_LATEX_INLINE: return p_latex_inline(stat); default: ERROR("Unknown format: %d", stat->format); return false; } } UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) { struct f_info info = { .out = f, }; struct status status = { - .putc = f_putc, + .put_char = f_putc, .info = &info, .unit = unit, .format = format, .fmtp = fmtp, .extra = NULL, }; return _print(&status); } UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) { struct sn_info info = { .buffer = buffer, .size = buflen, .idx = 0, }; struct status status = { - .putc = sn_putc, + .put_char = sn_putc, .info = &info, .unit = unit, .format = format, .fmtp = fmtp, .extra = NULL, }; memset(buffer, 0, buflen); return _print(&status); } UL_API size_t ul_length(const unit_t *unit, ul_format_t format) { struct cnt_info info = {0}; struct status status = { - .putc = cnt_putc, + .put_char = cnt_putc, .info = &info, .unit = unit, .format = format, .fmtp = NULL, .extra = NULL, }; _print(&status); return info.count; }
jan-kuechler/unitlib
ac7f4d2a02c2c98c8dbb77dfbfe7ecc90225cf78
Fixed bug where '/' was not handled for numbers.
diff --git a/parser.c b/parser.c index cd227dc..912f00b 100644 --- a/parser.c +++ b/parser.c @@ -1,568 +1,568 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" typedef struct rule { const char *symbol; unit_t unit; bool force; struct rule *next; } rule_t; typedef struct prefix { char symbol; ul_number value; struct prefix *next; } prefix_t; // A list of all rules static rule_t *rules = NULL; // The base rules static rule_t base_rules[NUM_BASE_UNITS]; static prefix_t *prefixes = NULL; #define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) struct parser_state { int sign; }; enum { MAX_SYM_SIZE = 128, MAX_ITEM_SIZE = 1024, }; // Returns the last rule in the list static rule_t *last_rule(void) { rule_t *cur = rules; while (cur) { if (!cur->next) return cur; cur = cur->next; } // rules cannot be NULL assert(false); return NULL; } static rule_t *get_rule(const char *sym) { assert(sym); for (rule_t *cur = rules; cur; cur = cur->next) { if (strcmp(cur->symbol, sym) == 0) return cur; } return NULL; } static prefix_t *last_prefix(void) { prefix_t *cur = prefixes; while (cur) { if (!cur->next) return cur; cur = cur->next; } return NULL; } static prefix_t *get_prefix(char sym) { for (prefix_t *cur = prefixes; cur; cur = cur->next) { if (cur->symbol == sym) return cur; } return NULL; } static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } static size_t nextspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !isspace(text[i])) i++; return i; } static bool try_parse_factor(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); char *endptr; ul_number f = _strton(str, &endptr); if (endptr && *endptr) { debug("'%s' is not a factor", str); return false; } - unit->factor *= f; + unit->factor *= _pown(f, state->sign); return true; } static bool is_special(const char *str) { assert(str); if (strlen(str) == 1) { switch (str[0]) { case '*': // shall be ignored return true; case '/': // change sign return true; } } return false; } static bool handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); switch (str[0]) { case '*': // ignore return true; case '/': state->sign *= -1; return true; } ERROR("Internal error: is_special/handle_special missmatch for '%s'.", str); return false; } static bool unit_and_prefix(const char *sym, unit_t **unit, ul_number *prefix) { rule_t *rule = get_rule(sym); if (rule) { *unit = &rule->unit; *prefix = 1.0; return true; } char p = sym[0]; debug("Got prefix: %c", p); prefix_t *pref = get_prefix(p); if (!pref) { ERROR("Unknown symbol: '%s'", sym); return false; } rule = get_rule(sym + 1); if (!rule) { ERROR("Unknown symbol: '%s' with prefix %c", sym + 1, p); return false; } *unit = &rule->unit; *prefix = pref->value; return true; } static bool parse_item(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; size_t symend = 0; while (str[symend] && str[symend] != '^') symend++; if (symend >= MAX_SYM_SIZE) { ERROR("Symbol to long"); return false; } strncpy(symbol, str, symend); symbol[symend] = '\0'; if (str[symend]) { // The '^' should not be the last value of the string if (!str[symend+1]) { ERROR("Missing exponent after '^' while parsing '%s'", str); return false; } // Parse the exponent char *endptr = NULL; exp = strtol(str+symend+1, &endptr, 10); // the whole exp string was valid only if *endptr is '\0' if (endptr && *endptr) { ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); return false; } } debug("Exponent is %d", exp); exp *= state->sign; unit_t *rule; ul_number prefix; if (!unit_and_prefix(symbol, &rule, &prefix)) return false; // And add the definitions add_unit(unit, rule, exp); unit->factor *= _pown(prefix, exp); return true; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); struct parser_state state; state.sign = 1; init_unit(unit); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace size_t end = nextspace(str, start); if (end == start) {// End of string break; } // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; // and parse it if (is_special(this_item)) { if (!handle_special(this_item, &state)) return false; } else if (try_parse_factor(this_item, unit, &state)) { // nothing todo } else { if (!parse_item(this_item, unit, &state)) return false; } start = end + 1; } while (start < len); return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } static bool add_prefix(char sym, ul_number n) { prefix_t *pref = malloc(sizeof(*pref)); if (!pref) { ERROR("Failed to allocate %d bytes", sizeof(*pref)); return false; } pref->symbol = sym; pref->value = n; pref->next = NULL; prefix_t *last = last_prefix(); if (last) last->next = pref; else prefixes = pref; return true; } static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); for (size_t i=0; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } static bool init_prefixes(void) { if (!add_prefix('Y', 1e24)) return false; if (!add_prefix('Z', 1e21)) return false; //zetta if (!add_prefix('E', 1e18)) return false; //exa if (!add_prefix('P', 1e15)) return false; //peta if (!add_prefix('T', 1e12)) return false; //tera if (!add_prefix('G', 1e9)) return false; // giga if (!add_prefix('M', 1e6)) return false; // mega if (!add_prefix('k', 1e3)) return false; // kilo if (!add_prefix('h', 1e2)) return false; // hecto // missing: da - deca if (!add_prefix('d', 1e-1)) return false; //deci if (!add_prefix('c', 1e-2)) return false; //centi if (!add_prefix('m', 1e-3)) return false; //milli if (!add_prefix('u', 1e-6)) return false; //micro if (!add_prefix('n', 1e-9)) return false; //nano if (!add_prefix('p', 1e-12)) return false; // pico if (!add_prefix('f', 1e-15)) return false; // femto if (!add_prefix('a', 1e-18)) return false; // atto if (!add_prefix('z', 1e-21)) return false; // zepto if (!add_prefix('y', 1e-24)) return false; // yocto return true; } UL_LINKAGE bool _ul_init_rules(void) { for (int i=0; i < NUM_BASE_UNITS; ++i) { base_rules[i].symbol = _ul_symbols[i]; init_unit(&base_rules[i].unit); base_rules[i].force = true; base_rules[i].unit.exps[i] = 1; base_rules[i].next = &base_rules[i+1]; } dynamic_rules = NULL; rules = base_rules; // stupid inconsistend SI system... unit_t gram = { {[U_KILOGRAM] = 1}, 1e-3, }; if (!add_rule("g", &gram, true)) return false; if (!init_prefixes()) return false; return true; } UL_LINKAGE void _ul_free_rules(void) { debug("Freeing rule list"); rule_t *cur = dynamic_rules; while (cur) { rule_t *next = cur->next; free((char*)cur->symbol); free(cur); cur = next; } prefix_t *pref = prefixes; while (pref) { prefix_t *next = pref->next; free(pref); pref = next; } }
jan-kuechler/unitlib
a42cf998c1945d7085bbdf76dc71df4500ea8180
Fixed leaking of the prefix list's memory.
diff --git a/parser.c b/parser.c index 49360f2..cd227dc 100644 --- a/parser.c +++ b/parser.c @@ -49,513 +49,520 @@ static rule_t *last_rule(void) if (!cur->next) return cur; cur = cur->next; } // rules cannot be NULL assert(false); return NULL; } static rule_t *get_rule(const char *sym) { assert(sym); for (rule_t *cur = rules; cur; cur = cur->next) { if (strcmp(cur->symbol, sym) == 0) return cur; } return NULL; } static prefix_t *last_prefix(void) { prefix_t *cur = prefixes; while (cur) { if (!cur->next) return cur; cur = cur->next; } return NULL; } static prefix_t *get_prefix(char sym) { for (prefix_t *cur = prefixes; cur; cur = cur->next) { if (cur->symbol == sym) return cur; } return NULL; } static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } static size_t nextspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !isspace(text[i])) i++; return i; } static bool try_parse_factor(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); char *endptr; ul_number f = _strton(str, &endptr); if (endptr && *endptr) { debug("'%s' is not a factor", str); return false; } unit->factor *= f; return true; } static bool is_special(const char *str) { assert(str); if (strlen(str) == 1) { switch (str[0]) { case '*': // shall be ignored return true; case '/': // change sign return true; } } return false; } static bool handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); switch (str[0]) { case '*': // ignore return true; case '/': state->sign *= -1; return true; } ERROR("Internal error: is_special/handle_special missmatch for '%s'.", str); return false; } static bool unit_and_prefix(const char *sym, unit_t **unit, ul_number *prefix) { rule_t *rule = get_rule(sym); if (rule) { *unit = &rule->unit; *prefix = 1.0; return true; } char p = sym[0]; debug("Got prefix: %c", p); prefix_t *pref = get_prefix(p); if (!pref) { ERROR("Unknown symbol: '%s'", sym); return false; } rule = get_rule(sym + 1); if (!rule) { ERROR("Unknown symbol: '%s' with prefix %c", sym + 1, p); return false; } *unit = &rule->unit; *prefix = pref->value; return true; } static bool parse_item(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; size_t symend = 0; while (str[symend] && str[symend] != '^') symend++; if (symend >= MAX_SYM_SIZE) { ERROR("Symbol to long"); return false; } strncpy(symbol, str, symend); symbol[symend] = '\0'; if (str[symend]) { // The '^' should not be the last value of the string if (!str[symend+1]) { ERROR("Missing exponent after '^' while parsing '%s'", str); return false; } // Parse the exponent char *endptr = NULL; exp = strtol(str+symend+1, &endptr, 10); // the whole exp string was valid only if *endptr is '\0' if (endptr && *endptr) { ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); return false; } } debug("Exponent is %d", exp); exp *= state->sign; unit_t *rule; ul_number prefix; if (!unit_and_prefix(symbol, &rule, &prefix)) return false; // And add the definitions add_unit(unit, rule, exp); unit->factor *= _pown(prefix, exp); return true; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); struct parser_state state; state.sign = 1; init_unit(unit); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace size_t end = nextspace(str, start); if (end == start) {// End of string break; } // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; // and parse it if (is_special(this_item)) { if (!handle_special(this_item, &state)) return false; } else if (try_parse_factor(this_item, unit, &state)) { // nothing todo } else { if (!parse_item(this_item, unit, &state)) return false; } start = end + 1; } while (start < len); return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } static bool add_prefix(char sym, ul_number n) { prefix_t *pref = malloc(sizeof(*pref)); if (!pref) { ERROR("Failed to allocate %d bytes", sizeof(*pref)); return false; } pref->symbol = sym; pref->value = n; pref->next = NULL; prefix_t *last = last_prefix(); if (last) last->next = pref; else prefixes = pref; return true; } static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); for (size_t i=0; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } static bool init_prefixes(void) { if (!add_prefix('Y', 1e24)) return false; if (!add_prefix('Z', 1e21)) return false; //zetta if (!add_prefix('E', 1e18)) return false; //exa if (!add_prefix('P', 1e15)) return false; //peta if (!add_prefix('T', 1e12)) return false; //tera if (!add_prefix('G', 1e9)) return false; // giga if (!add_prefix('M', 1e6)) return false; // mega if (!add_prefix('k', 1e3)) return false; // kilo if (!add_prefix('h', 1e2)) return false; // hecto // missing: da - deca if (!add_prefix('d', 1e-1)) return false; //deci if (!add_prefix('c', 1e-2)) return false; //centi if (!add_prefix('m', 1e-3)) return false; //milli if (!add_prefix('u', 1e-6)) return false; //micro if (!add_prefix('n', 1e-9)) return false; //nano if (!add_prefix('p', 1e-12)) return false; // pico if (!add_prefix('f', 1e-15)) return false; // femto if (!add_prefix('a', 1e-18)) return false; // atto if (!add_prefix('z', 1e-21)) return false; // zepto if (!add_prefix('y', 1e-24)) return false; // yocto return true; } UL_LINKAGE bool _ul_init_rules(void) { for (int i=0; i < NUM_BASE_UNITS; ++i) { base_rules[i].symbol = _ul_symbols[i]; init_unit(&base_rules[i].unit); base_rules[i].force = true; base_rules[i].unit.exps[i] = 1; base_rules[i].next = &base_rules[i+1]; } dynamic_rules = NULL; rules = base_rules; // stupid inconsistend SI system... unit_t gram = { {[U_KILOGRAM] = 1}, 1e-3, }; if (!add_rule("g", &gram, true)) return false; if (!init_prefixes()) return false; return true; } UL_LINKAGE void _ul_free_rules(void) { debug("Freeing rule list"); rule_t *cur = dynamic_rules; while (cur) { rule_t *next = cur->next; free((char*)cur->symbol); free(cur); cur = next; } + + prefix_t *pref = prefixes; + while (pref) { + prefix_t *next = pref->next; + free(pref); + pref = next; + } }
jan-kuechler/unitlib
2ee26e4ab53d05a43cc85726dd1504479b7c454b
Changed version info to 0.4a1
diff --git a/unitlib.h b/unitlib.h index a9c6e32..5aff1f7 100644 --- a/unitlib.h +++ b/unitlib.h @@ -1,237 +1,237 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "unitlib-config.h" #define UL_NAME "unitlib" -#define UL_VERSION "0.4dev" +#define UL_VERSION "0.4a1" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif #if defined(UL_EXPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllexport) #elif defined(UL_IMPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllimport) #else #define UL_API UL_LINKAGE #endif typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; #define U_ANY -1 typedef enum ul_format { UL_FMT_PLAIN, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, } ul_format_t; typedef enum ul_cmpres { UL_ERROR = 0x00, UL_SAME_UNIT = 0x01, UL_SAME_FACTOR = 0x02, UL_EQUAL = 0x03, } ul_cmpres_t; typedef struct ul_format_ops { bool sort; int order[NUM_BASE_UNITS]; } ul_fmtops_t; typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** * Deinitializes the unitlib and frees all. This function * has to be called at the end of the program. * internals resources. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); /** * Returns the factor of a unit * @param unit The unit * @return The factor */ static inline ul_number ul_factor(const unit_t *unit) { if (!unit) return 0.0; return unit->factor; } /** * Compares two units * @param a A unit * @param b Another unit * @return Compare result */ UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b); /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ static inline bool ul_equal(const unit_t *a, const unit_t *b) { return ul_cmp(a, b) == UL_EQUAL; } /** * Copies a unit into another * @param dst Destination unit * @param src Source unit * @return success */ UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src); /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with); /** * Multiplies a unit with a factor * @param unit The unit * @param factor The factor * @return success */ UL_API bool ul_mult(unit_t *unit, ul_number factor); /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ static inline bool ul_print(const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) { return ul_fprint(stdout, unit, format, fmtp); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); /** * Returns the length of the formated unit * @param unit The unit * @param format Format option * @return Length of the formated string */ UL_API size_t ul_length(const unit_t *unit, ul_format_t format); #endif /*UNITLIB_H*/
jan-kuechler/unitlib
c492624595c6ce3a82a2eab108eb2fbe5827fadc
Added tests for the prefix support.
diff --git a/_test.c b/_test.c index be6e91f..27cf78e 100644 --- a/_test.c +++ b/_test.c @@ -1,156 +1,156 @@ #include <stdio.h> #include "unitlib.h" #ifndef SMASH int main(void) { printf("Testing %s\n", UL_FULL_NAME); ul_debugging(true); ul_debugout("debug.log", false); if (!ul_init()) { printf("init failed"); } if (!ul_parse_rule(" N= 1 kg m s^-2 ")) { printf("Error: %s\n", ul_error()); } unit_t unit; - if (!ul_parse("0.2 N^2 * 0.75 m^-1", &unit)) { + if (!ul_parse("( 0.2 N^2 ) * 0.75 m^-1", &unit)) { printf("Error: %s\n", ul_error()); } ul_fmtops_t fmtop; fmtop.sort = true; fmtop.order[0] = U_LEMMING; fmtop.order[1] = U_KILOGRAM; fmtop.order[2] = U_METER; fmtop.order[3] = U_ANY; printf("0.2 N^2 * 0.75 m^-1 = "); if (!ul_fprint(stdout, &unit, UL_FMT_PLAIN, &fmtop)) { printf("Error: %s\n", ul_error()); } printf("\n"); char buffer[1024]; if (!ul_snprint(buffer, 1024, &unit, UL_FMT_PLAIN, NULL)) { printf("Error: %s\n", ul_error()); } printf("snprint => '%s'\n", buffer); { printf("\n----------\n"); fmtop.order[2] = U_ANY; unit_t n; ul_parse("N", &n); printf("1 N = "); ul_print(&n, UL_FMT_PLAIN, &fmtop); printf("\n----------\n\n"); } ul_print( &unit, UL_FMT_LATEX_FRAC, &fmtop); printf("\n"); ul_print(&unit, UL_FMT_LATEX_INLINE, NULL); printf("\n"); { unit_t unit; ul_parse("s^-1", &unit); printf("LaTeX: "); ul_print(&unit, UL_FMT_LATEX_FRAC, NULL); printf("\n"); } { const char *u = "1 mg"; unit_t unit; if (!ul_parse(u, &unit)) printf("%s\n", ul_error()); printf("%s = ", u); ul_print(&unit, UL_FMT_PLAIN, NULL); printf("\n"); } ul_quit(); return 0; } #else void smashit(const char *str, bool asRule) { bool ok = true; if (asRule) { ok = ul_parse_rule(str); } else { unit_t u; ok = ul_parse(str, &u); } if (ok) { fprintf(stderr, "successfull?\n"); } else { fprintf(stderr, "error: %s\n", ul_error()); } } int main(void) { ul_init(); srand(time(NULL)); { fprintf(stderr, "Smash 1: "); char test[] = "dil^aöjf lkfjda gäklj#ä#jadf klnhöklj213jl^^- kjäjre"; smashit(test, false); fprintf(stderr, "Smash 2: "); smashit(test, true); } { size_t size = 4096; int *_test = malloc(size); int i=0; for (; i < size / sizeof(int); ++i) { _test[i] = rand(); } char *test = (char*)_test; for (i=0; i < size; ++i) { if (!test[i]) test[i] = 42; } fprintf(stderr, "%4d bytes garbage: ", size ); smashit(test, false); fprintf(stderr, "as rule: "); smashit(test, true); } { char test[] = " \t\t\n\n\r kg = "; printf("Evil: "); smashit(test, true); } { char test[] = "kg^2!"; printf("test: "); ul_debugging(true); smashit(test, false); } return 0; } #endif diff --git a/parser.c b/parser.c index 01d0e64..49360f2 100644 --- a/parser.c +++ b/parser.c @@ -1,559 +1,561 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" typedef struct rule { const char *symbol; unit_t unit; bool force; struct rule *next; } rule_t; typedef struct prefix { char symbol; ul_number value; struct prefix *next; } prefix_t; // A list of all rules static rule_t *rules = NULL; // The base rules static rule_t base_rules[NUM_BASE_UNITS]; static prefix_t *prefixes = NULL; #define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) struct parser_state { int sign; }; enum { MAX_SYM_SIZE = 128, MAX_ITEM_SIZE = 1024, }; // Returns the last rule in the list static rule_t *last_rule(void) { rule_t *cur = rules; while (cur) { if (!cur->next) return cur; cur = cur->next; } // rules cannot be NULL assert(false); return NULL; } static rule_t *get_rule(const char *sym) { assert(sym); for (rule_t *cur = rules; cur; cur = cur->next) { if (strcmp(cur->symbol, sym) == 0) return cur; } return NULL; } static prefix_t *last_prefix(void) { prefix_t *cur = prefixes; while (cur) { if (!cur->next) return cur; cur = cur->next; } return NULL; } static prefix_t *get_prefix(char sym) { for (prefix_t *cur = prefixes; cur; cur = cur->next) { if (cur->symbol == sym) return cur; } return NULL; } static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } static size_t nextspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !isspace(text[i])) i++; return i; } static bool try_parse_factor(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); char *endptr; ul_number f = _strton(str, &endptr); if (endptr && *endptr) { debug("'%s' is not a factor", str); return false; } unit->factor *= f; return true; } static bool is_special(const char *str) { assert(str); if (strlen(str) == 1) { switch (str[0]) { case '*': + // shall be ignored return true; case '/': + // change sign return true; } } return false; } static bool handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); switch (str[0]) { case '*': // ignore return true; case '/': state->sign *= -1; return true; } ERROR("Internal error: is_special/handle_special missmatch for '%s'.", str); return false; } static bool unit_and_prefix(const char *sym, unit_t **unit, ul_number *prefix) { rule_t *rule = get_rule(sym); if (rule) { *unit = &rule->unit; *prefix = 1.0; return true; } char p = sym[0]; debug("Got prefix: %c", p); prefix_t *pref = get_prefix(p); if (!pref) { ERROR("Unknown symbol: '%s'", sym); return false; } rule = get_rule(sym + 1); if (!rule) { ERROR("Unknown symbol: '%s' with prefix %c", sym + 1, p); return false; } *unit = &rule->unit; *prefix = pref->value; return true; } static bool parse_item(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; size_t symend = 0; while (str[symend] && str[symend] != '^') symend++; if (symend >= MAX_SYM_SIZE) { ERROR("Symbol to long"); return false; } strncpy(symbol, str, symend); symbol[symend] = '\0'; if (str[symend]) { // The '^' should not be the last value of the string if (!str[symend+1]) { ERROR("Missing exponent after '^' while parsing '%s'", str); return false; } // Parse the exponent char *endptr = NULL; exp = strtol(str+symend+1, &endptr, 10); // the whole exp string was valid only if *endptr is '\0' if (endptr && *endptr) { ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); return false; } } debug("Exponent is %d", exp); exp *= state->sign; unit_t *rule; ul_number prefix; if (!unit_and_prefix(symbol, &rule, &prefix)) return false; // And add the definitions add_unit(unit, rule, exp); unit->factor *= _pown(prefix, exp); return true; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); struct parser_state state; state.sign = 1; init_unit(unit); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace size_t end = nextspace(str, start); if (end == start) {// End of string break; } // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; // and parse it if (is_special(this_item)) { if (!handle_special(this_item, &state)) return false; } else if (try_parse_factor(this_item, unit, &state)) { // nothing todo } else { if (!parse_item(this_item, unit, &state)) return false; } start = end + 1; } while (start < len); return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } static bool add_prefix(char sym, ul_number n) { prefix_t *pref = malloc(sizeof(*pref)); if (!pref) { ERROR("Failed to allocate %d bytes", sizeof(*pref)); return false; } pref->symbol = sym; pref->value = n; pref->next = NULL; prefix_t *last = last_prefix(); if (last) last->next = pref; else prefixes = pref; return true; } static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); for (size_t i=0; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } static bool init_prefixes(void) { if (!add_prefix('Y', 1e24)) return false; if (!add_prefix('Z', 1e21)) return false; //zetta if (!add_prefix('E', 1e18)) return false; //exa if (!add_prefix('P', 1e15)) return false; //peta if (!add_prefix('T', 1e12)) return false; //tera if (!add_prefix('G', 1e9)) return false; // giga if (!add_prefix('M', 1e6)) return false; // mega if (!add_prefix('k', 1e3)) return false; // kilo if (!add_prefix('h', 1e2)) return false; // hecto // missing: da - deca if (!add_prefix('d', 1e-1)) return false; //deci if (!add_prefix('c', 1e-2)) return false; //centi if (!add_prefix('m', 1e-3)) return false; //milli if (!add_prefix('u', 1e-6)) return false; //micro if (!add_prefix('n', 1e-9)) return false; //nano if (!add_prefix('p', 1e-12)) return false; // pico if (!add_prefix('f', 1e-15)) return false; // femto if (!add_prefix('a', 1e-18)) return false; // atto if (!add_prefix('z', 1e-21)) return false; // zepto if (!add_prefix('y', 1e-24)) return false; // yocto return true; } UL_LINKAGE bool _ul_init_rules(void) { for (int i=0; i < NUM_BASE_UNITS; ++i) { base_rules[i].symbol = _ul_symbols[i]; init_unit(&base_rules[i].unit); base_rules[i].force = true; base_rules[i].unit.exps[i] = 1; base_rules[i].next = &base_rules[i+1]; } dynamic_rules = NULL; rules = base_rules; // stupid inconsistend SI system... unit_t gram = { {[U_KILOGRAM] = 1}, 1e-3, }; if (!add_rule("g", &gram, true)) return false; if (!init_prefixes()) return false; return true; } UL_LINKAGE void _ul_free_rules(void) { debug("Freeing rule list"); rule_t *cur = dynamic_rules; while (cur) { rule_t *next = cur->next; free((char*)cur->symbol); free(cur); cur = next; } } diff --git a/unittest.c b/unittest.c index 4cb8c50..56e5863 100644 --- a/unittest.c +++ b/unittest.c @@ -1,480 +1,515 @@ #ifndef GET_TEST_DEFS #include <stdarg.h> #include <stdlib.h> #include <string.h> #include "unitlib.h" #include "intern.h" // yay, self include (-: #define GET_TEST_DEFS #include "unittest.c" #undef GET_TEST_DEFS static unit_t make_unit(ul_number fac, ...) { va_list args; va_start(args, fac); unit_t u; memset(u.exps, 0, NUM_BASE_UNITS * sizeof(int)); u.factor = fac; int b = va_arg(args, int); int e = va_arg(args, int); while (b || e) { u.exps[b] = e; b = va_arg(args, int); e = va_arg(args, int); } return u; } #define MAKE_UNIT(...) make_unit(__VA_ARGS__,0,0,0) TEST_SUITE(parser) TEST unit_t u; CHECK(ul_parse("m", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_METER] == 1); int i=0; for (; i < NUM_BASE_UNITS; ++i) { if (i != U_METER) { CHECK(u.exps[i] == 0); } } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; CHECK(ul_parse(" \n kg^2 * m ", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_KILOGRAM] == 2); CHECK(u.exps[U_METER] == 1); CHECK(u.exps[U_SECOND] == 0); CHECK(ncmp(u.factor, 1.0) == 0); CHECK(ul_parse("2 Cd 7 s^-1", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_CANDELA] == 1); CHECK(u.exps[U_SECOND] == -1); CHECK(ncmp(u.factor, 14.0) == 0); CHECK(ul_parse("", &u)); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; const char *strings[] = { "5*kg^2", // need whitespace "5 ** kg^2", // double * "5! * kg^2", // ! "5 * kg^2!", // ! NULL }; int i = 0; while (strings[i]) { CHECK(ul_parse(strings[i], &u) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST const char *strings[] = { "", // empty rule " =", // empty symbol "16 = 16", // invalid rule " a b = s ", // invalid symbol " c == kg", // double = "d = e", // unknown 'e' " = kg", // empty symbol NULL, }; int i=0; while (strings[i]) { CHECK(ul_parse_rule(strings[i]) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST // Empty rules are allowed CHECK(ul_parse_rule("EmptySymbol = ")); FAIL_MSG("Error: %s", ul_error()); unit_t u; CHECK(ul_parse("EmptySymbol", &u)); FAIL_MSG("Error: %s", ul_error()); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; CHECK(ul_parse(NULL, NULL) == false); CHECK(ul_parse(NULL, &u) == false); CHECK(ul_parse("kg", NULL) == false); CHECK(ul_parse_rule(NULL) == false); CHECK(ul_parse_rule("") == false); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t s = MAKE_UNIT(1.0, U_SECOND, 1); unit_t u; CHECK(ul_parse_rule("!ForcedRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("ForcedRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("NewRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("!NewRule = s")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); CHECK(ul_equal(&s, &u)); CHECK(ul_parse_rule("!NewRule = m") == false); CHECK(ul_parse_rule("!kg = kg") == false); CHECK(ul_parse_rule(" Recurse = m")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse_rule("!Recurse = Recurse") == false); END_TEST + + TEST + static char prefs[] = "YZEPTGMkh dcmunpfazy"; + static ul_number factors[] = { + 1e24, 1e21, 1e18, 1e15, 1e12, 1e9, 1e6, 1e3, 1e2, 1, + 1e-1, 1e-2, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15, 1e-18, 1e-21, 1e-24, + }; + + size_t num_prefs = strlen(prefs); + FATAL((sizeof(factors) / sizeof(factors[0])) != num_prefs); + + for (size_t i = 0; i < num_prefs; ++i) { + char expr[128] = ""; + snprintf(expr, 128, "5 %cm", prefs[i]); + + unit_t u; + CHECK(ul_parse(expr, &u)); + FAIL_MSG("Failed to parse: '%s' (%s)", expr, ul_error()); + + CHECK(ncmp(ul_factor(&u), 5 * factors[i]) == 0); + FAIL_MSG("Factor: %g instead of %g (%c)", ul_factor(&u), 5 * factors[i], prefs[i]); + + // check kilogram, the only base unit with a prefix + snprintf(expr, 128, "%cg", prefs[i]); + CHECK(ul_parse(expr, &u)); + } + END_TEST END_TEST_SUITE() TEST_SUITE(core) TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t kg2 = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_equal(&kg, &kg2)); kg2.factor = 2.0; CHECK(!ul_equal(&kg, &kg2)); kg2.factor = 1.0; CHECK(ul_equal(&kg, &kg2)); kg2.exps[U_KILOGRAM]++; CHECK(!ul_equal(&kg, &kg2)); unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); CHECK(!ul_equal(&kg, &N)); END_TEST TEST unit_t a = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t b; CHECK(ul_copy(&b, &a)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&b, &a)); CHECK(!ul_copy(NULL, NULL)); CHECK(!ul_copy(&a, NULL)); CHECK(!ul_copy(NULL, &a)); END_TEST TEST unit_t a = MAKE_UNIT(2.0, U_KILOGRAM, 1); unit_t b = MAKE_UNIT(3.0, U_SECOND, -2); unit_t res; CHECK(ul_copy(&res, &a)); FAIL_MSG("Preparation failed: %s", ul_error()); CHECK(ul_combine(&res, &b)); FAIL_MSG("Error: %s", ul_error()); unit_t correct = MAKE_UNIT(6.0, U_KILOGRAM, 1, U_SECOND, -2); CHECK(ul_equal(&res, &correct)); END_TEST END_TEST_SUITE() TEST_SUITE(format) TEST extern void _ul_getnexp(ul_number n, ul_number *m, int *e); ul_number m; int e; _ul_getnexp(1.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1.0, &m, &e); CHECK(ncmp(m, -1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(11.0, &m, &e); CHECK(ncmp(m, 1.1) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e);; _ul_getnexp(9.81, &m, &e); CHECK(ncmp(m, 9.81) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1234, &m, &e); CHECK(ncmp(m, -1.234) == 0); FAIL_MSG("m == %g", m); CHECK(e == 3); FAIL_MSG("e == %d", e); _ul_getnexp(10.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); _ul_getnexp(0.01, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == -2); FAIL_MSG("e == %d", e); _ul_getnexp(0.99, &m, &e); CHECK(ncmp(m, 9.9) == 0); FAIL_MSG("m == %g", m); CHECK(e == -1); FAIL_MSG("e == %d", e); _ul_getnexp(10.01, &m, &e); CHECK(ncmp(m, 1.001) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN)); kg.factor = 1.5; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1.5 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN)); kg.factor = -1.0; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "-1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 m kg s^-2") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_PLAIN) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_PLAIN)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$1 \\text{ m} \\text{ kg} \\text{ s}^{-2}$") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_INLINE) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_INLINE)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "\\frac{1 \\text{ m} \\text{ kg}}{\\text{s}^{2}}") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_FRAC) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_FRAC)); END_TEST TEST unit_t zeroKg = MAKE_UNIT(0.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &zeroKg, UL_FMT_PLAIN, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "0 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); END_TEST END_TEST_SUITE() int main(void) { ul_debugging(false); if (!ul_init()) { printf("ul_init failed: %s", ul_error()); return 1; } INIT_TEST(); SET_LOGLVL(L_NORMAL); RUN_SUITE(core); RUN_SUITE(parser); RUN_SUITE(format); ul_quit(); return TEST_RESULT; } #endif /*ndef GET_TEST_DEFS*/ //################################################################################################# #ifdef GET_TEST_DEFS #define PRINT(o, lvl, ...) do { if ((o)->loglvl >= lvl) printf(__VA_ARGS__); } while (0) +#define FATAL(expr) \ + do { \ + if (expr) { \ + PRINT(_o, L_RESULT, "[%s-%d] Fatal: %s\n", _name, _id, #expr); \ + exit(1); \ + } \ + } while (0) + #define CHECK(expr) \ do { \ int _this = ++_cid; \ if (!(expr)) { \ _err++; _fail++; \ PRINT(_o, L_NORMAL, "[%s-%d-%d] Fail: '%s'\n", _name, _id, _this, #expr); \ _last = false;\ } \ else { \ PRINT(_o, L_VERBOSE, "[%s-%d-%d] Pass: '%s'\n", _name, _id, _this, #expr); \ _last = true; \ } \ } while (0) #define FAIL_MSG(msg, ...) \ do {if (!_last) PRINT(_o,L_NORMAL,msg"\n", ##__VA_ARGS__); } while (0) #define PASS_MSG(msg, ...) \ do {if (_last) PRINT(_o,L_VERBOSE,msg"\n", ##__VA_ARGS__); } while (0) #define INFO(fmt, ...) \ do { printf("* " fmt "\n", ##__VA_ARGS__); } while (0) // TEST SUITE #define TEST_SUITE(name) \ int _test_##name(_tops *_o) { \ const char *_name = #name; \ int _fail = 0; \ int _test_id = 0; \ #define END_TEST_SUITE() \ return _fail; } // SINGLE TEST #define TEST \ { int _id = ++_test_id; int _err = 0; int _cid = 0; bool _last = true; \ #define END_TEST \ if (_err > 0) { \ PRINT(_o, L_NORMAL, "[%s-%d] failed with %d error%s.\n", _name, _id, _err, _err > 1 ? "s" : ""); \ } \ else { \ PRINT(_o, L_NORMAL, "[%s-%d] passed.\n", _name, _id); \ } \ } // OTHER typedef struct { int loglvl; } _tops; enum { L_QUIET = 0, L_RESULT = 1, L_NORMAL = 2, L_VERBOSE = 3, L_ALL = 4, }; static inline int _run_suite(int (*suite)(_tops*), const char *name, _tops *o) { int num_errs = suite(o); if (num_errs == 0) { PRINT(o, L_RESULT, "[%s] passed.\n", name); } else { PRINT(o, L_RESULT, "[%s] failed with %d error%s.\n", name, num_errs, num_errs > 1 ? "s" : ""); } return num_errs; } #define INIT_TEST() \ _tops _ops; int _tres = 0; #define SET_LOGLVL(lvl) \ _ops.loglvl = (lvl); #define RUN_SUITE(name) \ _tres += _run_suite(_test_##name, #name, &_ops) #define TEST_RESULT _tres #endif /* GET_TEST_DEFS*/
jan-kuechler/unitlib
c58a73408d8b991c1b75246afe2c20c85e88b232
Beautyfication
diff --git a/parser.c b/parser.c index fa96526..01d0e64 100644 --- a/parser.c +++ b/parser.c @@ -1,558 +1,559 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" typedef struct rule { const char *symbol; unit_t unit; bool force; struct rule *next; } rule_t; typedef struct prefix { char symbol; ul_number value; struct prefix *next; } prefix_t; // A list of all rules static rule_t *rules = NULL; // The base rules static rule_t base_rules[NUM_BASE_UNITS]; static prefix_t *prefixes = NULL; #define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) struct parser_state { int sign; }; enum { MAX_SYM_SIZE = 128, MAX_ITEM_SIZE = 1024, }; // Returns the last rule in the list static rule_t *last_rule(void) { rule_t *cur = rules; while (cur) { if (!cur->next) return cur; cur = cur->next; } + // rules cannot be NULL assert(false); return NULL; } -static prefix_t *last_prefix(void) +static rule_t *get_rule(const char *sym) { - prefix_t *cur = prefixes; - while (cur) { - if (!cur->next) + assert(sym); + for (rule_t *cur = rules; cur; cur = cur->next) { + if (strcmp(cur->symbol, sym) == 0) return cur; - cur = cur->next; } return NULL; } -static rule_t *get_rule(const char *sym) +static prefix_t *last_prefix(void) { - assert(sym); - for (rule_t *cur = rules; cur; cur = cur->next) { - if (strcmp(cur->symbol, sym) == 0) + prefix_t *cur = prefixes; + while (cur) { + if (!cur->next) return cur; + cur = cur->next; } return NULL; } static prefix_t *get_prefix(char sym) { for (prefix_t *cur = prefixes; cur; cur = cur->next) { if (cur->symbol == sym) return cur; } return NULL; } static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } static size_t nextspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !isspace(text[i])) i++; return i; } static bool try_parse_factor(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); char *endptr; ul_number f = _strton(str, &endptr); if (endptr && *endptr) { debug("'%s' is not a factor", str); return false; } unit->factor *= f; return true; } static bool is_special(const char *str) { assert(str); if (strlen(str) == 1) { switch (str[0]) { case '*': return true; case '/': return true; } } return false; } static bool handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); switch (str[0]) { case '*': // ignore return true; case '/': state->sign *= -1; return true; } ERROR("Internal error: is_special/handle_special missmatch for '%s'.", str); return false; } static bool unit_and_prefix(const char *sym, unit_t **unit, ul_number *prefix) { rule_t *rule = get_rule(sym); if (rule) { *unit = &rule->unit; *prefix = 1.0; return true; } char p = sym[0]; debug("Got prefix: %c", p); prefix_t *pref = get_prefix(p); if (!pref) { ERROR("Unknown symbol: '%s'", sym); return false; } rule = get_rule(sym + 1); if (!rule) { ERROR("Unknown symbol: '%s' with prefix %c", sym + 1, p); return false; } *unit = &rule->unit; *prefix = pref->value; return true; } static bool parse_item(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; size_t symend = 0; while (str[symend] && str[symend] != '^') symend++; if (symend >= MAX_SYM_SIZE) { ERROR("Symbol to long"); return false; } strncpy(symbol, str, symend); symbol[symend] = '\0'; if (str[symend]) { // The '^' should not be the last value of the string if (!str[symend+1]) { ERROR("Missing exponent after '^' while parsing '%s'", str); return false; } // Parse the exponent char *endptr = NULL; exp = strtol(str+symend+1, &endptr, 10); // the whole exp string was valid only if *endptr is '\0' if (endptr && *endptr) { ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); return false; } } debug("Exponent is %d", exp); exp *= state->sign; unit_t *rule; ul_number prefix; if (!unit_and_prefix(symbol, &rule, &prefix)) return false; // And add the definitions add_unit(unit, rule, exp); unit->factor *= _pown(prefix, exp); return true; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); struct parser_state state; state.sign = 1; init_unit(unit); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace size_t end = nextspace(str, start); if (end == start) {// End of string break; } // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; // and parse it if (is_special(this_item)) { if (!handle_special(this_item, &state)) return false; } else if (try_parse_factor(this_item, unit, &state)) { // nothing todo } else { if (!parse_item(this_item, unit, &state)) return false; } start = end + 1; } while (start < len); return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } static bool add_prefix(char sym, ul_number n) { prefix_t *pref = malloc(sizeof(*pref)); if (!pref) { ERROR("Failed to allocate %d bytes", sizeof(*pref)); return false; } pref->symbol = sym; pref->value = n; pref->next = NULL; prefix_t *last = last_prefix(); if (last) last->next = pref; else prefixes = pref; return true; } static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); for (size_t i=0; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } static bool init_prefixes(void) { - if (!add_prefix('Y', 1e24)) return false; - if (!add_prefix('Z', 1e21)) return false; //zetta - if (!add_prefix('E', 1e18)) return false; //exa - if (!add_prefix('P', 1e15)) return false; //peta - if (!add_prefix('T', 1e12)) return false; //tera - if (!add_prefix('G', 1e9)) return false; // giga - if (!add_prefix('M', 1e6)) return false; // mega - if (!add_prefix('k', 1e3)) return false; // kilo - if (!add_prefix('h', 1e2)) return false; // hecto + if (!add_prefix('Y', 1e24)) return false; + if (!add_prefix('Z', 1e21)) return false; //zetta + if (!add_prefix('E', 1e18)) return false; //exa + if (!add_prefix('P', 1e15)) return false; //peta + if (!add_prefix('T', 1e12)) return false; //tera + if (!add_prefix('G', 1e9)) return false; // giga + if (!add_prefix('M', 1e6)) return false; // mega + if (!add_prefix('k', 1e3)) return false; // kilo + if (!add_prefix('h', 1e2)) return false; // hecto // missing: da - deca - if (!add_prefix('d', 1e-1)) return false; //deci - if (!add_prefix('c', 1e-2)) return false; //centi - if (!add_prefix('m', 1e-3)) return false; //milli - if (!add_prefix('u', 1e-6)) return false; //micro - if (!add_prefix('n', 1e-9)) return false; //nano - if (!add_prefix('p', 1e-12))return false; // pico - if (!add_prefix('f', 1e-15))return false; // femto - if (!add_prefix('a', 1e-18))return false; // atto - if (!add_prefix('z', 1e-21))return false; // zepto - if (!add_prefix('y', 1e-24))return false; // yocto + if (!add_prefix('d', 1e-1)) return false; //deci + if (!add_prefix('c', 1e-2)) return false; //centi + if (!add_prefix('m', 1e-3)) return false; //milli + if (!add_prefix('u', 1e-6)) return false; //micro + if (!add_prefix('n', 1e-9)) return false; //nano + if (!add_prefix('p', 1e-12)) return false; // pico + if (!add_prefix('f', 1e-15)) return false; // femto + if (!add_prefix('a', 1e-18)) return false; // atto + if (!add_prefix('z', 1e-21)) return false; // zepto + if (!add_prefix('y', 1e-24)) return false; // yocto return true; } UL_LINKAGE bool _ul_init_rules(void) { for (int i=0; i < NUM_BASE_UNITS; ++i) { base_rules[i].symbol = _ul_symbols[i]; init_unit(&base_rules[i].unit); base_rules[i].force = true; base_rules[i].unit.exps[i] = 1; base_rules[i].next = &base_rules[i+1]; } dynamic_rules = NULL; rules = base_rules; // stupid inconsistend SI system... unit_t gram = { {[U_KILOGRAM] = 1}, 1e-3, }; if (!add_rule("g", &gram, true)) return false; if (!init_prefixes()) return false; return true; } UL_LINKAGE void _ul_free_rules(void) { debug("Freeing rule list"); rule_t *cur = dynamic_rules; while (cur) { rule_t *next = cur->next; free((char*)cur->symbol); free(cur); cur = next; } }
jan-kuechler/unitlib
d5a31b6b539c78b1d12ad20f6eb32290e343f4ef
Changed the prefix array into a list, for future extensibility.
diff --git a/parser.c b/parser.c index 2dd1b92..fa96526 100644 --- a/parser.c +++ b/parser.c @@ -1,515 +1,558 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" typedef struct rule { const char *symbol; unit_t unit; bool force; struct rule *next; } rule_t; +typedef struct prefix +{ + char symbol; + ul_number value; + struct prefix *next; +} prefix_t; + // A list of all rules static rule_t *rules = NULL; // The base rules static rule_t base_rules[NUM_BASE_UNITS]; -static ul_number prefixes[256]; +static prefix_t *prefixes = NULL; #define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) struct parser_state { int sign; }; enum { MAX_SYM_SIZE = 128, MAX_ITEM_SIZE = 1024, }; // Returns the last rule in the list static rule_t *last_rule(void) { rule_t *cur = rules; while (cur) { if (!cur->next) return cur; cur = cur->next; } assert(false); return NULL; } +static prefix_t *last_prefix(void) +{ + prefix_t *cur = prefixes; + while (cur) { + if (!cur->next) + return cur; + cur = cur->next; + } + return NULL; +} + static rule_t *get_rule(const char *sym) { assert(sym); for (rule_t *cur = rules; cur; cur = cur->next) { if (strcmp(cur->symbol, sym) == 0) return cur; } return NULL; } +static prefix_t *get_prefix(char sym) +{ + for (prefix_t *cur = prefixes; cur; cur = cur->next) { + if (cur->symbol == sym) + return cur; + } + return NULL; +} + static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } static size_t nextspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !isspace(text[i])) i++; return i; } static bool try_parse_factor(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); char *endptr; ul_number f = _strton(str, &endptr); if (endptr && *endptr) { debug("'%s' is not a factor", str); return false; } unit->factor *= f; return true; } static bool is_special(const char *str) { assert(str); if (strlen(str) == 1) { switch (str[0]) { case '*': return true; case '/': return true; } } return false; } static bool handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); switch (str[0]) { case '*': // ignore return true; case '/': state->sign *= -1; return true; } ERROR("Internal error: is_special/handle_special missmatch for '%s'.", str); return false; } static bool unit_and_prefix(const char *sym, unit_t **unit, ul_number *prefix) { rule_t *rule = get_rule(sym); if (rule) { *unit = &rule->unit; *prefix = 1.0; return true; } - size_t p = (size_t)sym[0]; - debug("Got prefix: %c", (char)p); - if (prefixes[p] == 0.0) { + char p = sym[0]; + debug("Got prefix: %c", p); + prefix_t *pref = get_prefix(p); + if (!pref) { ERROR("Unknown symbol: '%s'", sym); return false; } rule = get_rule(sym + 1); if (!rule) { - ERROR("Unknown symbol: '%s' with prefix %c", sym + 1, (char)p); + ERROR("Unknown symbol: '%s' with prefix %c", sym + 1, p); return false; } *unit = &rule->unit; - *prefix = prefixes[p]; + *prefix = pref->value; return true; } static bool parse_item(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; size_t symend = 0; while (str[symend] && str[symend] != '^') symend++; if (symend >= MAX_SYM_SIZE) { ERROR("Symbol to long"); return false; } strncpy(symbol, str, symend); symbol[symend] = '\0'; if (str[symend]) { // The '^' should not be the last value of the string if (!str[symend+1]) { ERROR("Missing exponent after '^' while parsing '%s'", str); return false; } // Parse the exponent char *endptr = NULL; exp = strtol(str+symend+1, &endptr, 10); // the whole exp string was valid only if *endptr is '\0' if (endptr && *endptr) { ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); return false; } } debug("Exponent is %d", exp); exp *= state->sign; unit_t *rule; ul_number prefix; if (!unit_and_prefix(symbol, &rule, &prefix)) return false; // And add the definitions add_unit(unit, rule, exp); unit->factor *= _pown(prefix, exp); return true; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); struct parser_state state; state.sign = 1; init_unit(unit); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace size_t end = nextspace(str, start); if (end == start) {// End of string break; } // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; // and parse it if (is_special(this_item)) { if (!handle_special(this_item, &state)) return false; } else if (try_parse_factor(this_item, unit, &state)) { // nothing todo } else { if (!parse_item(this_item, unit, &state)) return false; } start = end + 1; } while (start < len); return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } +static bool add_prefix(char sym, ul_number n) +{ + prefix_t *pref = malloc(sizeof(*pref)); + if (!pref) { + ERROR("Failed to allocate %d bytes", sizeof(*pref)); + return false; + } + + pref->symbol = sym; + pref->value = n; + pref->next = NULL; + + prefix_t *last = last_prefix(); + if (last) + last->next = pref; + else + prefixes = pref; + return true; +} + static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); for (size_t i=0; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } -static void init_prefixes(void) +static bool init_prefixes(void) { - for (int i=0; i < 256; ++i) { - prefixes[i] = 0.0; - } - - prefixes['Y'] = 1e24; // yotta - prefixes['Z'] = 1e21; // zetta - prefixes['E'] = 1e18; // exa - prefixes['P'] = 1e15; // peta - prefixes['T'] = 1e12; // tera - prefixes['G'] = 1e9; // giga - prefixes['M'] = 1e6; // mega - prefixes['k'] = 1e3; // kilo - prefixes['h'] = 1e2; // hecto + if (!add_prefix('Y', 1e24)) return false; + if (!add_prefix('Z', 1e21)) return false; //zetta + if (!add_prefix('E', 1e18)) return false; //exa + if (!add_prefix('P', 1e15)) return false; //peta + if (!add_prefix('T', 1e12)) return false; //tera + if (!add_prefix('G', 1e9)) return false; // giga + if (!add_prefix('M', 1e6)) return false; // mega + if (!add_prefix('k', 1e3)) return false; // kilo + if (!add_prefix('h', 1e2)) return false; // hecto // missing: da - deca - prefixes['d'] = 1e-1; // deci - prefixes['c'] = 1e-2; // centi - prefixes['m'] = 1e-3; // milli - prefixes['u'] = 1e-6; // micro - prefixes['n'] = 1e-9; // nano - prefixes['p'] = 1e-12; // pico - prefixes['f'] = 1e-15; // femto - - // Note: the following prefixes are so damn small, - // that they get truncated to 0. - // Do not use them! - prefixes['a'] = 1e-18; // atto - prefixes['z'] = 1e-21; // zepto - prefixes['y'] = 1e-24; // yocto + if (!add_prefix('d', 1e-1)) return false; //deci + if (!add_prefix('c', 1e-2)) return false; //centi + if (!add_prefix('m', 1e-3)) return false; //milli + if (!add_prefix('u', 1e-6)) return false; //micro + if (!add_prefix('n', 1e-9)) return false; //nano + if (!add_prefix('p', 1e-12))return false; // pico + if (!add_prefix('f', 1e-15))return false; // femto + if (!add_prefix('a', 1e-18))return false; // atto + if (!add_prefix('z', 1e-21))return false; // zepto + if (!add_prefix('y', 1e-24))return false; // yocto + + return true; } UL_LINKAGE bool _ul_init_rules(void) { for (int i=0; i < NUM_BASE_UNITS; ++i) { base_rules[i].symbol = _ul_symbols[i]; init_unit(&base_rules[i].unit); base_rules[i].force = true; base_rules[i].unit.exps[i] = 1; base_rules[i].next = &base_rules[i+1]; } dynamic_rules = NULL; rules = base_rules; // stupid inconsistend SI system... unit_t gram = { {[U_KILOGRAM] = 1}, 1e-3, }; if (!add_rule("g", &gram, true)) return false; - init_prefixes(); + if (!init_prefixes()) + return false; return true; } UL_LINKAGE void _ul_free_rules(void) { debug("Freeing rule list"); rule_t *cur = dynamic_rules; while (cur) { rule_t *next = cur->next; free((char*)cur->symbol); free(cur); cur = next; } }
jan-kuechler/unitlib
40383304de5146c6d805fa6af2cb05cc6c9be73e
Added function ul_length(unit,format) to determine the length of a formated unit.
diff --git a/format.c b/format.c index 2f90704..24a35df 100644 --- a/format.c +++ b/format.c @@ -1,359 +1,389 @@ #include <assert.h> #include <stdio.h> #include <string.h> #include "intern.h" #include "unitlib.h" struct status { bool (*putc)(char c, void *info); void *info; const unit_t *unit; ul_format_t format; ul_fmtops_t *fmtp; void *extra; }; typedef bool (*printer_t)(struct status*,int,int,bool*); struct f_info { FILE *out; }; static bool f_putc(char c, void *i) { struct f_info *info = i; return fputc(c, info->out) == c; } struct sn_info { char *buffer; int idx; int size; }; static bool sn_putc(char c, void *i) { struct sn_info *info = i; if (info->idx >= info->size) { return false; } info->buffer[info->idx++] = c; return true; } +struct cnt_info +{ + size_t count; +}; + +static bool cnt_putc(char c, void *i) +{ + (void)c; + struct cnt_info *info = i; + info->count++; + return true; +} + #define _putc(s,c) (s)->putc((c),(s)->info) #define CHECK(x) do { if (!(x)) return false; } while (0) static bool _puts(struct status *s, const char *str) { while (*str) { char c = *str++; if (!_putc(s, c)) return false; } return true; } static bool _putd(struct status *stat, int n) { char buffer[1024]; snprintf(buffer, 1024, "%d", n); return _puts(stat, buffer); } static bool _putn(struct status *stat, ul_number n) { char buffer[1024]; snprintf(buffer, 1024, N_FMT, n); return _puts(stat, buffer); } static void getnexp(ul_number n, ul_number *mantissa, int *exp) { bool neg = false; if (n < 0) { neg = true; n = -n; } if ((ncmp(n, 10.0) == -1) && (ncmp(n, 1.0) == 1)) { *mantissa = neg ? -n : n; *exp = 0; return; } else if (ncmp(n, 10.0) > -1) { int e = 0; do { e++; n /= 10; } while (ncmp(n, 10.0) == 1); *exp = e; *mantissa = neg ? -n : n; } else if (ncmp(n, 1.0) < 1) { int e = 0; while (ncmp(n, 1.0) == -1) { e--; n *= 10; } *exp = e; *mantissa = neg ? -n : n; } } // global for testing purpose, it's not declared in the header void _ul_getnexp(ul_number n, ul_number *m, int *e) { getnexp(n, m, e); } static bool print_sorted(struct status *stat, printer_t func, bool *first) { bool printed[NUM_BASE_UNITS] = {0}; bool _first = true; bool *fptr = first ? first : &_first; // Print any sorted order for (int i=0; i < NUM_BASE_UNITS; ++i) { int unit = stat->fmtp->order[i]; if (unit == U_ANY) { break; } int exp = stat->unit->exps[unit]; CHECK(func(stat, unit, exp , fptr)); printed[unit] = true; } // Print the rest for (int i=0; i < NUM_BASE_UNITS; ++i) { if (!printed[i]) { int exp = stat->unit->exps[i]; if (exp != 0) { CHECK(func(stat, i, exp , fptr)); } } } return true; } static bool print_normal(struct status *stat, printer_t func, bool *first) { bool _first = true; bool *fptr = first ? first : &_first; for (int i=0; i < NUM_BASE_UNITS; ++i) { CHECK(func(stat,i,stat->unit->exps[i], fptr)); } return true; } // Begin - plain static bool _plain_one(struct status* stat, int unit, int exp, bool *first) { if (exp == 0) return true; if (!*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, _ul_symbols[unit])); // and the exponent if (exp != 1) { CHECK(_putc(stat, '^')); CHECK(_putd(stat, exp)); } *first = false; return true; } static bool p_plain(struct status *stat) { CHECK(_putn(stat, stat->unit->factor)); CHECK(_putc(stat, ' ')); if (stat->fmtp && stat->fmtp->sort) { return print_sorted(stat, _plain_one, NULL); } else { return print_normal(stat, _plain_one, NULL); } return true; } // End - plain // Begin - LaTeX static bool _latex_one(struct status *stat, int unit, int exp, bool *first) { if (exp == 0) return true; if (stat->extra) { bool pos = *(bool*)stat->extra; if (exp > 0 && !pos) return true; if (exp < 0) { if (pos) return true; exp = -exp; } } if (!*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, "\\text{")); if (!*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, _ul_symbols[unit])); CHECK(_puts(stat, "}")); if (exp != 1) { CHECK(_putc(stat, '^')); CHECK(_putc(stat, '{')); CHECK(_putd(stat, exp)); CHECK(_putc(stat, '}')); } *first = false; return true; } static bool p_latex_frac(struct status *stat) { bool first = true; bool positive = true; stat->extra = &positive; ul_number m; int e; getnexp(stat->unit->factor, &m, &e); CHECK(_puts(stat, "\\frac{")); if (e >= 0) { CHECK(_putn(stat, m)); if (e > 0) { CHECK(_puts(stat, " \\cdot 10^{")); CHECK(_putd(stat, e)); CHECK(_putc(stat, '}')); } first = false; } if (stat->fmtp && stat->fmtp->sort) { print_sorted(stat, _latex_one, &first); } else { print_normal(stat, _latex_one, &first); } if (first) { // nothing up there... CHECK(_putc(stat, '1')); } CHECK(_puts(stat, "}{")); first = true; positive = false; if (e < 0) { e = -e; CHECK(_putn(stat, m)); if (e > 0) { CHECK(_puts(stat, " \\cdot 10^{")); CHECK(_putd(stat, e)); CHECK(_putc(stat, '}')); } first = false; } if (stat->fmtp && stat->fmtp->sort) { print_sorted(stat, _latex_one, &first); } else { print_normal(stat, _latex_one, &first); } if (first) { CHECK(_putc(stat, '1')); } CHECK(_putc(stat, '}')); return true; } static bool p_latex_inline(struct status *stat) { bool first = false; CHECK(_putc(stat, '$')); ul_number m; int e; getnexp(stat->unit->factor, &m, &e); CHECK(_putn(stat, m)); if (e != 0) { CHECK(_puts(stat, " \\cdot 10^{")); CHECK(_putd(stat, e)); CHECK(_putc(stat, '}')); } for (int i=0; i < NUM_BASE_UNITS; ++i) { int exp = stat->unit->exps[i]; if (exp != 0) { CHECK(_latex_one(stat, i, exp, &first)); } } CHECK(_putc(stat, '$')); return true; } // End - LaTeX static bool _print(struct status *stat) { switch (stat->format) { case UL_FMT_PLAIN: return p_plain(stat); case UL_FMT_LATEX_FRAC: return p_latex_frac(stat); case UL_FMT_LATEX_INLINE: return p_latex_inline(stat); default: ERROR("Unknown format: %d", stat->format); return false; } } UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) { struct f_info info = { .out = f, }; struct status status = { .putc = f_putc, .info = &info, .unit = unit, .format = format, .fmtp = fmtp, .extra = NULL, }; return _print(&status); } UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) { struct sn_info info = { .buffer = buffer, .size = buflen, .idx = 0, }; struct status status = { .putc = sn_putc, .info = &info, .unit = unit, .format = format, .fmtp = fmtp, .extra = NULL, }; memset(buffer, 0, buflen); return _print(&status); } + +UL_API size_t ul_length(const unit_t *unit, ul_format_t format) +{ + struct cnt_info info = {0}; + + struct status status = { + .putc = cnt_putc, + .info = &info, + .unit = unit, + .format = format, + .fmtp = NULL, + .extra = NULL, + }; + + _print(&status); + return info.count; +} diff --git a/unitlib.h b/unitlib.h index 22060cd..a9c6e32 100644 --- a/unitlib.h +++ b/unitlib.h @@ -1,229 +1,237 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "unitlib-config.h" #define UL_NAME "unitlib" #define UL_VERSION "0.4dev" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif #if defined(UL_EXPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllexport) #elif defined(UL_IMPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllimport) #else #define UL_API UL_LINKAGE #endif typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; #define U_ANY -1 typedef enum ul_format { UL_FMT_PLAIN, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, } ul_format_t; typedef enum ul_cmpres { UL_ERROR = 0x00, UL_SAME_UNIT = 0x01, UL_SAME_FACTOR = 0x02, UL_EQUAL = 0x03, } ul_cmpres_t; typedef struct ul_format_ops { bool sort; int order[NUM_BASE_UNITS]; } ul_fmtops_t; typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** * Deinitializes the unitlib and frees all. This function * has to be called at the end of the program. * internals resources. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); /** * Returns the factor of a unit * @param unit The unit * @return The factor */ static inline ul_number ul_factor(const unit_t *unit) { if (!unit) return 0.0; return unit->factor; } /** * Compares two units * @param a A unit * @param b Another unit * @return Compare result */ UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b); /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ static inline bool ul_equal(const unit_t *a, const unit_t *b) { return ul_cmp(a, b) == UL_EQUAL; } /** * Copies a unit into another * @param dst Destination unit * @param src Source unit * @return success */ UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src); /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with); /** * Multiplies a unit with a factor * @param unit The unit * @param factor The factor * @return success */ UL_API bool ul_mult(unit_t *unit, ul_number factor); /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ static inline bool ul_print(const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) { return ul_fprint(stdout, unit, format, fmtp); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); +/** + * Returns the length of the formated unit + * @param unit The unit + * @param format Format option + * @return Length of the formated string + */ +UL_API size_t ul_length(const unit_t *unit, ul_format_t format); + #endif /*UNITLIB_H*/ diff --git a/unittest.c b/unittest.c index 2743bb7..4cb8c50 100644 --- a/unittest.c +++ b/unittest.c @@ -1,468 +1,480 @@ #ifndef GET_TEST_DEFS #include <stdarg.h> #include <stdlib.h> #include <string.h> #include "unitlib.h" #include "intern.h" // yay, self include (-: #define GET_TEST_DEFS #include "unittest.c" #undef GET_TEST_DEFS static unit_t make_unit(ul_number fac, ...) { va_list args; va_start(args, fac); unit_t u; memset(u.exps, 0, NUM_BASE_UNITS * sizeof(int)); u.factor = fac; int b = va_arg(args, int); int e = va_arg(args, int); while (b || e) { u.exps[b] = e; b = va_arg(args, int); e = va_arg(args, int); } return u; } #define MAKE_UNIT(...) make_unit(__VA_ARGS__,0,0,0) TEST_SUITE(parser) TEST unit_t u; CHECK(ul_parse("m", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_METER] == 1); int i=0; for (; i < NUM_BASE_UNITS; ++i) { if (i != U_METER) { CHECK(u.exps[i] == 0); } } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; CHECK(ul_parse(" \n kg^2 * m ", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_KILOGRAM] == 2); CHECK(u.exps[U_METER] == 1); CHECK(u.exps[U_SECOND] == 0); CHECK(ncmp(u.factor, 1.0) == 0); CHECK(ul_parse("2 Cd 7 s^-1", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_CANDELA] == 1); CHECK(u.exps[U_SECOND] == -1); CHECK(ncmp(u.factor, 14.0) == 0); CHECK(ul_parse("", &u)); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; const char *strings[] = { "5*kg^2", // need whitespace "5 ** kg^2", // double * "5! * kg^2", // ! "5 * kg^2!", // ! NULL }; int i = 0; while (strings[i]) { CHECK(ul_parse(strings[i], &u) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST const char *strings[] = { "", // empty rule " =", // empty symbol "16 = 16", // invalid rule " a b = s ", // invalid symbol " c == kg", // double = "d = e", // unknown 'e' " = kg", // empty symbol NULL, }; int i=0; while (strings[i]) { CHECK(ul_parse_rule(strings[i]) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST // Empty rules are allowed CHECK(ul_parse_rule("EmptySymbol = ")); FAIL_MSG("Error: %s", ul_error()); unit_t u; CHECK(ul_parse("EmptySymbol", &u)); FAIL_MSG("Error: %s", ul_error()); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; CHECK(ul_parse(NULL, NULL) == false); CHECK(ul_parse(NULL, &u) == false); CHECK(ul_parse("kg", NULL) == false); CHECK(ul_parse_rule(NULL) == false); CHECK(ul_parse_rule("") == false); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t s = MAKE_UNIT(1.0, U_SECOND, 1); unit_t u; CHECK(ul_parse_rule("!ForcedRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("ForcedRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("NewRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("!NewRule = s")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); CHECK(ul_equal(&s, &u)); CHECK(ul_parse_rule("!NewRule = m") == false); CHECK(ul_parse_rule("!kg = kg") == false); CHECK(ul_parse_rule(" Recurse = m")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse_rule("!Recurse = Recurse") == false); END_TEST END_TEST_SUITE() TEST_SUITE(core) TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t kg2 = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_equal(&kg, &kg2)); kg2.factor = 2.0; CHECK(!ul_equal(&kg, &kg2)); kg2.factor = 1.0; CHECK(ul_equal(&kg, &kg2)); kg2.exps[U_KILOGRAM]++; CHECK(!ul_equal(&kg, &kg2)); unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); CHECK(!ul_equal(&kg, &N)); END_TEST TEST unit_t a = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t b; CHECK(ul_copy(&b, &a)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&b, &a)); CHECK(!ul_copy(NULL, NULL)); CHECK(!ul_copy(&a, NULL)); CHECK(!ul_copy(NULL, &a)); END_TEST TEST unit_t a = MAKE_UNIT(2.0, U_KILOGRAM, 1); unit_t b = MAKE_UNIT(3.0, U_SECOND, -2); unit_t res; CHECK(ul_copy(&res, &a)); FAIL_MSG("Preparation failed: %s", ul_error()); CHECK(ul_combine(&res, &b)); FAIL_MSG("Error: %s", ul_error()); unit_t correct = MAKE_UNIT(6.0, U_KILOGRAM, 1, U_SECOND, -2); CHECK(ul_equal(&res, &correct)); END_TEST END_TEST_SUITE() TEST_SUITE(format) TEST extern void _ul_getnexp(ul_number n, ul_number *m, int *e); ul_number m; int e; _ul_getnexp(1.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1.0, &m, &e); CHECK(ncmp(m, -1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(11.0, &m, &e); CHECK(ncmp(m, 1.1) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e);; _ul_getnexp(9.81, &m, &e); CHECK(ncmp(m, 9.81) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1234, &m, &e); CHECK(ncmp(m, -1.234) == 0); FAIL_MSG("m == %g", m); CHECK(e == 3); FAIL_MSG("e == %d", e); _ul_getnexp(10.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); _ul_getnexp(0.01, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == -2); FAIL_MSG("e == %d", e); _ul_getnexp(0.99, &m, &e); CHECK(ncmp(m, 9.9) == 0); FAIL_MSG("m == %g", m); CHECK(e == -1); FAIL_MSG("e == %d", e); _ul_getnexp(10.01, &m, &e); CHECK(ncmp(m, 1.001) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, NULL)); FAIL_MSG("Error: %s", ul_error()); - CHECK(strcmp(buffer, "1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); + CHECK(ul_length(&kg, UL_FMT_PLAIN) == strlen(buffer)); + FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN)); kg.factor = 1.5; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, NULL)); FAIL_MSG("Error: %s", ul_error()); - CHECK(strcmp(buffer, "1.5 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); + CHECK(ul_length(&kg, UL_FMT_PLAIN) == strlen(buffer)); + FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN)); kg.factor = -1.0; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, NULL)); FAIL_MSG("Error: %s", ul_error()); - CHECK(strcmp(buffer, "-1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); + CHECK(ul_length(&kg, UL_FMT_PLAIN) == strlen(buffer)); + FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 m kg s^-2") == 0); FAIL_MSG("buffer: '%s'", buffer); + + CHECK(ul_length(&N, UL_FMT_PLAIN) == strlen(buffer)); + FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_PLAIN)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$1 \\text{ m} \\text{ kg} \\text{ s}^{-2}$") == 0); FAIL_MSG("buffer: '%s'", buffer); + + CHECK(ul_length(&N, UL_FMT_LATEX_INLINE) == strlen(buffer)); + FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_INLINE)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "\\frac{1 \\text{ m} \\text{ kg}}{\\text{s}^{2}}") == 0); FAIL_MSG("buffer: '%s'", buffer); + + CHECK(ul_length(&N, UL_FMT_LATEX_FRAC) == strlen(buffer)); + FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_FRAC)); END_TEST TEST unit_t zeroKg = MAKE_UNIT(0.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &zeroKg, UL_FMT_PLAIN, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "0 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); END_TEST END_TEST_SUITE() int main(void) { ul_debugging(false); if (!ul_init()) { printf("ul_init failed: %s", ul_error()); return 1; } INIT_TEST(); SET_LOGLVL(L_NORMAL); RUN_SUITE(core); RUN_SUITE(parser); RUN_SUITE(format); ul_quit(); return TEST_RESULT; } #endif /*ndef GET_TEST_DEFS*/ //################################################################################################# #ifdef GET_TEST_DEFS #define PRINT(o, lvl, ...) do { if ((o)->loglvl >= lvl) printf(__VA_ARGS__); } while (0) #define CHECK(expr) \ do { \ int _this = ++_cid; \ if (!(expr)) { \ _err++; _fail++; \ PRINT(_o, L_NORMAL, "[%s-%d-%d] Fail: '%s'\n", _name, _id, _this, #expr); \ _last = false;\ } \ else { \ PRINT(_o, L_VERBOSE, "[%s-%d-%d] Pass: '%s'\n", _name, _id, _this, #expr); \ _last = true; \ } \ } while (0) #define FAIL_MSG(msg, ...) \ do {if (!_last) PRINT(_o,L_NORMAL,msg"\n", ##__VA_ARGS__); } while (0) #define PASS_MSG(msg, ...) \ do {if (_last) PRINT(_o,L_VERBOSE,msg"\n", ##__VA_ARGS__); } while (0) #define INFO(fmt, ...) \ do { printf("* " fmt "\n", ##__VA_ARGS__); } while (0) // TEST SUITE #define TEST_SUITE(name) \ int _test_##name(_tops *_o) { \ const char *_name = #name; \ int _fail = 0; \ int _test_id = 0; \ #define END_TEST_SUITE() \ return _fail; } // SINGLE TEST #define TEST \ { int _id = ++_test_id; int _err = 0; int _cid = 0; bool _last = true; \ #define END_TEST \ if (_err > 0) { \ PRINT(_o, L_NORMAL, "[%s-%d] failed with %d error%s.\n", _name, _id, _err, _err > 1 ? "s" : ""); \ } \ else { \ PRINT(_o, L_NORMAL, "[%s-%d] passed.\n", _name, _id); \ } \ } // OTHER typedef struct { int loglvl; } _tops; enum { L_QUIET = 0, L_RESULT = 1, L_NORMAL = 2, L_VERBOSE = 3, L_ALL = 4, }; static inline int _run_suite(int (*suite)(_tops*), const char *name, _tops *o) { int num_errs = suite(o); if (num_errs == 0) { PRINT(o, L_RESULT, "[%s] passed.\n", name); } else { PRINT(o, L_RESULT, "[%s] failed with %d error%s.\n", name, num_errs, num_errs > 1 ? "s" : ""); } return num_errs; } #define INIT_TEST() \ _tops _ops; int _tres = 0; #define SET_LOGLVL(lvl) \ _ops.loglvl = (lvl); #define RUN_SUITE(name) \ _tres += _run_suite(_test_##name, #name, &_ops) #define TEST_RESULT _tres #endif /* GET_TEST_DEFS*/
jan-kuechler/unitlib
e9aa80e878d281b999a7e7bd25bf3dff77398e77
Renamed config header to have a project specific name. Updated install-dll target.
diff --git a/Makefile b/Makefile index ff514ba..c5d1825 100644 --- a/Makefile +++ b/Makefile @@ -1,86 +1,89 @@ ## # Makefile for unitlib ## +MSVC_COMPAT = -mno-cygwin -mms-bitfields + CC = gcc -CFLAGS = -O2 -std=c99 -Wall -Wextra +CFLAGS = -O2 -std=c99 -Wall -Wextra $(MSVC_COMPAT) AR = ar RANLIB = ranlib TARGET = libunit.a DLL = libunit.dll IMPLIB = libunit.lib -HEADER = unitlib.h +HEADER = unitlib-config.h unitlib.h SRCFILES = unitlib.c parser.c format.c -HDRFILES = unitlib.h intern.h config.h +HDRFILES = unitlib.h intern.h unitlib-config.h +DLL_INSTALL = /c/Windows LIB_INSTALL = /g/Programmieren/lib HDR_INSTALL = /g/Programmieren/include OBJFILES = unitlib.o parser.o format.o TESTPROG = _test.exe SMASHPROG = _smash.exe UNITTEST = ultest .PHONY: test clean allclean all: $(TARGET) dll: $(DLL) install-dll: dll - cp $(DLL) $(LIB_INSTALL) + cp $(DLL) $(DLL_INSTALL) cp $(IMPLIB) $(LIB_INSTALL) cp $(HEADER) $(HDR_INSTALL) test: $(TESTPROG) @./$(TESTPROG) utest: $(UNITTEST) @./$(UNITTEST) smash: $(SMASHPROG) @./$(SMASHPROG) $(TARGET): $(OBJFILES) @$(AR) rc $(TARGET) $(OBJFILES) @$(RANLIB) $(TARGET) $(DLL): $(SRCFILES) $(HDRFILES) @$(CC) $(CFLAGS) -shared -o $(DLL) $(SRCFILES) -Wl,--out-implib,$(IMPLIB) unitlib.o: unitlib.c $(HDRFILES) @$(CC) $(CFLAGS) -o unitlib.o -c unitlib.c parser.o: parser.c $(HDRFILES) @$(CC) $(CFLAGS) -o parser.o -c parser.c format.o: format.c $(HDRFILES) @$(CC) $(CFLAGS) -o format.o -c format.c $(TESTPROG): $(TARGET) _test.c @$(CC) -o $(TESTPROG) -g -L. _test.c -lunit $(SMASHPROG): $(TARGET) _test.c @$(CC) -o $(SMASHPROG) -L. -DSMASH _test.c -lunit $(UNITTEST): $(TARGET) unittest.c @$(CC) -std=gnu99 -o $(UNITTEST) -L. unittest.c -lunit clean: @rm -f $(OBJFILES) @rm -f $(TESTPROG) @rm -f $(SMASHPROG) @rm -f $(UNITTEST) @rm -f debug.log allclean: clean @rm -f $(TARGET) @rm -f $(DLL) @rm -f $(IMPLIB) diff --git a/config.h b/unitlib-config.h similarity index 100% rename from config.h rename to unitlib-config.h diff --git a/unitlib.h b/unitlib.h index 9761fca..22060cd 100644 --- a/unitlib.h +++ b/unitlib.h @@ -1,229 +1,229 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> -#include "config.h" +#include "unitlib-config.h" #define UL_NAME "unitlib" #define UL_VERSION "0.4dev" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif #if defined(UL_EXPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllexport) #elif defined(UL_IMPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllimport) #else #define UL_API UL_LINKAGE #endif typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; #define U_ANY -1 typedef enum ul_format { UL_FMT_PLAIN, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, } ul_format_t; typedef enum ul_cmpres { UL_ERROR = 0x00, UL_SAME_UNIT = 0x01, UL_SAME_FACTOR = 0x02, UL_EQUAL = 0x03, } ul_cmpres_t; typedef struct ul_format_ops { bool sort; int order[NUM_BASE_UNITS]; } ul_fmtops_t; typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** * Deinitializes the unitlib and frees all. This function * has to be called at the end of the program. * internals resources. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); /** * Returns the factor of a unit * @param unit The unit * @return The factor */ static inline ul_number ul_factor(const unit_t *unit) { if (!unit) return 0.0; return unit->factor; } /** * Compares two units * @param a A unit * @param b Another unit * @return Compare result */ UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b); /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ static inline bool ul_equal(const unit_t *a, const unit_t *b) { return ul_cmp(a, b) == UL_EQUAL; } /** * Copies a unit into another * @param dst Destination unit * @param src Source unit * @return success */ UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src); /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with); /** * Multiplies a unit with a factor * @param unit The unit * @param factor The factor * @return success */ UL_API bool ul_mult(unit_t *unit, ul_number factor); /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ static inline bool ul_print(const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) { return ul_fprint(stdout, unit, format, fmtp); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); #endif /*UNITLIB_H*/
jan-kuechler/unitlib
6fd32ea932b509158bffbfaeac31579bc7462e5f
Added config.h to the recognized header files
diff --git a/Makefile b/Makefile index 9acddcd..ff514ba 100644 --- a/Makefile +++ b/Makefile @@ -1,86 +1,86 @@ ## # Makefile for unitlib ## CC = gcc CFLAGS = -O2 -std=c99 -Wall -Wextra AR = ar RANLIB = ranlib TARGET = libunit.a DLL = libunit.dll IMPLIB = libunit.lib HEADER = unitlib.h SRCFILES = unitlib.c parser.c format.c -HDRFILES = unitlib.h intern.h +HDRFILES = unitlib.h intern.h config.h LIB_INSTALL = /g/Programmieren/lib HDR_INSTALL = /g/Programmieren/include OBJFILES = unitlib.o parser.o format.o TESTPROG = _test.exe SMASHPROG = _smash.exe UNITTEST = ultest .PHONY: test clean allclean all: $(TARGET) dll: $(DLL) install-dll: dll cp $(DLL) $(LIB_INSTALL) cp $(IMPLIB) $(LIB_INSTALL) cp $(HEADER) $(HDR_INSTALL) test: $(TESTPROG) @./$(TESTPROG) utest: $(UNITTEST) @./$(UNITTEST) smash: $(SMASHPROG) @./$(SMASHPROG) $(TARGET): $(OBJFILES) @$(AR) rc $(TARGET) $(OBJFILES) @$(RANLIB) $(TARGET) $(DLL): $(SRCFILES) $(HDRFILES) @$(CC) $(CFLAGS) -shared -o $(DLL) $(SRCFILES) -Wl,--out-implib,$(IMPLIB) unitlib.o: unitlib.c $(HDRFILES) @$(CC) $(CFLAGS) -o unitlib.o -c unitlib.c parser.o: parser.c $(HDRFILES) @$(CC) $(CFLAGS) -o parser.o -c parser.c format.o: format.c $(HDRFILES) @$(CC) $(CFLAGS) -o format.o -c format.c $(TESTPROG): $(TARGET) _test.c @$(CC) -o $(TESTPROG) -g -L. _test.c -lunit $(SMASHPROG): $(TARGET) _test.c @$(CC) -o $(SMASHPROG) -L. -DSMASH _test.c -lunit $(UNITTEST): $(TARGET) unittest.c @$(CC) -std=gnu99 -o $(UNITTEST) -L. unittest.c -lunit clean: @rm -f $(OBJFILES) @rm -f $(TESTPROG) @rm -f $(SMASHPROG) @rm -f $(UNITTEST) @rm -f debug.log allclean: clean @rm -f $(TARGET) @rm -f $(DLL) @rm -f $(IMPLIB)
jan-kuechler/unitlib
d5dc1081428db790fd44da160ddc5440ec6650e8
Very stupid deve... bug!
diff --git a/parser.c b/parser.c index 5330452..2dd1b92 100644 --- a/parser.c +++ b/parser.c @@ -1,516 +1,515 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" typedef struct rule { const char *symbol; unit_t unit; bool force; struct rule *next; } rule_t; // A list of all rules static rule_t *rules = NULL; // The base rules static rule_t base_rules[NUM_BASE_UNITS]; static ul_number prefixes[256]; #define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) struct parser_state { int sign; }; enum { MAX_SYM_SIZE = 128, MAX_ITEM_SIZE = 1024, }; // Returns the last rule in the list static rule_t *last_rule(void) { rule_t *cur = rules; while (cur) { if (!cur->next) return cur; cur = cur->next; } assert(false); return NULL; } static rule_t *get_rule(const char *sym) { assert(sym); for (rule_t *cur = rules; cur; cur = cur->next) { if (strcmp(cur->symbol, sym) == 0) return cur; } return NULL; } static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } static size_t nextspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !isspace(text[i])) i++; return i; } static bool try_parse_factor(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); char *endptr; ul_number f = _strton(str, &endptr); if (endptr && *endptr) { debug("'%s' is not a factor", str); return false; } unit->factor *= f; return true; } static bool is_special(const char *str) { assert(str); if (strlen(str) == 1) { switch (str[0]) { case '*': return true; case '/': return true; } } return false; } static bool handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); switch (str[0]) { case '*': // ignore return true; case '/': state->sign *= -1; return true; } ERROR("Internal error: is_special/handle_special missmatch for '%s'.", str); return false; } static bool unit_and_prefix(const char *sym, unit_t **unit, ul_number *prefix) { rule_t *rule = get_rule(sym); if (rule) { *unit = &rule->unit; *prefix = 1.0; return true; } size_t p = (size_t)sym[0]; debug("Got prefix: %c", (char)p); if (prefixes[p] == 0.0) { ERROR("Unknown symbol: '%s'", sym); return false; } rule = get_rule(sym + 1); if (!rule) { ERROR("Unknown symbol: '%s' with prefix %c", sym + 1, (char)p); return false; } *unit = &rule->unit; *prefix = prefixes[p]; return true; } static bool parse_item(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; size_t symend = 0; while (str[symend] && str[symend] != '^') symend++; if (symend >= MAX_SYM_SIZE) { ERROR("Symbol to long"); return false; } strncpy(symbol, str, symend); symbol[symend] = '\0'; if (str[symend]) { // The '^' should not be the last value of the string if (!str[symend+1]) { ERROR("Missing exponent after '^' while parsing '%s'", str); return false; } // Parse the exponent char *endptr = NULL; exp = strtol(str+symend+1, &endptr, 10); // the whole exp string was valid only if *endptr is '\0' if (endptr && *endptr) { ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); return false; } } debug("Exponent is %d", exp); + exp *= state->sign; unit_t *rule; ul_number prefix; if (!unit_and_prefix(symbol, &rule, &prefix)) return false; - prefix = _pown(prefix, exp); - // And add the definitions - add_unit(unit, rule, state->sign * exp); - unit->factor *= prefix; + add_unit(unit, rule, exp); + unit->factor *= _pown(prefix, exp); return true; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); struct parser_state state; state.sign = 1; init_unit(unit); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace size_t end = nextspace(str, start); if (end == start) {// End of string break; } // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; // and parse it if (is_special(this_item)) { if (!handle_special(this_item, &state)) return false; } else if (try_parse_factor(this_item, unit, &state)) { // nothing todo } else { if (!parse_item(this_item, unit, &state)) return false; } start = end + 1; } while (start < len); return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); for (size_t i=0; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } static void init_prefixes(void) { for (int i=0; i < 256; ++i) { prefixes[i] = 0.0; } prefixes['Y'] = 1e24; // yotta prefixes['Z'] = 1e21; // zetta prefixes['E'] = 1e18; // exa prefixes['P'] = 1e15; // peta prefixes['T'] = 1e12; // tera prefixes['G'] = 1e9; // giga prefixes['M'] = 1e6; // mega prefixes['k'] = 1e3; // kilo prefixes['h'] = 1e2; // hecto // missing: da - deca prefixes['d'] = 1e-1; // deci prefixes['c'] = 1e-2; // centi prefixes['m'] = 1e-3; // milli prefixes['u'] = 1e-6; // micro prefixes['n'] = 1e-9; // nano prefixes['p'] = 1e-12; // pico prefixes['f'] = 1e-15; // femto // Note: the following prefixes are so damn small, // that they get truncated to 0. // Do not use them! prefixes['a'] = 1e-18; // atto prefixes['z'] = 1e-21; // zepto prefixes['y'] = 1e-24; // yocto } UL_LINKAGE bool _ul_init_rules(void) { for (int i=0; i < NUM_BASE_UNITS; ++i) { base_rules[i].symbol = _ul_symbols[i]; init_unit(&base_rules[i].unit); base_rules[i].force = true; base_rules[i].unit.exps[i] = 1; base_rules[i].next = &base_rules[i+1]; } dynamic_rules = NULL; rules = base_rules; // stupid inconsistend SI system... unit_t gram = { {[U_KILOGRAM] = 1}, 1e-3, }; if (!add_rule("g", &gram, true)) return false; init_prefixes(); return true; } UL_LINKAGE void _ul_free_rules(void) { debug("Freeing rule list"); rule_t *cur = dynamic_rules; while (cur) { rule_t *next = cur->next; free((char*)cur->symbol); free(cur); cur = next; } }
jan-kuechler/unitlib
2ccd6be2b278d254e71423ba9bae3b6fa0564b1e
Stupid bug...
diff --git a/parser.c b/parser.c index dc31b0d..5330452 100644 --- a/parser.c +++ b/parser.c @@ -1,516 +1,516 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" typedef struct rule { const char *symbol; unit_t unit; bool force; struct rule *next; } rule_t; // A list of all rules static rule_t *rules = NULL; // The base rules static rule_t base_rules[NUM_BASE_UNITS]; static ul_number prefixes[256]; #define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) struct parser_state { int sign; }; enum { MAX_SYM_SIZE = 128, MAX_ITEM_SIZE = 1024, }; // Returns the last rule in the list static rule_t *last_rule(void) { rule_t *cur = rules; while (cur) { if (!cur->next) return cur; cur = cur->next; } assert(false); return NULL; } static rule_t *get_rule(const char *sym) { assert(sym); for (rule_t *cur = rules; cur; cur = cur->next) { if (strcmp(cur->symbol, sym) == 0) return cur; } return NULL; } static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } static size_t nextspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !isspace(text[i])) i++; return i; } static bool try_parse_factor(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); char *endptr; ul_number f = _strton(str, &endptr); if (endptr && *endptr) { debug("'%s' is not a factor", str); return false; } unit->factor *= f; return true; } static bool is_special(const char *str) { assert(str); if (strlen(str) == 1) { switch (str[0]) { case '*': return true; case '/': return true; } } return false; } static bool handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); switch (str[0]) { case '*': // ignore return true; case '/': state->sign *= -1; return true; } ERROR("Internal error: is_special/handle_special missmatch for '%s'.", str); return false; } static bool unit_and_prefix(const char *sym, unit_t **unit, ul_number *prefix) { rule_t *rule = get_rule(sym); if (rule) { *unit = &rule->unit; *prefix = 1.0; return true; } size_t p = (size_t)sym[0]; debug("Got prefix: %c", (char)p); if (prefixes[p] == 0.0) { ERROR("Unknown symbol: '%s'", sym); return false; } rule = get_rule(sym + 1); if (!rule) { ERROR("Unknown symbol: '%s' with prefix %c", sym + 1, (char)p); return false; } *unit = &rule->unit; *prefix = prefixes[p]; return true; } static bool parse_item(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; size_t symend = 0; while (str[symend] && str[symend] != '^') symend++; if (symend >= MAX_SYM_SIZE) { ERROR("Symbol to long"); return false; } strncpy(symbol, str, symend); symbol[symend] = '\0'; if (str[symend]) { // The '^' should not be the last value of the string if (!str[symend+1]) { ERROR("Missing exponent after '^' while parsing '%s'", str); return false; } // Parse the exponent char *endptr = NULL; exp = strtol(str+symend+1, &endptr, 10); // the whole exp string was valid only if *endptr is '\0' if (endptr && *endptr) { ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); return false; } } debug("Exponent is %d", exp); unit_t *rule; ul_number prefix; if (!unit_and_prefix(symbol, &rule, &prefix)) return false; - prefix = _pown(prefix, abs(exp)); + prefix = _pown(prefix, exp); // And add the definitions add_unit(unit, rule, state->sign * exp); unit->factor *= prefix; return true; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); struct parser_state state; state.sign = 1; init_unit(unit); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace size_t end = nextspace(str, start); if (end == start) {// End of string break; } // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; // and parse it if (is_special(this_item)) { if (!handle_special(this_item, &state)) return false; } else if (try_parse_factor(this_item, unit, &state)) { // nothing todo } else { if (!parse_item(this_item, unit, &state)) return false; } start = end + 1; } while (start < len); return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); for (size_t i=0; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } static void init_prefixes(void) { for (int i=0; i < 256; ++i) { prefixes[i] = 0.0; } prefixes['Y'] = 1e24; // yotta prefixes['Z'] = 1e21; // zetta prefixes['E'] = 1e18; // exa prefixes['P'] = 1e15; // peta prefixes['T'] = 1e12; // tera prefixes['G'] = 1e9; // giga prefixes['M'] = 1e6; // mega prefixes['k'] = 1e3; // kilo prefixes['h'] = 1e2; // hecto // missing: da - deca prefixes['d'] = 1e-1; // deci prefixes['c'] = 1e-2; // centi prefixes['m'] = 1e-3; // milli prefixes['u'] = 1e-6; // micro prefixes['n'] = 1e-9; // nano prefixes['p'] = 1e-12; // pico prefixes['f'] = 1e-15; // femto // Note: the following prefixes are so damn small, // that they get truncated to 0. // Do not use them! prefixes['a'] = 1e-18; // atto prefixes['z'] = 1e-21; // zepto prefixes['y'] = 1e-24; // yocto } UL_LINKAGE bool _ul_init_rules(void) { for (int i=0; i < NUM_BASE_UNITS; ++i) { base_rules[i].symbol = _ul_symbols[i]; init_unit(&base_rules[i].unit); base_rules[i].force = true; base_rules[i].unit.exps[i] = 1; base_rules[i].next = &base_rules[i+1]; } dynamic_rules = NULL; rules = base_rules; // stupid inconsistend SI system... unit_t gram = { {[U_KILOGRAM] = 1}, 1e-3, }; if (!add_rule("g", &gram, true)) return false; init_prefixes(); return true; } UL_LINKAGE void _ul_free_rules(void) { debug("Freeing rule list"); rule_t *cur = dynamic_rules; while (cur) { rule_t *next = cur->next; free((char*)cur->symbol); free(cur); cur = next; } }
jan-kuechler/unitlib
badf37e42ff7f842404009fbc360b1eee137b06c
Added some more prefixes.
diff --git a/parser.c b/parser.c index 6f5b7e3..dc31b0d 100644 --- a/parser.c +++ b/parser.c @@ -1,504 +1,516 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" typedef struct rule { const char *symbol; unit_t unit; bool force; struct rule *next; } rule_t; // A list of all rules static rule_t *rules = NULL; // The base rules static rule_t base_rules[NUM_BASE_UNITS]; static ul_number prefixes[256]; #define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) struct parser_state { int sign; }; enum { MAX_SYM_SIZE = 128, MAX_ITEM_SIZE = 1024, }; // Returns the last rule in the list static rule_t *last_rule(void) { rule_t *cur = rules; while (cur) { if (!cur->next) return cur; cur = cur->next; } assert(false); return NULL; } static rule_t *get_rule(const char *sym) { assert(sym); for (rule_t *cur = rules; cur; cur = cur->next) { if (strcmp(cur->symbol, sym) == 0) return cur; } return NULL; } static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } static size_t nextspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !isspace(text[i])) i++; return i; } static bool try_parse_factor(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); char *endptr; ul_number f = _strton(str, &endptr); if (endptr && *endptr) { debug("'%s' is not a factor", str); return false; } unit->factor *= f; return true; } static bool is_special(const char *str) { assert(str); if (strlen(str) == 1) { switch (str[0]) { case '*': return true; case '/': return true; } } return false; } static bool handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); switch (str[0]) { case '*': // ignore return true; case '/': state->sign *= -1; return true; } ERROR("Internal error: is_special/handle_special missmatch for '%s'.", str); return false; } static bool unit_and_prefix(const char *sym, unit_t **unit, ul_number *prefix) { rule_t *rule = get_rule(sym); if (rule) { *unit = &rule->unit; *prefix = 1.0; return true; } size_t p = (size_t)sym[0]; debug("Got prefix: %c", (char)p); if (prefixes[p] == 0.0) { ERROR("Unknown symbol: '%s'", sym); return false; } rule = get_rule(sym + 1); if (!rule) { ERROR("Unknown symbol: '%s' with prefix %c", sym + 1, (char)p); return false; } *unit = &rule->unit; *prefix = prefixes[p]; return true; } static bool parse_item(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; size_t symend = 0; while (str[symend] && str[symend] != '^') symend++; if (symend >= MAX_SYM_SIZE) { ERROR("Symbol to long"); return false; } strncpy(symbol, str, symend); symbol[symend] = '\0'; if (str[symend]) { // The '^' should not be the last value of the string if (!str[symend+1]) { ERROR("Missing exponent after '^' while parsing '%s'", str); return false; } // Parse the exponent char *endptr = NULL; exp = strtol(str+symend+1, &endptr, 10); // the whole exp string was valid only if *endptr is '\0' if (endptr && *endptr) { ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); return false; } } debug("Exponent is %d", exp); unit_t *rule; ul_number prefix; if (!unit_and_prefix(symbol, &rule, &prefix)) return false; prefix = _pown(prefix, abs(exp)); // And add the definitions add_unit(unit, rule, state->sign * exp); unit->factor *= prefix; return true; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); struct parser_state state; state.sign = 1; init_unit(unit); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace size_t end = nextspace(str, start); if (end == start) {// End of string break; } // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; // and parse it if (is_special(this_item)) { if (!handle_special(this_item, &state)) return false; } else if (try_parse_factor(this_item, unit, &state)) { // nothing todo } else { if (!parse_item(this_item, unit, &state)) return false; } start = end + 1; } while (start < len); return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); for (size_t i=0; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } static void init_prefixes(void) { for (int i=0; i < 256; ++i) { prefixes[i] = 0.0; } + prefixes['Y'] = 1e24; // yotta + prefixes['Z'] = 1e21; // zetta + prefixes['E'] = 1e18; // exa + prefixes['P'] = 1e15; // peta prefixes['T'] = 1e12; // tera prefixes['G'] = 1e9; // giga prefixes['M'] = 1e6; // mega prefixes['k'] = 1e3; // kilo prefixes['h'] = 1e2; // hecto // missing: da - deca prefixes['d'] = 1e-1; // deci prefixes['c'] = 1e-2; // centi prefixes['m'] = 1e-3; // milli prefixes['u'] = 1e-6; // micro prefixes['n'] = 1e-9; // nano prefixes['p'] = 1e-12; // pico + prefixes['f'] = 1e-15; // femto + + // Note: the following prefixes are so damn small, + // that they get truncated to 0. + // Do not use them! + prefixes['a'] = 1e-18; // atto + prefixes['z'] = 1e-21; // zepto + prefixes['y'] = 1e-24; // yocto } UL_LINKAGE bool _ul_init_rules(void) { for (int i=0; i < NUM_BASE_UNITS; ++i) { base_rules[i].symbol = _ul_symbols[i]; init_unit(&base_rules[i].unit); base_rules[i].force = true; base_rules[i].unit.exps[i] = 1; base_rules[i].next = &base_rules[i+1]; } dynamic_rules = NULL; rules = base_rules; // stupid inconsistend SI system... unit_t gram = { {[U_KILOGRAM] = 1}, 1e-3, }; if (!add_rule("g", &gram, true)) return false; init_prefixes(); return true; } UL_LINKAGE void _ul_free_rules(void) { debug("Freeing rule list"); rule_t *cur = dynamic_rules; while (cur) { rule_t *next = cur->next; free((char*)cur->symbol); free(cur); cur = next; } }
jan-kuechler/unitlib
849d3569cabe959cc70455c701d2d964d03b1d8c
Started development of version 0.4.
diff --git a/unitlib.h b/unitlib.h index 3a4d94d..9761fca 100644 --- a/unitlib.h +++ b/unitlib.h @@ -1,229 +1,229 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "config.h" #define UL_NAME "unitlib" -#define UL_VERSION "0.3" +#define UL_VERSION "0.4dev" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif #if defined(UL_EXPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllexport) #elif defined(UL_IMPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllimport) #else #define UL_API UL_LINKAGE #endif typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; #define U_ANY -1 typedef enum ul_format { UL_FMT_PLAIN, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, } ul_format_t; typedef enum ul_cmpres { UL_ERROR = 0x00, UL_SAME_UNIT = 0x01, UL_SAME_FACTOR = 0x02, UL_EQUAL = 0x03, } ul_cmpres_t; typedef struct ul_format_ops { bool sort; int order[NUM_BASE_UNITS]; } ul_fmtops_t; typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** * Deinitializes the unitlib and frees all. This function * has to be called at the end of the program. * internals resources. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); /** * Returns the factor of a unit * @param unit The unit * @return The factor */ static inline ul_number ul_factor(const unit_t *unit) { if (!unit) return 0.0; return unit->factor; } /** * Compares two units * @param a A unit * @param b Another unit * @return Compare result */ UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b); /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ static inline bool ul_equal(const unit_t *a, const unit_t *b) { return ul_cmp(a, b) == UL_EQUAL; } /** * Copies a unit into another * @param dst Destination unit * @param src Source unit * @return success */ UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src); /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with); /** * Multiplies a unit with a factor * @param unit The unit * @param factor The factor * @return success */ UL_API bool ul_mult(unit_t *unit, ul_number factor); /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ static inline bool ul_print(const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) { return ul_fprint(stdout, unit, format, fmtp); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); #endif /*UNITLIB_H*/
jan-kuechler/unitlib
42f7b76899a90ab8f4084e6a388602d34efc984a
Added basic prefix support.
diff --git a/_test.c b/_test.c index e970183..be6e91f 100644 --- a/_test.c +++ b/_test.c @@ -1,145 +1,156 @@ #include <stdio.h> #include "unitlib.h" #ifndef SMASH int main(void) { printf("Testing %s\n", UL_FULL_NAME); ul_debugging(true); ul_debugout("debug.log", false); if (!ul_init()) { printf("init failed"); } if (!ul_parse_rule(" N= 1 kg m s^-2 ")) { printf("Error: %s\n", ul_error()); } unit_t unit; if (!ul_parse("0.2 N^2 * 0.75 m^-1", &unit)) { printf("Error: %s\n", ul_error()); } ul_fmtops_t fmtop; fmtop.sort = true; fmtop.order[0] = U_LEMMING; fmtop.order[1] = U_KILOGRAM; fmtop.order[2] = U_METER; fmtop.order[3] = U_ANY; printf("0.2 N^2 * 0.75 m^-1 = "); if (!ul_fprint(stdout, &unit, UL_FMT_PLAIN, &fmtop)) { printf("Error: %s\n", ul_error()); } printf("\n"); char buffer[1024]; if (!ul_snprint(buffer, 1024, &unit, UL_FMT_PLAIN, NULL)) { printf("Error: %s\n", ul_error()); } printf("snprint => '%s'\n", buffer); { printf("\n----------\n"); fmtop.order[2] = U_ANY; unit_t n; ul_parse("N", &n); printf("1 N = "); ul_print(&n, UL_FMT_PLAIN, &fmtop); printf("\n----------\n\n"); } ul_print( &unit, UL_FMT_LATEX_FRAC, &fmtop); printf("\n"); ul_print(&unit, UL_FMT_LATEX_INLINE, NULL); printf("\n"); { unit_t unit; ul_parse("s^-1", &unit); printf("LaTeX: "); ul_print(&unit, UL_FMT_LATEX_FRAC, NULL); printf("\n"); } + { + const char *u = "1 mg"; + unit_t unit; + if (!ul_parse(u, &unit)) + printf("%s\n", ul_error()); + + printf("%s = ", u); + ul_print(&unit, UL_FMT_PLAIN, NULL); + printf("\n"); + } + ul_quit(); return 0; } #else void smashit(const char *str, bool asRule) { bool ok = true; if (asRule) { ok = ul_parse_rule(str); } else { unit_t u; ok = ul_parse(str, &u); } if (ok) { fprintf(stderr, "successfull?\n"); } else { fprintf(stderr, "error: %s\n", ul_error()); } } int main(void) { ul_init(); srand(time(NULL)); { fprintf(stderr, "Smash 1: "); char test[] = "dil^aöjf lkfjda gäklj#ä#jadf klnhöklj213jl^^- kjäjre"; smashit(test, false); fprintf(stderr, "Smash 2: "); smashit(test, true); } { size_t size = 4096; int *_test = malloc(size); int i=0; for (; i < size / sizeof(int); ++i) { _test[i] = rand(); } char *test = (char*)_test; for (i=0; i < size; ++i) { if (!test[i]) test[i] = 42; } fprintf(stderr, "%4d bytes garbage: ", size ); smashit(test, false); fprintf(stderr, "as rule: "); smashit(test, true); } { char test[] = " \t\t\n\n\r kg = "; printf("Evil: "); smashit(test, true); } { char test[] = "kg^2!"; printf("test: "); ul_debugging(true); smashit(test, false); } return 0; } #endif diff --git a/intern.h b/intern.h index 36bdc4f..65a0c1f 100644 --- a/intern.h +++ b/intern.h @@ -1,57 +1,57 @@ #ifndef UL_INTERN_H #define UL_INTERN_H #include <float.h> #include <math.h> #include "unitlib.h" extern const char *_ul_symbols[]; extern size_t _ul_symlens[]; extern bool _ul_debugging; UL_LINKAGE void _ul_debug(const char *fmt, ...); #define debug(fmt,...) \ do { \ if (_ul_debugging) _ul_debug("[ul - %s] " fmt "\n",\ __func__, ##__VA_ARGS__);\ } while(0) UL_LINKAGE void _ul_set_error(const char *func, int line, const char *fmt, ...); #define ERROR(msg, ...) _ul_set_error(__func__, __LINE__, msg, ##__VA_ARGS__) -UL_LINKAGE void _ul_init_rules(void); +UL_LINKAGE bool _ul_init_rules(void); UL_LINKAGE void _ul_free_rules(void); #define EXPS_SIZE(unit) (sizeof((unit)->exps[0]) * NUM_BASE_UNITS) static inline void init_unit(unit_t *unit) { memset(unit->exps, 0, EXPS_SIZE(unit)); unit->factor = 1.0; } static inline void copy_unit(const unit_t *restrict src, unit_t *restrict dst) { memcpy(dst->exps, src->exps, EXPS_SIZE(dst)); dst->factor = src->factor; } static inline void add_unit(unit_t *restrict to, const unit_t *restrict other, int times) { for (int i=0; i < NUM_BASE_UNITS; ++i) { to->exps[i] += (times * other->exps[i]); } to->factor *= _pown(other->factor, times); } static inline int ncmp(ul_number a, ul_number b) { if (_fabsn(a-b) < N_EPSILON) return 0; if (a < b) return -1; return 1; } #endif /*UL_INTERN_H*/ diff --git a/parser.c b/parser.c index b53dd19..6f5b7e3 100644 --- a/parser.c +++ b/parser.c @@ -1,443 +1,504 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" typedef struct rule { const char *symbol; unit_t unit; bool force; struct rule *next; } rule_t; // A list of all rules static rule_t *rules = NULL; // The base rules static rule_t base_rules[NUM_BASE_UNITS]; +static ul_number prefixes[256]; + #define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) struct parser_state { int sign; }; enum { MAX_SYM_SIZE = 128, MAX_ITEM_SIZE = 1024, }; // Returns the last rule in the list static rule_t *last_rule(void) { rule_t *cur = rules; while (cur) { if (!cur->next) return cur; cur = cur->next; } assert(false); return NULL; } static rule_t *get_rule(const char *sym) { assert(sym); for (rule_t *cur = rules; cur; cur = cur->next) { if (strcmp(cur->symbol, sym) == 0) return cur; } return NULL; } static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } static size_t nextspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !isspace(text[i])) i++; return i; } static bool try_parse_factor(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); char *endptr; ul_number f = _strton(str, &endptr); if (endptr && *endptr) { debug("'%s' is not a factor", str); return false; } unit->factor *= f; return true; } static bool is_special(const char *str) { assert(str); if (strlen(str) == 1) { switch (str[0]) { case '*': return true; case '/': return true; } } return false; } static bool handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); switch (str[0]) { case '*': // ignore return true; case '/': state->sign *= -1; return true; } ERROR("Internal error: is_special/handle_special missmatch for '%s'.", str); return false; } +static bool unit_and_prefix(const char *sym, unit_t **unit, ul_number *prefix) +{ + rule_t *rule = get_rule(sym); + if (rule) { + *unit = &rule->unit; + *prefix = 1.0; + return true; + } + + size_t p = (size_t)sym[0]; + debug("Got prefix: %c", (char)p); + if (prefixes[p] == 0.0) { + ERROR("Unknown symbol: '%s'", sym); + return false; + } + + rule = get_rule(sym + 1); + if (!rule) { + ERROR("Unknown symbol: '%s' with prefix %c", sym + 1, (char)p); + return false; + } + + *unit = &rule->unit; + *prefix = prefixes[p]; + return true; +} + static bool parse_item(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; size_t symend = 0; while (str[symend] && str[symend] != '^') symend++; if (symend >= MAX_SYM_SIZE) { ERROR("Symbol to long"); return false; } strncpy(symbol, str, symend); symbol[symend] = '\0'; if (str[symend]) { // The '^' should not be the last value of the string if (!str[symend+1]) { ERROR("Missing exponent after '^' while parsing '%s'", str); return false; } // Parse the exponent char *endptr = NULL; exp = strtol(str+symend+1, &endptr, 10); // the whole exp string was valid only if *endptr is '\0' if (endptr && *endptr) { ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); return false; } } debug("Exponent is %d", exp); - // Find the matching rule - rule_t *rule = get_rule(symbol); - if (!rule) { - ERROR("No matching rule found for '%s'", symbol); + unit_t *rule; + ul_number prefix; + if (!unit_and_prefix(symbol, &rule, &prefix)) return false; - } + + prefix = _pown(prefix, abs(exp)); // And add the definitions - add_unit(unit, &rule->unit, state->sign * exp); + add_unit(unit, rule, state->sign * exp); + unit->factor *= prefix; return true; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); struct parser_state state; state.sign = 1; init_unit(unit); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace size_t end = nextspace(str, start); if (end == start) {// End of string break; } // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; // and parse it if (is_special(this_item)) { if (!handle_special(this_item, &state)) return false; } else if (try_parse_factor(this_item, unit, &state)) { // nothing todo } else { if (!parse_item(this_item, unit, &state)) return false; } start = end + 1; } while (start < len); return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); for (size_t i=0; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } -UL_LINKAGE void _ul_init_rules(void) +static void init_prefixes(void) +{ + for (int i=0; i < 256; ++i) { + prefixes[i] = 0.0; + } + + prefixes['T'] = 1e12; // tera + prefixes['G'] = 1e9; // giga + prefixes['M'] = 1e6; // mega + prefixes['k'] = 1e3; // kilo + prefixes['h'] = 1e2; // hecto + // missing: da - deca + prefixes['d'] = 1e-1; // deci + prefixes['c'] = 1e-2; // centi + prefixes['m'] = 1e-3; // milli + prefixes['u'] = 1e-6; // micro + prefixes['n'] = 1e-9; // nano + prefixes['p'] = 1e-12; // pico +} + +UL_LINKAGE bool _ul_init_rules(void) { for (int i=0; i < NUM_BASE_UNITS; ++i) { base_rules[i].symbol = _ul_symbols[i]; init_unit(&base_rules[i].unit); base_rules[i].force = true; base_rules[i].unit.exps[i] = 1; base_rules[i].next = &base_rules[i+1]; } dynamic_rules = NULL; rules = base_rules; + + // stupid inconsistend SI system... + unit_t gram = { + {[U_KILOGRAM] = 1}, + 1e-3, + }; + if (!add_rule("g", &gram, true)) + return false; + + init_prefixes(); + return true; } UL_LINKAGE void _ul_free_rules(void) { debug("Freeing rule list"); rule_t *cur = dynamic_rules; while (cur) { rule_t *next = cur->next; free((char*)cur->symbol); free(cur); cur = next; } } diff --git a/unitlib.c b/unitlib.c index 0a599c3..2d64c50 100644 --- a/unitlib.c +++ b/unitlib.c @@ -1,185 +1,186 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" #define static_assert(e) extern char (*STATIC_ASSERT(void))[sizeof(char[1 - 2*!(e)])] #define sizeofarray(ar) (sizeof((ar))/sizeof((ar)[0])) static FILE *dbg_out = NULL; bool _ul_debugging = false; UL_LINKAGE void _ul_debug(const char *fmt, ...) { assert(dbg_out); va_list ap; va_start(ap, fmt); vfprintf(dbg_out, fmt, ap); va_end(ap); } const char *_ul_symbols[] = { "m", "kg", "s", "A", "K", "mol", "Cd", "L", }; static_assert(sizeofarray(_ul_symbols) == NUM_BASE_UNITS); // The last error message static char errmsg[1024]; UL_LINKAGE void _ul_set_error(const char *func, int line, const char *fmt, ...) { snprintf(errmsg, 1024, "[%s:%d] ", func, line); size_t len = strlen(errmsg); va_list ap; va_start(ap, fmt); vsnprintf(errmsg + len, 1024 - len, fmt, ap); va_end(ap); } UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b) { if (!a || !b) { ERROR("Invalid parameters"); return UL_ERROR; } int res = UL_SAME_UNIT; for (int i=0; i < NUM_BASE_UNITS; ++i) { if (a->exps[i] != b->exps[i]) { res = 0; break; } } if (ncmp(a->factor, b->factor) == 0) { res |= UL_SAME_FACTOR; } return res; } UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with) { if (!unit || !with) { ERROR("Invalid parameter"); return false; } add_unit(unit, with, 1); return true; } UL_API bool ul_mult(unit_t *unit, ul_number factor) { if (!unit) { ERROR("Invalid parameter"); return false; } unit->factor *= factor; return true; } UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src) { if (!dst || !src) { ERROR("Invalid parameter"); return false; } copy_unit(src, dst); return true; } UL_API bool ul_inverse(unit_t *unit) { if (!unit) { ERROR("Invalid parameter"); return false; } if (ncmp(unit->factor, 0.0) == 0) { ERROR("Cannot inverse 0.0"); return false; } for (int i=0; i < NUM_BASE_UNITS; ++i) { unit->exps[i] = -unit->exps[i]; } unit->factor = 1/unit->factor; return true; } UL_API bool ul_sqrt(unit_t *unit) { if (!unit) { ERROR("Invalid parameter"); return false; } for (int i=0; i < NUM_BASE_UNITS; ++i) { if ((unit->exps[i] % 2) != 0) { ERROR("Cannot take root of an odd exponent"); return false; } } for (int i=0; i < NUM_BASE_UNITS; ++i) { unit->exps[i] /= 2; } unit->factor = _sqrtn(unit->factor); return false; } UL_API void ul_debugging(bool flag) { _ul_debugging = flag; } UL_API void ul_debugout(const char *path, bool append) { if (dbg_out && dbg_out != stderr) { debug("New debug file: %s", path ? path : "stderr"); fclose(dbg_out); } if (!path) { dbg_out = stderr; } else { dbg_out = fopen(path, append ? "a" : "w"); if (!dbg_out) { dbg_out = stderr; debug("Failed to open '%s' as debugout, using stderr.", path); } } } UL_API const char *ul_error(void) { return errmsg; } UL_API bool ul_init(void) { if(!dbg_out) dbg_out = stderr; debug("Initializing base rules"); - _ul_init_rules(); + if (!_ul_init_rules()) + return false; const char *rulePath = getenv("UL_RULES"); if (rulePath) { debug("UL_RULES is set: %s", rulePath); if (!ul_load_rules(rulePath)) { ERROR("Failed to load rules: %s", errmsg); return false; } } return true; } UL_API void ul_quit(void) { _ul_free_rules(); if (dbg_out && dbg_out != stderr) fclose(dbg_out); }
jan-kuechler/unitlib
d206cc0eab070042240f08756b08c9d7c3ace6b5
Added c89 compatibility for programs that use unitlib, the library itself is still c99.
diff --git a/config.h b/config.h index 1dd0275..48c0d72 100644 --- a/config.h +++ b/config.h @@ -1,36 +1,46 @@ #ifndef UL_CONFIG_H #define UL_CONFIG_H /** * To support long double uncomment the following line */ //#define UL_HAS_LONG_DOUBLE // Don't change anything beyond this line //----------------------------------------------------------------------------- #ifdef UL_HAS_LONG_DOUBLE typedef long double ul_number; #define _strton strtold #define _fabsn fabsl #define _sqrtn sqrtl #define _pown pow #define N_FMT "%Lg" #define N_EPSILON LDBL_EPSILON #else typedef double ul_number; #define _strton strtod #define _fabsn fabs #define _sqrtn sqrt #define _pown powl #define N_FMT "%g" #define N_EPSILON DBL_EPSILON #endif +#ifdef __STDC_VERSION__ +#if (__STDC_VERSION__ == 199901L) +#define _HAS_C99 +#endif +#endif + +#ifndef _HAS_C99 +#define restrict +#endif + #endif /*UL_CONFIG_H*/
jan-kuechler/unitlib
16309a19cdb574bac56d744dbc3ea4c89eb43a04
Changed version to 0.3.
diff --git a/format.c b/format.c index 50e149f..2f90704 100644 --- a/format.c +++ b/format.c @@ -1,360 +1,359 @@ #include <assert.h> #include <stdio.h> #include <string.h> #include "intern.h" #include "unitlib.h" struct status { bool (*putc)(char c, void *info); void *info; const unit_t *unit; ul_format_t format; ul_fmtops_t *fmtp; void *extra; }; typedef bool (*printer_t)(struct status*,int,int,bool*); struct f_info { FILE *out; }; static bool f_putc(char c, void *i) { struct f_info *info = i; return fputc(c, info->out) == c; } struct sn_info { char *buffer; int idx; int size; }; static bool sn_putc(char c, void *i) { struct sn_info *info = i; if (info->idx >= info->size) { return false; } info->buffer[info->idx++] = c; return true; } #define _putc(s,c) (s)->putc((c),(s)->info) #define CHECK(x) do { if (!(x)) return false; } while (0) static bool _puts(struct status *s, const char *str) { while (*str) { char c = *str++; if (!_putc(s, c)) return false; } return true; } static bool _putd(struct status *stat, int n) { char buffer[1024]; snprintf(buffer, 1024, "%d", n); return _puts(stat, buffer); } static bool _putn(struct status *stat, ul_number n) { char buffer[1024]; snprintf(buffer, 1024, N_FMT, n); return _puts(stat, buffer); } static void getnexp(ul_number n, ul_number *mantissa, int *exp) { bool neg = false; if (n < 0) { neg = true; n = -n; } if ((ncmp(n, 10.0) == -1) && (ncmp(n, 1.0) == 1)) { *mantissa = neg ? -n : n; *exp = 0; return; } else if (ncmp(n, 10.0) > -1) { int e = 0; do { e++; n /= 10; } while (ncmp(n, 10.0) == 1); *exp = e; *mantissa = neg ? -n : n; } else if (ncmp(n, 1.0) < 1) { int e = 0; while (ncmp(n, 1.0) == -1) { e--; n *= 10; } *exp = e; *mantissa = neg ? -n : n; } } // global for testing purpose, it's not declared in the header void _ul_getnexp(ul_number n, ul_number *m, int *e) { getnexp(n, m, e); } static bool print_sorted(struct status *stat, printer_t func, bool *first) { bool printed[NUM_BASE_UNITS] = {0}; bool _first = true; bool *fptr = first ? first : &_first; // Print any sorted order for (int i=0; i < NUM_BASE_UNITS; ++i) { int unit = stat->fmtp->order[i]; if (unit == U_ANY) { break; } int exp = stat->unit->exps[unit]; CHECK(func(stat, unit, exp , fptr)); printed[unit] = true; } // Print the rest for (int i=0; i < NUM_BASE_UNITS; ++i) { if (!printed[i]) { int exp = stat->unit->exps[i]; if (exp != 0) { CHECK(func(stat, i, exp , fptr)); } } } return true; } static bool print_normal(struct status *stat, printer_t func, bool *first) { bool _first = true; bool *fptr = first ? first : &_first; for (int i=0; i < NUM_BASE_UNITS; ++i) { CHECK(func(stat,i,stat->unit->exps[i], fptr)); } return true; } // Begin - plain static bool _plain_one(struct status* stat, int unit, int exp, bool *first) { if (exp == 0) return true; if (!*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, _ul_symbols[unit])); // and the exponent if (exp != 1) { CHECK(_putc(stat, '^')); CHECK(_putd(stat, exp)); } *first = false; return true; } static bool p_plain(struct status *stat) { CHECK(_putn(stat, stat->unit->factor)); CHECK(_putc(stat, ' ')); if (stat->fmtp && stat->fmtp->sort) { return print_sorted(stat, _plain_one, NULL); } else { return print_normal(stat, _plain_one, NULL); } return true; } // End - plain // Begin - LaTeX static bool _latex_one(struct status *stat, int unit, int exp, bool *first) { if (exp == 0) return true; if (stat->extra) { bool pos = *(bool*)stat->extra; if (exp > 0 && !pos) return true; if (exp < 0) { if (pos) return true; exp = -exp; } } if (!*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, "\\text{")); if (!*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, _ul_symbols[unit])); CHECK(_puts(stat, "}")); if (exp != 1) { CHECK(_putc(stat, '^')); CHECK(_putc(stat, '{')); CHECK(_putd(stat, exp)); CHECK(_putc(stat, '}')); } *first = false; return true; } static bool p_latex_frac(struct status *stat) { bool first = true; bool positive = true; stat->extra = &positive; ul_number m; int e; getnexp(stat->unit->factor, &m, &e); CHECK(_puts(stat, "\\frac{")); if (e >= 0) { CHECK(_putn(stat, m)); if (e > 0) { CHECK(_puts(stat, " \\cdot 10^{")); CHECK(_putd(stat, e)); CHECK(_putc(stat, '}')); } first = false; } if (stat->fmtp && stat->fmtp->sort) { print_sorted(stat, _latex_one, &first); } else { print_normal(stat, _latex_one, &first); } if (first) { // nothing up there... CHECK(_putc(stat, '1')); } CHECK(_puts(stat, "}{")); first = true; positive = false; if (e < 0) { e = -e; CHECK(_putn(stat, m)); if (e > 0) { CHECK(_puts(stat, " \\cdot 10^{")); CHECK(_putd(stat, e)); CHECK(_putc(stat, '}')); } first = false; } if (stat->fmtp && stat->fmtp->sort) { print_sorted(stat, _latex_one, &first); } else { print_normal(stat, _latex_one, &first); } if (first) { CHECK(_putc(stat, '1')); } CHECK(_putc(stat, '}')); return true; } static bool p_latex_inline(struct status *stat) { bool first = false; CHECK(_putc(stat, '$')); ul_number m; int e; getnexp(stat->unit->factor, &m, &e); CHECK(_putn(stat, m)); if (e != 0) { CHECK(_puts(stat, " \\cdot 10^{")); CHECK(_putd(stat, e)); CHECK(_putc(stat, '}')); } for (int i=0; i < NUM_BASE_UNITS; ++i) { int exp = stat->unit->exps[i]; if (exp != 0) { CHECK(_latex_one(stat, i, exp, &first)); } } CHECK(_putc(stat, '$')); return true; } // End - LaTeX static bool _print(struct status *stat) { - debug("ignoring a factor of "N_FMT, stat->unit->factor); switch (stat->format) { case UL_FMT_PLAIN: return p_plain(stat); case UL_FMT_LATEX_FRAC: return p_latex_frac(stat); case UL_FMT_LATEX_INLINE: return p_latex_inline(stat); default: ERROR("Unknown format: %d", stat->format); return false; } } UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) { struct f_info info = { .out = f, }; struct status status = { .putc = f_putc, .info = &info, .unit = unit, .format = format, .fmtp = fmtp, .extra = NULL, }; return _print(&status); } UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) { struct sn_info info = { .buffer = buffer, .size = buflen, .idx = 0, }; struct status status = { .putc = sn_putc, .info = &info, .unit = unit, .format = format, .fmtp = fmtp, .extra = NULL, }; memset(buffer, 0, buflen); return _print(&status); } diff --git a/unitlib.h b/unitlib.h index e5390fb..3a4d94d 100644 --- a/unitlib.h +++ b/unitlib.h @@ -1,229 +1,229 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "config.h" #define UL_NAME "unitlib" -#define UL_VERSION "0.3b1" +#define UL_VERSION "0.3" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif #if defined(UL_EXPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllexport) #elif defined(UL_IMPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllimport) #else #define UL_API UL_LINKAGE #endif typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; #define U_ANY -1 typedef enum ul_format { UL_FMT_PLAIN, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, } ul_format_t; typedef enum ul_cmpres { UL_ERROR = 0x00, UL_SAME_UNIT = 0x01, UL_SAME_FACTOR = 0x02, UL_EQUAL = 0x03, } ul_cmpres_t; typedef struct ul_format_ops { bool sort; int order[NUM_BASE_UNITS]; } ul_fmtops_t; typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** * Deinitializes the unitlib and frees all. This function * has to be called at the end of the program. * internals resources. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); /** * Returns the factor of a unit * @param unit The unit * @return The factor */ static inline ul_number ul_factor(const unit_t *unit) { if (!unit) return 0.0; return unit->factor; } /** * Compares two units * @param a A unit * @param b Another unit * @return Compare result */ UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b); /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ static inline bool ul_equal(const unit_t *a, const unit_t *b) { return ul_cmp(a, b) == UL_EQUAL; } /** * Copies a unit into another * @param dst Destination unit * @param src Source unit * @return success */ UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src); /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with); /** * Multiplies a unit with a factor * @param unit The unit * @param factor The factor * @return success */ UL_API bool ul_mult(unit_t *unit, ul_number factor); /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ static inline bool ul_print(const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) { return ul_fprint(stdout, unit, format, fmtp); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); #endif /*UNITLIB_H*/ diff --git a/unittest.c b/unittest.c index c576098..2743bb7 100644 --- a/unittest.c +++ b/unittest.c @@ -1,458 +1,468 @@ #ifndef GET_TEST_DEFS #include <stdarg.h> #include <stdlib.h> #include <string.h> #include "unitlib.h" #include "intern.h" // yay, self include (-: #define GET_TEST_DEFS #include "unittest.c" #undef GET_TEST_DEFS static unit_t make_unit(ul_number fac, ...) { va_list args; va_start(args, fac); unit_t u; memset(u.exps, 0, NUM_BASE_UNITS * sizeof(int)); u.factor = fac; int b = va_arg(args, int); int e = va_arg(args, int); while (b || e) { u.exps[b] = e; b = va_arg(args, int); e = va_arg(args, int); } return u; } #define MAKE_UNIT(...) make_unit(__VA_ARGS__,0,0,0) TEST_SUITE(parser) TEST unit_t u; CHECK(ul_parse("m", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_METER] == 1); int i=0; for (; i < NUM_BASE_UNITS; ++i) { if (i != U_METER) { CHECK(u.exps[i] == 0); } } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; CHECK(ul_parse(" \n kg^2 * m ", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_KILOGRAM] == 2); CHECK(u.exps[U_METER] == 1); CHECK(u.exps[U_SECOND] == 0); CHECK(ncmp(u.factor, 1.0) == 0); CHECK(ul_parse("2 Cd 7 s^-1", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_CANDELA] == 1); CHECK(u.exps[U_SECOND] == -1); CHECK(ncmp(u.factor, 14.0) == 0); CHECK(ul_parse("", &u)); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; const char *strings[] = { "5*kg^2", // need whitespace "5 ** kg^2", // double * "5! * kg^2", // ! "5 * kg^2!", // ! NULL }; int i = 0; while (strings[i]) { CHECK(ul_parse(strings[i], &u) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST const char *strings[] = { "", // empty rule " =", // empty symbol "16 = 16", // invalid rule " a b = s ", // invalid symbol " c == kg", // double = "d = e", // unknown 'e' " = kg", // empty symbol NULL, }; int i=0; while (strings[i]) { CHECK(ul_parse_rule(strings[i]) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST // Empty rules are allowed CHECK(ul_parse_rule("EmptySymbol = ")); FAIL_MSG("Error: %s", ul_error()); unit_t u; CHECK(ul_parse("EmptySymbol", &u)); FAIL_MSG("Error: %s", ul_error()); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; CHECK(ul_parse(NULL, NULL) == false); CHECK(ul_parse(NULL, &u) == false); CHECK(ul_parse("kg", NULL) == false); CHECK(ul_parse_rule(NULL) == false); CHECK(ul_parse_rule("") == false); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t s = MAKE_UNIT(1.0, U_SECOND, 1); unit_t u; CHECK(ul_parse_rule("!ForcedRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("ForcedRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("NewRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("!NewRule = s")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); CHECK(ul_equal(&s, &u)); CHECK(ul_parse_rule("!NewRule = m") == false); CHECK(ul_parse_rule("!kg = kg") == false); CHECK(ul_parse_rule(" Recurse = m")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse_rule("!Recurse = Recurse") == false); END_TEST END_TEST_SUITE() TEST_SUITE(core) TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t kg2 = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_equal(&kg, &kg2)); kg2.factor = 2.0; CHECK(!ul_equal(&kg, &kg2)); kg2.factor = 1.0; CHECK(ul_equal(&kg, &kg2)); kg2.exps[U_KILOGRAM]++; CHECK(!ul_equal(&kg, &kg2)); unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); CHECK(!ul_equal(&kg, &N)); END_TEST TEST unit_t a = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t b; CHECK(ul_copy(&b, &a)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&b, &a)); CHECK(!ul_copy(NULL, NULL)); CHECK(!ul_copy(&a, NULL)); CHECK(!ul_copy(NULL, &a)); END_TEST TEST unit_t a = MAKE_UNIT(2.0, U_KILOGRAM, 1); unit_t b = MAKE_UNIT(3.0, U_SECOND, -2); unit_t res; CHECK(ul_copy(&res, &a)); FAIL_MSG("Preparation failed: %s", ul_error()); CHECK(ul_combine(&res, &b)); FAIL_MSG("Error: %s", ul_error()); unit_t correct = MAKE_UNIT(6.0, U_KILOGRAM, 1, U_SECOND, -2); CHECK(ul_equal(&res, &correct)); END_TEST END_TEST_SUITE() TEST_SUITE(format) TEST extern void _ul_getnexp(ul_number n, ul_number *m, int *e); ul_number m; int e; _ul_getnexp(1.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1.0, &m, &e); CHECK(ncmp(m, -1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(11.0, &m, &e); CHECK(ncmp(m, 1.1) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e);; _ul_getnexp(9.81, &m, &e); CHECK(ncmp(m, 9.81) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1234, &m, &e); CHECK(ncmp(m, -1.234) == 0); FAIL_MSG("m == %g", m); CHECK(e == 3); FAIL_MSG("e == %d", e); _ul_getnexp(10.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); _ul_getnexp(0.01, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == -2); FAIL_MSG("e == %d", e); _ul_getnexp(0.99, &m, &e); CHECK(ncmp(m, 9.9) == 0); FAIL_MSG("m == %g", m); CHECK(e == -1); FAIL_MSG("e == %d", e); _ul_getnexp(10.01, &m, &e); CHECK(ncmp(m, 1.001) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); kg.factor = 1.5; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1.5 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); kg.factor = -1.0; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "-1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 m kg s^-2") == 0); FAIL_MSG("buffer: '%s'", buffer); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$1 \\text{ m} \\text{ kg} \\text{ s}^{-2}$") == 0); FAIL_MSG("buffer: '%s'", buffer); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "\\frac{1 \\text{ m} \\text{ kg}}{\\text{s}^{2}}") == 0); FAIL_MSG("buffer: '%s'", buffer); END_TEST + + TEST + unit_t zeroKg = MAKE_UNIT(0.0, U_KILOGRAM, 1); + + char buffer[128]; + CHECK(ul_snprint(buffer, 128, &zeroKg, UL_FMT_PLAIN, NULL)); + FAIL_MSG("Error: %s", ul_error()); + CHECK(strcmp(buffer, "0 kg") == 0); + FAIL_MSG("buffer: '%s'", buffer); + END_TEST END_TEST_SUITE() int main(void) { ul_debugging(false); if (!ul_init()) { printf("ul_init failed: %s", ul_error()); return 1; } INIT_TEST(); SET_LOGLVL(L_NORMAL); RUN_SUITE(core); RUN_SUITE(parser); RUN_SUITE(format); ul_quit(); return TEST_RESULT; } #endif /*ndef GET_TEST_DEFS*/ //################################################################################################# #ifdef GET_TEST_DEFS #define PRINT(o, lvl, ...) do { if ((o)->loglvl >= lvl) printf(__VA_ARGS__); } while (0) #define CHECK(expr) \ do { \ int _this = ++_cid; \ if (!(expr)) { \ _err++; _fail++; \ PRINT(_o, L_NORMAL, "[%s-%d-%d] Fail: '%s'\n", _name, _id, _this, #expr); \ _last = false;\ } \ else { \ PRINT(_o, L_VERBOSE, "[%s-%d-%d] Pass: '%s'\n", _name, _id, _this, #expr); \ _last = true; \ } \ } while (0) #define FAIL_MSG(msg, ...) \ do {if (!_last) PRINT(_o,L_NORMAL,msg"\n", ##__VA_ARGS__); } while (0) #define PASS_MSG(msg, ...) \ do {if (_last) PRINT(_o,L_VERBOSE,msg"\n", ##__VA_ARGS__); } while (0) #define INFO(fmt, ...) \ do { printf("* " fmt "\n", ##__VA_ARGS__); } while (0) // TEST SUITE #define TEST_SUITE(name) \ int _test_##name(_tops *_o) { \ const char *_name = #name; \ int _fail = 0; \ int _test_id = 0; \ #define END_TEST_SUITE() \ return _fail; } // SINGLE TEST #define TEST \ { int _id = ++_test_id; int _err = 0; int _cid = 0; bool _last = true; \ #define END_TEST \ if (_err > 0) { \ PRINT(_o, L_NORMAL, "[%s-%d] failed with %d error%s.\n", _name, _id, _err, _err > 1 ? "s" : ""); \ } \ else { \ PRINT(_o, L_NORMAL, "[%s-%d] passed.\n", _name, _id); \ } \ } // OTHER typedef struct { int loglvl; } _tops; enum { L_QUIET = 0, L_RESULT = 1, L_NORMAL = 2, L_VERBOSE = 3, L_ALL = 4, }; static inline int _run_suite(int (*suite)(_tops*), const char *name, _tops *o) { int num_errs = suite(o); if (num_errs == 0) { PRINT(o, L_RESULT, "[%s] passed.\n", name); } else { PRINT(o, L_RESULT, "[%s] failed with %d error%s.\n", name, num_errs, num_errs > 1 ? "s" : ""); } return num_errs; } #define INIT_TEST() \ _tops _ops; int _tres = 0; #define SET_LOGLVL(lvl) \ _ops.loglvl = (lvl); #define RUN_SUITE(name) \ _tres += _run_suite(_test_##name, #name, &_ops) #define TEST_RESULT _tres #endif /* GET_TEST_DEFS*/
jan-kuechler/unitlib
b679345a87cbacb47bb1c09d8063e7b40bbb3215
Added ul_mult(unit,factor) to multiply a unit with a factor.
diff --git a/unitlib.c b/unitlib.c index f9a7def..0a599c3 100644 --- a/unitlib.c +++ b/unitlib.c @@ -1,175 +1,185 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" #define static_assert(e) extern char (*STATIC_ASSERT(void))[sizeof(char[1 - 2*!(e)])] #define sizeofarray(ar) (sizeof((ar))/sizeof((ar)[0])) static FILE *dbg_out = NULL; bool _ul_debugging = false; UL_LINKAGE void _ul_debug(const char *fmt, ...) { assert(dbg_out); va_list ap; va_start(ap, fmt); vfprintf(dbg_out, fmt, ap); va_end(ap); } const char *_ul_symbols[] = { "m", "kg", "s", "A", "K", "mol", "Cd", "L", }; static_assert(sizeofarray(_ul_symbols) == NUM_BASE_UNITS); // The last error message static char errmsg[1024]; UL_LINKAGE void _ul_set_error(const char *func, int line, const char *fmt, ...) { snprintf(errmsg, 1024, "[%s:%d] ", func, line); size_t len = strlen(errmsg); va_list ap; va_start(ap, fmt); vsnprintf(errmsg + len, 1024 - len, fmt, ap); va_end(ap); } UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b) { if (!a || !b) { ERROR("Invalid parameters"); return UL_ERROR; } int res = UL_SAME_UNIT; for (int i=0; i < NUM_BASE_UNITS; ++i) { if (a->exps[i] != b->exps[i]) { res = 0; break; } } if (ncmp(a->factor, b->factor) == 0) { res |= UL_SAME_FACTOR; } return res; } UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with) { if (!unit || !with) { ERROR("Invalid parameter"); return false; } add_unit(unit, with, 1); return true; } +UL_API bool ul_mult(unit_t *unit, ul_number factor) +{ + if (!unit) { + ERROR("Invalid parameter"); + return false; + } + unit->factor *= factor; + return true; +} + UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src) { if (!dst || !src) { ERROR("Invalid parameter"); return false; } copy_unit(src, dst); return true; } UL_API bool ul_inverse(unit_t *unit) { if (!unit) { ERROR("Invalid parameter"); return false; } if (ncmp(unit->factor, 0.0) == 0) { ERROR("Cannot inverse 0.0"); return false; } for (int i=0; i < NUM_BASE_UNITS; ++i) { unit->exps[i] = -unit->exps[i]; } unit->factor = 1/unit->factor; return true; } UL_API bool ul_sqrt(unit_t *unit) { if (!unit) { ERROR("Invalid parameter"); return false; } for (int i=0; i < NUM_BASE_UNITS; ++i) { if ((unit->exps[i] % 2) != 0) { ERROR("Cannot take root of an odd exponent"); return false; } } for (int i=0; i < NUM_BASE_UNITS; ++i) { unit->exps[i] /= 2; } unit->factor = _sqrtn(unit->factor); return false; } UL_API void ul_debugging(bool flag) { _ul_debugging = flag; } UL_API void ul_debugout(const char *path, bool append) { if (dbg_out && dbg_out != stderr) { debug("New debug file: %s", path ? path : "stderr"); fclose(dbg_out); } if (!path) { dbg_out = stderr; } else { dbg_out = fopen(path, append ? "a" : "w"); if (!dbg_out) { dbg_out = stderr; debug("Failed to open '%s' as debugout, using stderr.", path); } } } UL_API const char *ul_error(void) { return errmsg; } UL_API bool ul_init(void) { if(!dbg_out) dbg_out = stderr; debug("Initializing base rules"); _ul_init_rules(); const char *rulePath = getenv("UL_RULES"); if (rulePath) { debug("UL_RULES is set: %s", rulePath); if (!ul_load_rules(rulePath)) { ERROR("Failed to load rules: %s", errmsg); return false; } } return true; } UL_API void ul_quit(void) { _ul_free_rules(); if (dbg_out && dbg_out != stderr) fclose(dbg_out); } diff --git a/unitlib.h b/unitlib.h index 5f1f994..e5390fb 100644 --- a/unitlib.h +++ b/unitlib.h @@ -1,221 +1,229 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "config.h" #define UL_NAME "unitlib" #define UL_VERSION "0.3b1" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif #if defined(UL_EXPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllexport) #elif defined(UL_IMPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllimport) #else #define UL_API UL_LINKAGE #endif typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; #define U_ANY -1 typedef enum ul_format { UL_FMT_PLAIN, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, } ul_format_t; typedef enum ul_cmpres { UL_ERROR = 0x00, UL_SAME_UNIT = 0x01, UL_SAME_FACTOR = 0x02, UL_EQUAL = 0x03, } ul_cmpres_t; typedef struct ul_format_ops { bool sort; int order[NUM_BASE_UNITS]; } ul_fmtops_t; typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** * Deinitializes the unitlib and frees all. This function * has to be called at the end of the program. * internals resources. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); /** * Returns the factor of a unit * @param unit The unit * @return The factor */ static inline ul_number ul_factor(const unit_t *unit) { if (!unit) return 0.0; return unit->factor; } /** * Compares two units * @param a A unit * @param b Another unit * @return Compare result */ UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b); /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ static inline bool ul_equal(const unit_t *a, const unit_t *b) { return ul_cmp(a, b) == UL_EQUAL; } /** * Copies a unit into another * @param dst Destination unit * @param src Source unit * @return success */ UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src); /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with); +/** + * Multiplies a unit with a factor + * @param unit The unit + * @param factor The factor + * @return success + */ +UL_API bool ul_mult(unit_t *unit, ul_number factor); + /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ static inline bool ul_print(const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) { return ul_fprint(stdout, unit, format, fmtp); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); #endif /*UNITLIB_H*/
jan-kuechler/unitlib
b0acec019d0781ef02278e97f7f30ec553f52184
Added functions: ul_cmp and ul_factor.
diff --git a/unitlib.c b/unitlib.c index 863dcfe..f9a7def 100644 --- a/unitlib.c +++ b/unitlib.c @@ -1,169 +1,175 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" #define static_assert(e) extern char (*STATIC_ASSERT(void))[sizeof(char[1 - 2*!(e)])] #define sizeofarray(ar) (sizeof((ar))/sizeof((ar)[0])) static FILE *dbg_out = NULL; bool _ul_debugging = false; UL_LINKAGE void _ul_debug(const char *fmt, ...) { assert(dbg_out); va_list ap; va_start(ap, fmt); vfprintf(dbg_out, fmt, ap); va_end(ap); } const char *_ul_symbols[] = { "m", "kg", "s", "A", "K", "mol", "Cd", "L", }; static_assert(sizeofarray(_ul_symbols) == NUM_BASE_UNITS); // The last error message static char errmsg[1024]; UL_LINKAGE void _ul_set_error(const char *func, int line, const char *fmt, ...) { snprintf(errmsg, 1024, "[%s:%d] ", func, line); size_t len = strlen(errmsg); va_list ap; va_start(ap, fmt); vsnprintf(errmsg + len, 1024 - len, fmt, ap); va_end(ap); } -UL_API bool ul_equal(const unit_t *a, const unit_t *b) +UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b) { if (!a || !b) { ERROR("Invalid parameters"); - return false; + return UL_ERROR; } + int res = UL_SAME_UNIT; for (int i=0; i < NUM_BASE_UNITS; ++i) { - if (a->exps[i] != b->exps[i]) - return false; + if (a->exps[i] != b->exps[i]) { + res = 0; + break; + } + } + if (ncmp(a->factor, b->factor) == 0) { + res |= UL_SAME_FACTOR; } - return ncmp(a->factor, b->factor) == 0; + return res; } UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with) { if (!unit || !with) { ERROR("Invalid parameter"); return false; } add_unit(unit, with, 1); return true; } UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src) { if (!dst || !src) { ERROR("Invalid parameter"); return false; } copy_unit(src, dst); return true; } UL_API bool ul_inverse(unit_t *unit) { if (!unit) { ERROR("Invalid parameter"); return false; } if (ncmp(unit->factor, 0.0) == 0) { ERROR("Cannot inverse 0.0"); return false; } for (int i=0; i < NUM_BASE_UNITS; ++i) { unit->exps[i] = -unit->exps[i]; } unit->factor = 1/unit->factor; return true; } UL_API bool ul_sqrt(unit_t *unit) { if (!unit) { ERROR("Invalid parameter"); return false; } for (int i=0; i < NUM_BASE_UNITS; ++i) { if ((unit->exps[i] % 2) != 0) { ERROR("Cannot take root of an odd exponent"); return false; } } for (int i=0; i < NUM_BASE_UNITS; ++i) { unit->exps[i] /= 2; } unit->factor = _sqrtn(unit->factor); return false; } UL_API void ul_debugging(bool flag) { _ul_debugging = flag; } UL_API void ul_debugout(const char *path, bool append) { if (dbg_out && dbg_out != stderr) { debug("New debug file: %s", path ? path : "stderr"); fclose(dbg_out); } if (!path) { dbg_out = stderr; } else { dbg_out = fopen(path, append ? "a" : "w"); if (!dbg_out) { dbg_out = stderr; debug("Failed to open '%s' as debugout, using stderr.", path); } } } UL_API const char *ul_error(void) { return errmsg; } UL_API bool ul_init(void) { if(!dbg_out) dbg_out = stderr; debug("Initializing base rules"); _ul_init_rules(); const char *rulePath = getenv("UL_RULES"); if (rulePath) { debug("UL_RULES is set: %s", rulePath); if (!ul_load_rules(rulePath)) { ERROR("Failed to load rules: %s", errmsg); return false; } } return true; } UL_API void ul_quit(void) { _ul_free_rules(); if (dbg_out && dbg_out != stderr) fclose(dbg_out); } diff --git a/unitlib.h b/unitlib.h index 89b8e9e..5f1f994 100644 --- a/unitlib.h +++ b/unitlib.h @@ -1,190 +1,221 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "config.h" #define UL_NAME "unitlib" #define UL_VERSION "0.3b1" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif #if defined(UL_EXPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllexport) #elif defined(UL_IMPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllimport) #else #define UL_API UL_LINKAGE #endif typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; #define U_ANY -1 typedef enum ul_format { UL_FMT_PLAIN, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, } ul_format_t; +typedef enum ul_cmpres +{ + UL_ERROR = 0x00, + UL_SAME_UNIT = 0x01, + UL_SAME_FACTOR = 0x02, + UL_EQUAL = 0x03, +} ul_cmpres_t; + typedef struct ul_format_ops { bool sort; int order[NUM_BASE_UNITS]; } ul_fmtops_t; typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** * Deinitializes the unitlib and frees all. This function * has to be called at the end of the program. * internals resources. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); +/** + * Returns the factor of a unit + * @param unit The unit + * @return The factor + */ +static inline ul_number ul_factor(const unit_t *unit) +{ + if (!unit) + return 0.0; + return unit->factor; +} + +/** + * Compares two units + * @param a A unit + * @param b Another unit + * @return Compare result + */ +UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b); + /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ -UL_API bool ul_equal(const unit_t *a, const unit_t *b); +static inline bool ul_equal(const unit_t *a, const unit_t *b) +{ + return ul_cmp(a, b) == UL_EQUAL; +} /** * Copies a unit into another * @param dst Destination unit * @param src Source unit * @return success */ UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src); /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with); /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ static inline bool ul_print(const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) { return ul_fprint(stdout, unit, format, fmtp); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); #endif /*UNITLIB_H*/
jan-kuechler/unitlib
3e6cc02d9b743cc2d5e7318e35691d7056bb3092
Some format changes.
diff --git a/format.c b/format.c index 35c160c..50e149f 100644 --- a/format.c +++ b/format.c @@ -1,362 +1,360 @@ #include <assert.h> #include <stdio.h> #include <string.h> #include "intern.h" #include "unitlib.h" struct status { bool (*putc)(char c, void *info); void *info; const unit_t *unit; ul_format_t format; ul_fmtops_t *fmtp; void *extra; }; typedef bool (*printer_t)(struct status*,int,int,bool*); struct f_info { FILE *out; }; static bool f_putc(char c, void *i) { struct f_info *info = i; return fputc(c, info->out) == c; } struct sn_info { char *buffer; int idx; int size; }; static bool sn_putc(char c, void *i) { struct sn_info *info = i; if (info->idx >= info->size) { return false; } info->buffer[info->idx++] = c; return true; } #define _putc(s,c) (s)->putc((c),(s)->info) #define CHECK(x) do { if (!(x)) return false; } while (0) static bool _puts(struct status *s, const char *str) { while (*str) { char c = *str++; if (!_putc(s, c)) return false; } return true; } static bool _putd(struct status *stat, int n) { char buffer[1024]; snprintf(buffer, 1024, "%d", n); return _puts(stat, buffer); } static bool _putn(struct status *stat, ul_number n) { char buffer[1024]; snprintf(buffer, 1024, N_FMT, n); return _puts(stat, buffer); } static void getnexp(ul_number n, ul_number *mantissa, int *exp) { bool neg = false; if (n < 0) { neg = true; n = -n; } if ((ncmp(n, 10.0) == -1) && (ncmp(n, 1.0) == 1)) { *mantissa = neg ? -n : n; *exp = 0; return; } else if (ncmp(n, 10.0) > -1) { int e = 0; do { e++; n /= 10; } while (ncmp(n, 10.0) == 1); *exp = e; *mantissa = neg ? -n : n; } else if (ncmp(n, 1.0) < 1) { int e = 0; while (ncmp(n, 1.0) == -1) { e--; n *= 10; } *exp = e; *mantissa = neg ? -n : n; } } // global for testing purpose, it's not declared in the header void _ul_getnexp(ul_number n, ul_number *m, int *e) { getnexp(n, m, e); } static bool print_sorted(struct status *stat, printer_t func, bool *first) { bool printed[NUM_BASE_UNITS] = {0}; bool _first = true; bool *fptr = first ? first : &_first; // Print any sorted order for (int i=0; i < NUM_BASE_UNITS; ++i) { int unit = stat->fmtp->order[i]; if (unit == U_ANY) { break; } int exp = stat->unit->exps[unit]; CHECK(func(stat, unit, exp , fptr)); printed[unit] = true; } // Print the rest for (int i=0; i < NUM_BASE_UNITS; ++i) { if (!printed[i]) { int exp = stat->unit->exps[i]; if (exp != 0) { CHECK(func(stat, i, exp , fptr)); } } } return true; } static bool print_normal(struct status *stat, printer_t func, bool *first) { bool _first = true; bool *fptr = first ? first : &_first; for (int i=0; i < NUM_BASE_UNITS; ++i) { CHECK(func(stat,i,stat->unit->exps[i], fptr)); } return true; } // Begin - plain static bool _plain_one(struct status* stat, int unit, int exp, bool *first) { if (exp == 0) return true; if (!*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, _ul_symbols[unit])); // and the exponent if (exp != 1) { CHECK(_putc(stat, '^')); CHECK(_putd(stat, exp)); } *first = false; return true; } static bool p_plain(struct status *stat) { CHECK(_putn(stat, stat->unit->factor)); CHECK(_putc(stat, ' ')); if (stat->fmtp && stat->fmtp->sort) { return print_sorted(stat, _plain_one, NULL); } else { return print_normal(stat, _plain_one, NULL); } return true; } // End - plain // Begin - LaTeX static bool _latex_one(struct status *stat, int unit, int exp, bool *first) { if (exp == 0) return true; if (stat->extra) { bool pos = *(bool*)stat->extra; if (exp > 0 && !pos) return true; if (exp < 0) { if (pos) return true; exp = -exp; } } if (!*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, "\\text{")); if (!*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, _ul_symbols[unit])); CHECK(_puts(stat, "}")); if (exp != 1) { CHECK(_putc(stat, '^')); CHECK(_putc(stat, '{')); CHECK(_putd(stat, exp)); CHECK(_putc(stat, '}')); } *first = false; return true; } static bool p_latex_frac(struct status *stat) { bool first = true; bool positive = true; stat->extra = &positive; ul_number m; int e; getnexp(stat->unit->factor, &m, &e); CHECK(_puts(stat, "\\frac{")); if (e >= 0) { CHECK(_putn(stat, m)); if (e > 0) { CHECK(_puts(stat, " \\cdot 10^{")); CHECK(_putd(stat, e)); CHECK(_putc(stat, '}')); } first = false; } if (stat->fmtp && stat->fmtp->sort) { print_sorted(stat, _latex_one, &first); } else { print_normal(stat, _latex_one, &first); } if (first) { // nothing up there... CHECK(_putc(stat, '1')); } CHECK(_puts(stat, "}{")); first = true; positive = false; if (e < 0) { e = -e; CHECK(_putn(stat, m)); if (e > 0) { CHECK(_puts(stat, " \\cdot 10^{")); CHECK(_putd(stat, e)); CHECK(_putc(stat, '}')); } first = false; } if (stat->fmtp && stat->fmtp->sort) { print_sorted(stat, _latex_one, &first); } else { print_normal(stat, _latex_one, &first); } if (first) { CHECK(_putc(stat, '1')); } CHECK(_putc(stat, '}')); return true; } static bool p_latex_inline(struct status *stat) { bool first = false; CHECK(_putc(stat, '$')); ul_number m; int e; getnexp(stat->unit->factor, &m, &e); CHECK(_putn(stat, m)); if (e != 0) { CHECK(_puts(stat, " \\cdot 10^{")); CHECK(_putd(stat, e)); CHECK(_putc(stat, '}')); } for (int i=0; i < NUM_BASE_UNITS; ++i) { int exp = stat->unit->exps[i]; if (exp != 0) { CHECK(_latex_one(stat, i, exp, &first)); } } CHECK(_putc(stat, '$')); return true; } // End - LaTeX static bool _print(struct status *stat) { debug("ignoring a factor of "N_FMT, stat->unit->factor); switch (stat->format) { case UL_FMT_PLAIN: return p_plain(stat); case UL_FMT_LATEX_FRAC: return p_latex_frac(stat); case UL_FMT_LATEX_INLINE: return p_latex_inline(stat); default: ERROR("Unknown format: %d", stat->format); return false; } } -UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, - ul_fmtops_t *fmtp) +UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) { struct f_info info = { .out = f, }; struct status status = { .putc = f_putc, .info = &info, .unit = unit, .format = format, .fmtp = fmtp, .extra = NULL, }; return _print(&status); } -UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, - ul_format_t format, ul_fmtops_t *fmtp) +UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) { struct sn_info info = { .buffer = buffer, .size = buflen, .idx = 0, }; struct status status = { .putc = sn_putc, .info = &info, .unit = unit, .format = format, .fmtp = fmtp, .extra = NULL, }; memset(buffer, 0, buflen); return _print(&status); } diff --git a/parser.c b/parser.c index 8ef87e7..b53dd19 100644 --- a/parser.c +++ b/parser.c @@ -1,444 +1,443 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" typedef struct rule { const char *symbol; unit_t unit; bool force; struct rule *next; } rule_t; // A list of all rules static rule_t *rules = NULL; // The base rules static rule_t base_rules[NUM_BASE_UNITS]; #define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) struct parser_state { int sign; }; enum { MAX_SYM_SIZE = 128, MAX_ITEM_SIZE = 1024, }; // Returns the last rule in the list static rule_t *last_rule(void) { rule_t *cur = rules; while (cur) { if (!cur->next) return cur; cur = cur->next; } assert(false); return NULL; } static rule_t *get_rule(const char *sym) { assert(sym); for (rule_t *cur = rules; cur; cur = cur->next) { if (strcmp(cur->symbol, sym) == 0) return cur; } return NULL; } static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } static size_t nextspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !isspace(text[i])) i++; return i; } -static bool try_parse_factor(const char *str, unit_t *unit, - struct parser_state *state) +static bool try_parse_factor(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); char *endptr; ul_number f = _strton(str, &endptr); if (endptr && *endptr) { debug("'%s' is not a factor", str); return false; } unit->factor *= f; return true; } static bool is_special(const char *str) { assert(str); if (strlen(str) == 1) { switch (str[0]) { case '*': return true; case '/': return true; } } return false; } static bool handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); switch (str[0]) { case '*': // ignore return true; case '/': state->sign *= -1; return true; } ERROR("Internal error: is_special/handle_special missmatch for '%s'.", str); return false; } static bool parse_item(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; size_t symend = 0; while (str[symend] && str[symend] != '^') symend++; if (symend >= MAX_SYM_SIZE) { ERROR("Symbol to long"); return false; } strncpy(symbol, str, symend); symbol[symend] = '\0'; if (str[symend]) { // The '^' should not be the last value of the string if (!str[symend+1]) { ERROR("Missing exponent after '^' while parsing '%s'", str); return false; } // Parse the exponent char *endptr = NULL; exp = strtol(str+symend+1, &endptr, 10); // the whole exp string was valid only if *endptr is '\0' if (endptr && *endptr) { ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); return false; } } debug("Exponent is %d", exp); // Find the matching rule rule_t *rule = get_rule(symbol); if (!rule) { ERROR("No matching rule found for '%s'", symbol); return false; } // And add the definitions add_unit(unit, &rule->unit, state->sign * exp); return true; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); struct parser_state state; state.sign = 1; init_unit(unit); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace size_t end = nextspace(str, start); if (end == start) {// End of string break; } // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; // and parse it if (is_special(this_item)) { if (!handle_special(this_item, &state)) return false; } else if (try_parse_factor(this_item, unit, &state)) { // nothing todo } else { if (!parse_item(this_item, unit, &state)) return false; } start = end + 1; } while (start < len); return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); for (size_t i=0; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } UL_LINKAGE void _ul_init_rules(void) { for (int i=0; i < NUM_BASE_UNITS; ++i) { base_rules[i].symbol = _ul_symbols[i]; init_unit(&base_rules[i].unit); base_rules[i].force = true; base_rules[i].unit.exps[i] = 1; base_rules[i].next = &base_rules[i+1]; } dynamic_rules = NULL; rules = base_rules; } UL_LINKAGE void _ul_free_rules(void) { debug("Freeing rule list"); rule_t *cur = dynamic_rules; while (cur) { rule_t *next = cur->next; free((char*)cur->symbol); free(cur); cur = next; } } diff --git a/unitlib.h b/unitlib.h index b2b5bc7..89b8e9e 100644 --- a/unitlib.h +++ b/unitlib.h @@ -1,193 +1,190 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "config.h" #define UL_NAME "unitlib" #define UL_VERSION "0.3b1" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif #if defined(UL_EXPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllexport) #elif defined(UL_IMPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllimport) #else #define UL_API UL_LINKAGE #endif typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; #define U_ANY -1 typedef enum ul_format { UL_FMT_PLAIN, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, } ul_format_t; typedef struct ul_format_ops { bool sort; int order[NUM_BASE_UNITS]; } ul_fmtops_t; typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** * Deinitializes the unitlib and frees all. This function * has to be called at the end of the program. * internals resources. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ UL_API bool ul_equal(const unit_t *a, const unit_t *b); /** * Copies a unit into another * @param dst Destination unit * @param src Source unit * @return success */ UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src); /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with); /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ -UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, - ul_fmtops_t *fmtp); +UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ -static inline bool ul_print(const unit_t *unit, ul_format_t format, - ul_fmtops_t *fmtp) +static inline bool ul_print(const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) { return ul_fprint(stdout, unit, format, fmtp); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ -UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, - ul_format_t format, ul_fmtops_t *fmtp); +UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); #endif /*UNITLIB_H*/
jan-kuechler/unitlib
a6dbb09e13b71dc7461e486701dcd2564a5604ca
Added restrict qualifier to some function parameters.
diff --git a/intern.h b/intern.h index 0f3af09..36bdc4f 100644 --- a/intern.h +++ b/intern.h @@ -1,57 +1,57 @@ #ifndef UL_INTERN_H #define UL_INTERN_H #include <float.h> #include <math.h> #include "unitlib.h" extern const char *_ul_symbols[]; extern size_t _ul_symlens[]; extern bool _ul_debugging; UL_LINKAGE void _ul_debug(const char *fmt, ...); #define debug(fmt,...) \ do { \ if (_ul_debugging) _ul_debug("[ul - %s] " fmt "\n",\ __func__, ##__VA_ARGS__);\ } while(0) UL_LINKAGE void _ul_set_error(const char *func, int line, const char *fmt, ...); #define ERROR(msg, ...) _ul_set_error(__func__, __LINE__, msg, ##__VA_ARGS__) UL_LINKAGE void _ul_init_rules(void); UL_LINKAGE void _ul_free_rules(void); #define EXPS_SIZE(unit) (sizeof((unit)->exps[0]) * NUM_BASE_UNITS) static inline void init_unit(unit_t *unit) { memset(unit->exps, 0, EXPS_SIZE(unit)); unit->factor = 1.0; } -static inline void copy_unit(const unit_t *src, unit_t *dst) +static inline void copy_unit(const unit_t *restrict src, unit_t *restrict dst) { memcpy(dst->exps, src->exps, EXPS_SIZE(dst)); dst->factor = src->factor; } -static inline void add_unit(unit_t *to, const unit_t *other, int times) +static inline void add_unit(unit_t *restrict to, const unit_t *restrict other, int times) { for (int i=0; i < NUM_BASE_UNITS; ++i) { to->exps[i] += (times * other->exps[i]); } to->factor *= _pown(other->factor, times); } static inline int ncmp(ul_number a, ul_number b) { if (_fabsn(a-b) < N_EPSILON) return 0; if (a < b) return -1; return 1; } #endif /*UL_INTERN_H*/ diff --git a/unitlib.c b/unitlib.c index 48aec12..863dcfe 100644 --- a/unitlib.c +++ b/unitlib.c @@ -1,169 +1,169 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" #define static_assert(e) extern char (*STATIC_ASSERT(void))[sizeof(char[1 - 2*!(e)])] #define sizeofarray(ar) (sizeof((ar))/sizeof((ar)[0])) static FILE *dbg_out = NULL; bool _ul_debugging = false; UL_LINKAGE void _ul_debug(const char *fmt, ...) { assert(dbg_out); va_list ap; va_start(ap, fmt); vfprintf(dbg_out, fmt, ap); va_end(ap); } const char *_ul_symbols[] = { "m", "kg", "s", "A", "K", "mol", "Cd", "L", }; static_assert(sizeofarray(_ul_symbols) == NUM_BASE_UNITS); // The last error message static char errmsg[1024]; UL_LINKAGE void _ul_set_error(const char *func, int line, const char *fmt, ...) { snprintf(errmsg, 1024, "[%s:%d] ", func, line); size_t len = strlen(errmsg); va_list ap; va_start(ap, fmt); vsnprintf(errmsg + len, 1024 - len, fmt, ap); va_end(ap); } UL_API bool ul_equal(const unit_t *a, const unit_t *b) { if (!a || !b) { ERROR("Invalid parameters"); return false; } for (int i=0; i < NUM_BASE_UNITS; ++i) { if (a->exps[i] != b->exps[i]) return false; } return ncmp(a->factor, b->factor) == 0; } -UL_API bool ul_combine(unit_t *unit, const unit_t *with) +UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with) { if (!unit || !with) { ERROR("Invalid parameter"); return false; } add_unit(unit, with, 1); return true; } -UL_API bool ul_copy(unit_t *dst, const unit_t *src) +UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src) { if (!dst || !src) { ERROR("Invalid parameter"); return false; } copy_unit(src, dst); return true; } UL_API bool ul_inverse(unit_t *unit) { if (!unit) { ERROR("Invalid parameter"); return false; } if (ncmp(unit->factor, 0.0) == 0) { ERROR("Cannot inverse 0.0"); return false; } for (int i=0; i < NUM_BASE_UNITS; ++i) { unit->exps[i] = -unit->exps[i]; } unit->factor = 1/unit->factor; return true; } UL_API bool ul_sqrt(unit_t *unit) { if (!unit) { ERROR("Invalid parameter"); return false; } for (int i=0; i < NUM_BASE_UNITS; ++i) { if ((unit->exps[i] % 2) != 0) { ERROR("Cannot take root of an odd exponent"); return false; } } for (int i=0; i < NUM_BASE_UNITS; ++i) { unit->exps[i] /= 2; } unit->factor = _sqrtn(unit->factor); return false; } UL_API void ul_debugging(bool flag) { _ul_debugging = flag; } UL_API void ul_debugout(const char *path, bool append) { if (dbg_out && dbg_out != stderr) { debug("New debug file: %s", path ? path : "stderr"); fclose(dbg_out); } if (!path) { dbg_out = stderr; } else { dbg_out = fopen(path, append ? "a" : "w"); if (!dbg_out) { dbg_out = stderr; debug("Failed to open '%s' as debugout, using stderr.", path); } } } UL_API const char *ul_error(void) { return errmsg; } UL_API bool ul_init(void) { if(!dbg_out) dbg_out = stderr; debug("Initializing base rules"); _ul_init_rules(); const char *rulePath = getenv("UL_RULES"); if (rulePath) { debug("UL_RULES is set: %s", rulePath); if (!ul_load_rules(rulePath)) { ERROR("Failed to load rules: %s", errmsg); return false; } } return true; } UL_API void ul_quit(void) { _ul_free_rules(); if (dbg_out && dbg_out != stderr) fclose(dbg_out); } diff --git a/unitlib.h b/unitlib.h index cc1cb76..b2b5bc7 100644 --- a/unitlib.h +++ b/unitlib.h @@ -1,193 +1,193 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "config.h" #define UL_NAME "unitlib" #define UL_VERSION "0.3b1" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif #if defined(UL_EXPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllexport) #elif defined(UL_IMPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllimport) #else #define UL_API UL_LINKAGE #endif typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; #define U_ANY -1 typedef enum ul_format { UL_FMT_PLAIN, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, } ul_format_t; typedef struct ul_format_ops { bool sort; int order[NUM_BASE_UNITS]; } ul_fmtops_t; typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** * Deinitializes the unitlib and frees all. This function * has to be called at the end of the program. * internals resources. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ UL_API bool ul_equal(const unit_t *a, const unit_t *b); /** * Copies a unit into another * @param dst Destination unit * @param src Source unit * @return success */ -UL_API bool ul_copy(unit_t *dst, const unit_t *src); +UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src); /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ -UL_API bool ul_combine(unit_t *unit, const unit_t *with); +UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with); /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ static inline bool ul_print(const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) { return ul_fprint(stdout, unit, format, fmtp); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); #endif /*UNITLIB_H*/
jan-kuechler/unitlib
f824464059ee2ae4201699171d575e873d1325cf
Changed for loops to c99 style.
diff --git a/Makefile b/Makefile index 8482439..9acddcd 100644 --- a/Makefile +++ b/Makefile @@ -1,86 +1,86 @@ ## # Makefile for unitlib ## CC = gcc CFLAGS = -O2 -std=c99 -Wall -Wextra AR = ar RANLIB = ranlib TARGET = libunit.a DLL = libunit.dll IMPLIB = libunit.lib HEADER = unitlib.h SRCFILES = unitlib.c parser.c format.c HDRFILES = unitlib.h intern.h LIB_INSTALL = /g/Programmieren/lib HDR_INSTALL = /g/Programmieren/include OBJFILES = unitlib.o parser.o format.o TESTPROG = _test.exe SMASHPROG = _smash.exe UNITTEST = ultest .PHONY: test clean allclean all: $(TARGET) dll: $(DLL) install-dll: dll cp $(DLL) $(LIB_INSTALL) cp $(IMPLIB) $(LIB_INSTALL) cp $(HEADER) $(HDR_INSTALL) test: $(TESTPROG) @./$(TESTPROG) utest: $(UNITTEST) @./$(UNITTEST) smash: $(SMASHPROG) @./$(SMASHPROG) $(TARGET): $(OBJFILES) @$(AR) rc $(TARGET) $(OBJFILES) @$(RANLIB) $(TARGET) $(DLL): $(SRCFILES) $(HDRFILES) @$(CC) $(CFLAGS) -shared -o $(DLL) $(SRCFILES) -Wl,--out-implib,$(IMPLIB) unitlib.o: unitlib.c $(HDRFILES) @$(CC) $(CFLAGS) -o unitlib.o -c unitlib.c parser.o: parser.c $(HDRFILES) @$(CC) $(CFLAGS) -o parser.o -c parser.c format.o: format.c $(HDRFILES) @$(CC) $(CFLAGS) -o format.o -c format.c $(TESTPROG): $(TARGET) _test.c @$(CC) -o $(TESTPROG) -g -L. _test.c -lunit $(SMASHPROG): $(TARGET) _test.c @$(CC) -o $(SMASHPROG) -L. -DSMASH _test.c -lunit $(UNITTEST): $(TARGET) unittest.c - @$(CC) -o $(UNITTEST) -L. unittest.c -lunit + @$(CC) -std=gnu99 -o $(UNITTEST) -L. unittest.c -lunit clean: @rm -f $(OBJFILES) @rm -f $(TESTPROG) @rm -f $(SMASHPROG) @rm -f $(UNITTEST) @rm -f debug.log allclean: clean @rm -f $(TARGET) @rm -f $(DLL) @rm -f $(IMPLIB) diff --git a/format.c b/format.c index eee6414..35c160c 100644 --- a/format.c +++ b/format.c @@ -1,366 +1,362 @@ #include <assert.h> #include <stdio.h> #include <string.h> #include "intern.h" #include "unitlib.h" struct status { bool (*putc)(char c, void *info); void *info; const unit_t *unit; ul_format_t format; ul_fmtops_t *fmtp; void *extra; }; typedef bool (*printer_t)(struct status*,int,int,bool*); struct f_info { FILE *out; }; static bool f_putc(char c, void *i) { struct f_info *info = i; return fputc(c, info->out) == c; } struct sn_info { char *buffer; int idx; int size; }; static bool sn_putc(char c, void *i) { struct sn_info *info = i; if (info->idx >= info->size) { return false; } info->buffer[info->idx++] = c; return true; } #define _putc(s,c) (s)->putc((c),(s)->info) #define CHECK(x) do { if (!(x)) return false; } while (0) static bool _puts(struct status *s, const char *str) { while (*str) { char c = *str++; if (!_putc(s, c)) return false; } return true; } static bool _putd(struct status *stat, int n) { char buffer[1024]; snprintf(buffer, 1024, "%d", n); return _puts(stat, buffer); } static bool _putn(struct status *stat, ul_number n) { char buffer[1024]; snprintf(buffer, 1024, N_FMT, n); return _puts(stat, buffer); } static void getnexp(ul_number n, ul_number *mantissa, int *exp) { bool neg = false; if (n < 0) { neg = true; n = -n; } if ((ncmp(n, 10.0) == -1) && (ncmp(n, 1.0) == 1)) { *mantissa = neg ? -n : n; *exp = 0; return; } else if (ncmp(n, 10.0) > -1) { int e = 0; do { e++; n /= 10; } while (ncmp(n, 10.0) == 1); *exp = e; *mantissa = neg ? -n : n; } else if (ncmp(n, 1.0) < 1) { int e = 0; while (ncmp(n, 1.0) == -1) { e--; n *= 10; } *exp = e; *mantissa = neg ? -n : n; } } // global for testing purpose, it's not declared in the header void _ul_getnexp(ul_number n, ul_number *m, int *e) { getnexp(n, m, e); } static bool print_sorted(struct status *stat, printer_t func, bool *first) { bool printed[NUM_BASE_UNITS] = {0}; bool _first = true; - int i=0; - bool *fptr = first ? first : &_first; // Print any sorted order - for (; i < NUM_BASE_UNITS; ++i) { + for (int i=0; i < NUM_BASE_UNITS; ++i) { int unit = stat->fmtp->order[i]; if (unit == U_ANY) { break; } int exp = stat->unit->exps[unit]; CHECK(func(stat, unit, exp , fptr)); printed[unit] = true; } // Print the rest - for (i=0; i < NUM_BASE_UNITS; ++i) { + for (int i=0; i < NUM_BASE_UNITS; ++i) { if (!printed[i]) { int exp = stat->unit->exps[i]; if (exp != 0) { CHECK(func(stat, i, exp , fptr)); } } } return true; } static bool print_normal(struct status *stat, printer_t func, bool *first) { - int i=0; bool _first = true; bool *fptr = first ? first : &_first; - for (; i < NUM_BASE_UNITS; ++i) { + for (int i=0; i < NUM_BASE_UNITS; ++i) { CHECK(func(stat,i,stat->unit->exps[i], fptr)); } return true; } // Begin - plain static bool _plain_one(struct status* stat, int unit, int exp, bool *first) { if (exp == 0) return true; if (!*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, _ul_symbols[unit])); // and the exponent if (exp != 1) { CHECK(_putc(stat, '^')); CHECK(_putd(stat, exp)); } *first = false; return true; } static bool p_plain(struct status *stat) { CHECK(_putn(stat, stat->unit->factor)); CHECK(_putc(stat, ' ')); if (stat->fmtp && stat->fmtp->sort) { return print_sorted(stat, _plain_one, NULL); } else { return print_normal(stat, _plain_one, NULL); } return true; } // End - plain // Begin - LaTeX static bool _latex_one(struct status *stat, int unit, int exp, bool *first) { if (exp == 0) return true; if (stat->extra) { bool pos = *(bool*)stat->extra; if (exp > 0 && !pos) return true; if (exp < 0) { if (pos) return true; exp = -exp; } } if (!*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, "\\text{")); if (!*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, _ul_symbols[unit])); CHECK(_puts(stat, "}")); if (exp != 1) { CHECK(_putc(stat, '^')); CHECK(_putc(stat, '{')); CHECK(_putd(stat, exp)); CHECK(_putc(stat, '}')); } *first = false; return true; } static bool p_latex_frac(struct status *stat) { bool first = true; bool positive = true; stat->extra = &positive; ul_number m; int e; getnexp(stat->unit->factor, &m, &e); CHECK(_puts(stat, "\\frac{")); if (e >= 0) { CHECK(_putn(stat, m)); if (e > 0) { CHECK(_puts(stat, " \\cdot 10^{")); CHECK(_putd(stat, e)); CHECK(_putc(stat, '}')); } first = false; } if (stat->fmtp && stat->fmtp->sort) { print_sorted(stat, _latex_one, &first); } else { print_normal(stat, _latex_one, &first); } if (first) { // nothing up there... CHECK(_putc(stat, '1')); } CHECK(_puts(stat, "}{")); first = true; positive = false; if (e < 0) { e = -e; CHECK(_putn(stat, m)); if (e > 0) { CHECK(_puts(stat, " \\cdot 10^{")); CHECK(_putd(stat, e)); CHECK(_putc(stat, '}')); } first = false; } if (stat->fmtp && stat->fmtp->sort) { print_sorted(stat, _latex_one, &first); } else { print_normal(stat, _latex_one, &first); } if (first) { CHECK(_putc(stat, '1')); } CHECK(_putc(stat, '}')); return true; } static bool p_latex_inline(struct status *stat) { - int i=0; bool first = false; CHECK(_putc(stat, '$')); ul_number m; int e; getnexp(stat->unit->factor, &m, &e); CHECK(_putn(stat, m)); if (e != 0) { CHECK(_puts(stat, " \\cdot 10^{")); CHECK(_putd(stat, e)); CHECK(_putc(stat, '}')); } - for (i=0; i < NUM_BASE_UNITS; ++i) { + for (int i=0; i < NUM_BASE_UNITS; ++i) { int exp = stat->unit->exps[i]; if (exp != 0) { CHECK(_latex_one(stat, i, exp, &first)); } } CHECK(_putc(stat, '$')); return true; } // End - LaTeX static bool _print(struct status *stat) { debug("ignoring a factor of "N_FMT, stat->unit->factor); switch (stat->format) { case UL_FMT_PLAIN: return p_plain(stat); case UL_FMT_LATEX_FRAC: return p_latex_frac(stat); case UL_FMT_LATEX_INLINE: return p_latex_inline(stat); default: ERROR("Unknown format: %d", stat->format); return false; } } UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) { struct f_info info = { .out = f, }; struct status status = { .putc = f_putc, .info = &info, .unit = unit, .format = format, .fmtp = fmtp, .extra = NULL, }; return _print(&status); } UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) { struct sn_info info = { .buffer = buffer, .size = buflen, .idx = 0, }; struct status status = { .putc = sn_putc, .info = &info, .unit = unit, .format = format, .fmtp = fmtp, .extra = NULL, }; memset(buffer, 0, buflen); return _print(&status); } diff --git a/intern.h b/intern.h index 102c40d..0f3af09 100644 --- a/intern.h +++ b/intern.h @@ -1,58 +1,57 @@ #ifndef UL_INTERN_H #define UL_INTERN_H #include <float.h> #include <math.h> #include "unitlib.h" extern const char *_ul_symbols[]; extern size_t _ul_symlens[]; extern bool _ul_debugging; UL_LINKAGE void _ul_debug(const char *fmt, ...); #define debug(fmt,...) \ do { \ if (_ul_debugging) _ul_debug("[ul - %s] " fmt "\n",\ __func__, ##__VA_ARGS__);\ } while(0) UL_LINKAGE void _ul_set_error(const char *func, int line, const char *fmt, ...); #define ERROR(msg, ...) _ul_set_error(__func__, __LINE__, msg, ##__VA_ARGS__) UL_LINKAGE void _ul_init_rules(void); UL_LINKAGE void _ul_free_rules(void); #define EXPS_SIZE(unit) (sizeof((unit)->exps[0]) * NUM_BASE_UNITS) static inline void init_unit(unit_t *unit) { memset(unit->exps, 0, EXPS_SIZE(unit)); unit->factor = 1.0; } static inline void copy_unit(const unit_t *src, unit_t *dst) { memcpy(dst->exps, src->exps, EXPS_SIZE(dst)); dst->factor = src->factor; } static inline void add_unit(unit_t *to, const unit_t *other, int times) { - int i=0; - for (; i < NUM_BASE_UNITS; ++i) { + for (int i=0; i < NUM_BASE_UNITS; ++i) { to->exps[i] += (times * other->exps[i]); } to->factor *= _pown(other->factor, times); } static inline int ncmp(ul_number a, ul_number b) { if (_fabsn(a-b) < N_EPSILON) return 0; if (a < b) return -1; return 1; } #endif /*UL_INTERN_H*/ diff --git a/parser.c b/parser.c index fbad1dc..8ef87e7 100644 --- a/parser.c +++ b/parser.c @@ -1,448 +1,444 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" typedef struct rule { const char *symbol; unit_t unit; bool force; struct rule *next; } rule_t; // A list of all rules static rule_t *rules = NULL; // The base rules static rule_t base_rules[NUM_BASE_UNITS]; #define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) struct parser_state { int sign; }; enum { MAX_SYM_SIZE = 128, MAX_ITEM_SIZE = 1024, }; // Returns the last rule in the list static rule_t *last_rule(void) { rule_t *cur = rules; while (cur) { if (!cur->next) return cur; cur = cur->next; } assert(false); return NULL; } static rule_t *get_rule(const char *sym) { assert(sym); - rule_t *cur = rules; - while (cur) { + for (rule_t *cur = rules; cur; cur = cur->next) { if (strcmp(cur->symbol, sym) == 0) return cur; - cur = cur->next; } return NULL; } static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } static size_t nextspace(const char *text, size_t start) { assert(text); - size_t i=start; + size_t i = start; while (text[i] && !isspace(text[i])) i++; return i; } static bool try_parse_factor(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); char *endptr; ul_number f = _strton(str, &endptr); if (endptr && *endptr) { debug("'%s' is not a factor", str); return false; } unit->factor *= f; return true; } static bool is_special(const char *str) { assert(str); if (strlen(str) == 1) { switch (str[0]) { case '*': return true; case '/': return true; } } return false; } static bool handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); switch (str[0]) { case '*': // ignore return true; case '/': state->sign *= -1; return true; } ERROR("Internal error: is_special/handle_special missmatch for '%s'.", str); return false; } static bool parse_item(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; size_t symend = 0; while (str[symend] && str[symend] != '^') symend++; if (symend >= MAX_SYM_SIZE) { ERROR("Symbol to long"); return false; } strncpy(symbol, str, symend); symbol[symend] = '\0'; if (str[symend]) { // The '^' should not be the last value of the string if (!str[symend+1]) { ERROR("Missing exponent after '^' while parsing '%s'", str); return false; } // Parse the exponent char *endptr = NULL; exp = strtol(str+symend+1, &endptr, 10); // the whole exp string was valid only if *endptr is '\0' if (endptr && *endptr) { ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); return false; } } debug("Exponent is %d", exp); // Find the matching rule rule_t *rule = get_rule(symbol); if (!rule) { ERROR("No matching rule found for '%s'", symbol); return false; } // And add the definitions add_unit(unit, &rule->unit, state->sign * exp); return true; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); struct parser_state state; state.sign = 1; init_unit(unit); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace size_t end = nextspace(str, start); if (end == start) {// End of string break; } // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; // and parse it if (is_special(this_item)) { if (!handle_special(this_item, &state)) return false; } else if (try_parse_factor(this_item, unit, &state)) { // nothing todo } else { if (!parse_item(this_item, unit, &state)) return false; } start = end + 1; } while (start < len); return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); - size_t i=0; - for (; i < len; ++i) { + for (size_t i=0; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } UL_LINKAGE void _ul_init_rules(void) { - int i=0; - for (; i < NUM_BASE_UNITS; ++i) { + for (int i=0; i < NUM_BASE_UNITS; ++i) { base_rules[i].symbol = _ul_symbols[i]; init_unit(&base_rules[i].unit); base_rules[i].force = true; base_rules[i].unit.exps[i] = 1; base_rules[i].next = &base_rules[i+1]; } dynamic_rules = NULL; rules = base_rules; } UL_LINKAGE void _ul_free_rules(void) { debug("Freeing rule list"); rule_t *cur = dynamic_rules; while (cur) { rule_t *next = cur->next; free((char*)cur->symbol); free(cur); cur = next; } } diff --git a/unitlib.c b/unitlib.c index fd38654..48aec12 100644 --- a/unitlib.c +++ b/unitlib.c @@ -1,171 +1,169 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" #define static_assert(e) extern char (*STATIC_ASSERT(void))[sizeof(char[1 - 2*!(e)])] #define sizeofarray(ar) (sizeof((ar))/sizeof((ar)[0])) static FILE *dbg_out = NULL; bool _ul_debugging = false; UL_LINKAGE void _ul_debug(const char *fmt, ...) { assert(dbg_out); va_list ap; va_start(ap, fmt); vfprintf(dbg_out, fmt, ap); va_end(ap); } const char *_ul_symbols[] = { "m", "kg", "s", "A", "K", "mol", "Cd", "L", }; static_assert(sizeofarray(_ul_symbols) == NUM_BASE_UNITS); // The last error message static char errmsg[1024]; UL_LINKAGE void _ul_set_error(const char *func, int line, const char *fmt, ...) { snprintf(errmsg, 1024, "[%s:%d] ", func, line); size_t len = strlen(errmsg); va_list ap; va_start(ap, fmt); vsnprintf(errmsg + len, 1024 - len, fmt, ap); va_end(ap); } UL_API bool ul_equal(const unit_t *a, const unit_t *b) { if (!a || !b) { ERROR("Invalid parameters"); return false; } - int i=0; - for (; i < NUM_BASE_UNITS; ++i) { + for (int i=0; i < NUM_BASE_UNITS; ++i) { if (a->exps[i] != b->exps[i]) return false; } return ncmp(a->factor, b->factor) == 0; } UL_API bool ul_combine(unit_t *unit, const unit_t *with) { if (!unit || !with) { ERROR("Invalid parameter"); return false; } add_unit(unit, with, 1); return true; } UL_API bool ul_copy(unit_t *dst, const unit_t *src) { if (!dst || !src) { ERROR("Invalid parameter"); return false; } copy_unit(src, dst); return true; } UL_API bool ul_inverse(unit_t *unit) { if (!unit) { ERROR("Invalid parameter"); return false; } if (ncmp(unit->factor, 0.0) == 0) { ERROR("Cannot inverse 0.0"); return false; } - int i=0; - for (; i < NUM_BASE_UNITS; ++i) { + for (int i=0; i < NUM_BASE_UNITS; ++i) { unit->exps[i] = -unit->exps[i]; } unit->factor = 1/unit->factor; return true; } UL_API bool ul_sqrt(unit_t *unit) { if (!unit) { ERROR("Invalid parameter"); return false; } - int i=0; - for (; i < NUM_BASE_UNITS; ++i) { + + for (int i=0; i < NUM_BASE_UNITS; ++i) { if ((unit->exps[i] % 2) != 0) { ERROR("Cannot take root of an odd exponent"); return false; } } - for (; i < NUM_BASE_UNITS; ++i) { + for (int i=0; i < NUM_BASE_UNITS; ++i) { unit->exps[i] /= 2; } unit->factor = _sqrtn(unit->factor); return false; } UL_API void ul_debugging(bool flag) { _ul_debugging = flag; } UL_API void ul_debugout(const char *path, bool append) { if (dbg_out && dbg_out != stderr) { debug("New debug file: %s", path ? path : "stderr"); fclose(dbg_out); } if (!path) { dbg_out = stderr; } else { dbg_out = fopen(path, append ? "a" : "w"); if (!dbg_out) { dbg_out = stderr; debug("Failed to open '%s' as debugout, using stderr.", path); } } } UL_API const char *ul_error(void) { return errmsg; } UL_API bool ul_init(void) { if(!dbg_out) dbg_out = stderr; debug("Initializing base rules"); _ul_init_rules(); const char *rulePath = getenv("UL_RULES"); if (rulePath) { debug("UL_RULES is set: %s", rulePath); if (!ul_load_rules(rulePath)) { ERROR("Failed to load rules: %s", errmsg); return false; } } return true; } UL_API void ul_quit(void) { _ul_free_rules(); if (dbg_out && dbg_out != stderr) fclose(dbg_out); }
jan-kuechler/unitlib
96b158d17e090d47297382612aa809219f1ba910
Added more unittests. Added some parameter checks in core functions. Pushed version to 0.3b1
diff --git a/parser.c b/parser.c index 872f6e4..fbad1dc 100644 --- a/parser.c +++ b/parser.c @@ -1,448 +1,448 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" typedef struct rule { const char *symbol; unit_t unit; bool force; struct rule *next; } rule_t; // A list of all rules static rule_t *rules = NULL; // The base rules static rule_t base_rules[NUM_BASE_UNITS]; #define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) struct parser_state { int sign; }; enum { MAX_SYM_SIZE = 128, MAX_ITEM_SIZE = 1024, }; // Returns the last rule in the list static rule_t *last_rule(void) { rule_t *cur = rules; while (cur) { if (!cur->next) return cur; cur = cur->next; } assert(false); return NULL; } static rule_t *get_rule(const char *sym) { assert(sym); rule_t *cur = rules; while (cur) { if (strcmp(cur->symbol, sym) == 0) return cur; cur = cur->next; } return NULL; } static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } static size_t nextspace(const char *text, size_t start) { assert(text); size_t i=start; while (text[i] && !isspace(text[i])) i++; return i; } static bool try_parse_factor(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); char *endptr; ul_number f = _strton(str, &endptr); if (endptr && *endptr) { debug("'%s' is not a factor", str); return false; } unit->factor *= f; return true; } static bool is_special(const char *str) { assert(str); if (strlen(str) == 1) { switch (str[0]) { case '*': return true; case '/': return true; } } return false; } static bool handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); switch (str[0]) { case '*': // ignore return true; case '/': state->sign *= -1; return true; } ERROR("Internal error: is_special/handle_special missmatch for '%s'.", str); return false; } static bool parse_item(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; size_t symend = 0; while (str[symend] && str[symend] != '^') symend++; if (symend >= MAX_SYM_SIZE) { ERROR("Symbol to long"); return false; } strncpy(symbol, str, symend); symbol[symend] = '\0'; if (str[symend]) { // The '^' should not be the last value of the string if (!str[symend+1]) { ERROR("Missing exponent after '^' while parsing '%s'", str); return false; } // Parse the exponent char *endptr = NULL; exp = strtol(str+symend+1, &endptr, 10); // the whole exp string was valid only if *endptr is '\0' if (endptr && *endptr) { ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); return false; } } debug("Exponent is %d", exp); // Find the matching rule rule_t *rule = get_rule(symbol); if (!rule) { ERROR("No matching rule found for '%s'", symbol); return false; } // And add the definitions add_unit(unit, &rule->unit, state->sign * exp); return true; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); struct parser_state state; state.sign = 1; init_unit(unit); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace size_t end = nextspace(str, start); if (end == start) {// End of string break; } // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; + // and parse it if (is_special(this_item)) { if (!handle_special(this_item, &state)) return false; } else if (try_parse_factor(this_item, unit, &state)) { // nothing todo } else { - // and parse it if (!parse_item(this_item, unit, &state)) return false; } start = end + 1; } while (start < len); return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); size_t i=0; for (; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } UL_LINKAGE void _ul_init_rules(void) { int i=0; for (; i < NUM_BASE_UNITS; ++i) { base_rules[i].symbol = _ul_symbols[i]; init_unit(&base_rules[i].unit); base_rules[i].force = true; base_rules[i].unit.exps[i] = 1; base_rules[i].next = &base_rules[i+1]; } dynamic_rules = NULL; rules = base_rules; } UL_LINKAGE void _ul_free_rules(void) { debug("Freeing rule list"); rule_t *cur = dynamic_rules; while (cur) { rule_t *next = cur->next; free((char*)cur->symbol); free(cur); cur = next; } } diff --git a/unitlib.c b/unitlib.c index 577aff2..fd38654 100644 --- a/unitlib.c +++ b/unitlib.c @@ -1,159 +1,171 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" #define static_assert(e) extern char (*STATIC_ASSERT(void))[sizeof(char[1 - 2*!(e)])] #define sizeofarray(ar) (sizeof((ar))/sizeof((ar)[0])) static FILE *dbg_out = NULL; bool _ul_debugging = false; UL_LINKAGE void _ul_debug(const char *fmt, ...) { assert(dbg_out); va_list ap; va_start(ap, fmt); vfprintf(dbg_out, fmt, ap); va_end(ap); } const char *_ul_symbols[] = { "m", "kg", "s", "A", "K", "mol", "Cd", "L", }; static_assert(sizeofarray(_ul_symbols) == NUM_BASE_UNITS); // The last error message static char errmsg[1024]; UL_LINKAGE void _ul_set_error(const char *func, int line, const char *fmt, ...) { snprintf(errmsg, 1024, "[%s:%d] ", func, line); size_t len = strlen(errmsg); va_list ap; va_start(ap, fmt); vsnprintf(errmsg + len, 1024 - len, fmt, ap); va_end(ap); } UL_API bool ul_equal(const unit_t *a, const unit_t *b) { if (!a || !b) { ERROR("Invalid parameters"); return false; } int i=0; for (; i < NUM_BASE_UNITS; ++i) { if (a->exps[i] != b->exps[i]) return false; } return ncmp(a->factor, b->factor) == 0; } UL_API bool ul_combine(unit_t *unit, const unit_t *with) { + if (!unit || !with) { + ERROR("Invalid parameter"); + return false; + } add_unit(unit, with, 1); return true; } UL_API bool ul_copy(unit_t *dst, const unit_t *src) { if (!dst || !src) { ERROR("Invalid parameter"); return false; } copy_unit(src, dst); return true; } UL_API bool ul_inverse(unit_t *unit) { + if (!unit) { + ERROR("Invalid parameter"); + return false; + } if (ncmp(unit->factor, 0.0) == 0) { ERROR("Cannot inverse 0.0"); return false; } int i=0; for (; i < NUM_BASE_UNITS; ++i) { unit->exps[i] = -unit->exps[i]; } unit->factor = 1/unit->factor; return true; } UL_API bool ul_sqrt(unit_t *unit) { + if (!unit) { + ERROR("Invalid parameter"); + return false; + } int i=0; for (; i < NUM_BASE_UNITS; ++i) { if ((unit->exps[i] % 2) != 0) { ERROR("Cannot take root of an odd exponent"); return false; } } for (; i < NUM_BASE_UNITS; ++i) { unit->exps[i] /= 2; } unit->factor = _sqrtn(unit->factor); return false; } UL_API void ul_debugging(bool flag) { _ul_debugging = flag; } UL_API void ul_debugout(const char *path, bool append) { if (dbg_out && dbg_out != stderr) { debug("New debug file: %s", path ? path : "stderr"); fclose(dbg_out); } if (!path) { dbg_out = stderr; } else { dbg_out = fopen(path, append ? "a" : "w"); if (!dbg_out) { dbg_out = stderr; debug("Failed to open '%s' as debugout, using stderr.", path); } } } UL_API const char *ul_error(void) { return errmsg; } UL_API bool ul_init(void) { if(!dbg_out) dbg_out = stderr; debug("Initializing base rules"); _ul_init_rules(); const char *rulePath = getenv("UL_RULES"); if (rulePath) { debug("UL_RULES is set: %s", rulePath); if (!ul_load_rules(rulePath)) { ERROR("Failed to load rules: %s", errmsg); return false; } } return true; } UL_API void ul_quit(void) { _ul_free_rules(); if (dbg_out && dbg_out != stderr) fclose(dbg_out); } diff --git a/unitlib.h b/unitlib.h index 61b5e5e..cc1cb76 100644 --- a/unitlib.h +++ b/unitlib.h @@ -1,193 +1,193 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "config.h" #define UL_NAME "unitlib" -#define UL_VERSION "0.3a1" +#define UL_VERSION "0.3b1" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif #if defined(UL_EXPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllexport) #elif defined(UL_IMPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllimport) #else #define UL_API UL_LINKAGE #endif typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; #define U_ANY -1 typedef enum ul_format { UL_FMT_PLAIN, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, } ul_format_t; typedef struct ul_format_ops { bool sort; int order[NUM_BASE_UNITS]; } ul_fmtops_t; typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** * Deinitializes the unitlib and frees all. This function * has to be called at the end of the program. * internals resources. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ UL_API bool ul_equal(const unit_t *a, const unit_t *b); /** * Copies a unit into another * @param dst Destination unit * @param src Source unit * @return success */ UL_API bool ul_copy(unit_t *dst, const unit_t *src); /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ UL_API bool ul_combine(unit_t *unit, const unit_t *with); /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ static inline bool ul_print(const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) { return ul_fprint(stdout, unit, format, fmtp); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); #endif /*UNITLIB_H*/ diff --git a/unittest.c b/unittest.c index e766192..c576098 100644 --- a/unittest.c +++ b/unittest.c @@ -1,430 +1,458 @@ #ifndef GET_TEST_DEFS #include <stdarg.h> #include <stdlib.h> #include <string.h> #include "unitlib.h" #include "intern.h" // yay, self include (-: #define GET_TEST_DEFS #include "unittest.c" #undef GET_TEST_DEFS static unit_t make_unit(ul_number fac, ...) { va_list args; va_start(args, fac); unit_t u; memset(u.exps, 0, NUM_BASE_UNITS * sizeof(int)); u.factor = fac; int b = va_arg(args, int); int e = va_arg(args, int); while (b || e) { u.exps[b] = e; b = va_arg(args, int); e = va_arg(args, int); } return u; } #define MAKE_UNIT(...) make_unit(__VA_ARGS__,0,0,0) TEST_SUITE(parser) TEST unit_t u; CHECK(ul_parse("m", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_METER] == 1); int i=0; for (; i < NUM_BASE_UNITS; ++i) { if (i != U_METER) { CHECK(u.exps[i] == 0); } } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; CHECK(ul_parse(" \n kg^2 * m ", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_KILOGRAM] == 2); CHECK(u.exps[U_METER] == 1); CHECK(u.exps[U_SECOND] == 0); CHECK(ncmp(u.factor, 1.0) == 0); CHECK(ul_parse("2 Cd 7 s^-1", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_CANDELA] == 1); CHECK(u.exps[U_SECOND] == -1); CHECK(ncmp(u.factor, 14.0) == 0); CHECK(ul_parse("", &u)); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; const char *strings[] = { "5*kg^2", // need whitespace "5 ** kg^2", // double * "5! * kg^2", // ! "5 * kg^2!", // ! NULL }; int i = 0; while (strings[i]) { CHECK(ul_parse(strings[i], &u) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST const char *strings[] = { "", // empty rule " =", // empty symbol "16 = 16", // invalid rule " a b = s ", // invalid symbol " c == kg", // double = "d = e", // unknown 'e' " = kg", // empty symbol NULL, }; int i=0; while (strings[i]) { CHECK(ul_parse_rule(strings[i]) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST // Empty rules are allowed CHECK(ul_parse_rule("EmptySymbol = ")); FAIL_MSG("Error: %s", ul_error()); unit_t u; CHECK(ul_parse("EmptySymbol", &u)); FAIL_MSG("Error: %s", ul_error()); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; CHECK(ul_parse(NULL, NULL) == false); CHECK(ul_parse(NULL, &u) == false); CHECK(ul_parse("kg", NULL) == false); CHECK(ul_parse_rule(NULL) == false); CHECK(ul_parse_rule("") == false); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t s = MAKE_UNIT(1.0, U_SECOND, 1); unit_t u; CHECK(ul_parse_rule("!ForcedRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("ForcedRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("NewRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("!NewRule = s")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); CHECK(ul_equal(&s, &u)); CHECK(ul_parse_rule("!NewRule = m") == false); CHECK(ul_parse_rule("!kg = kg") == false); CHECK(ul_parse_rule(" Recurse = m")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse_rule("!Recurse = Recurse") == false); END_TEST END_TEST_SUITE() TEST_SUITE(core) TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t kg2 = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_equal(&kg, &kg2)); kg2.factor = 2.0; CHECK(!ul_equal(&kg, &kg2)); kg2.factor = 1.0; CHECK(ul_equal(&kg, &kg2)); kg2.exps[U_KILOGRAM]++; CHECK(!ul_equal(&kg, &kg2)); unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); CHECK(!ul_equal(&kg, &N)); + END_TEST + + TEST + unit_t a = MAKE_UNIT(1.0, U_KILOGRAM, 1); + unit_t b; + + CHECK(ul_copy(&b, &a)); + FAIL_MSG("Error: %s", ul_error()); + + CHECK(ul_equal(&b, &a)); + + CHECK(!ul_copy(NULL, NULL)); + CHECK(!ul_copy(&a, NULL)); + CHECK(!ul_copy(NULL, &a)); + END_TEST + + TEST + unit_t a = MAKE_UNIT(2.0, U_KILOGRAM, 1); + unit_t b = MAKE_UNIT(3.0, U_SECOND, -2); + + unit_t res; + CHECK(ul_copy(&res, &a)); + FAIL_MSG("Preparation failed: %s", ul_error()); + + CHECK(ul_combine(&res, &b)); + FAIL_MSG("Error: %s", ul_error()); + unit_t correct = MAKE_UNIT(6.0, U_KILOGRAM, 1, U_SECOND, -2); + CHECK(ul_equal(&res, &correct)); END_TEST END_TEST_SUITE() TEST_SUITE(format) TEST extern void _ul_getnexp(ul_number n, ul_number *m, int *e); ul_number m; int e; _ul_getnexp(1.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1.0, &m, &e); CHECK(ncmp(m, -1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(11.0, &m, &e); CHECK(ncmp(m, 1.1) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e);; _ul_getnexp(9.81, &m, &e); CHECK(ncmp(m, 9.81) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1234, &m, &e); CHECK(ncmp(m, -1.234) == 0); FAIL_MSG("m == %g", m); CHECK(e == 3); FAIL_MSG("e == %d", e); _ul_getnexp(10.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); _ul_getnexp(0.01, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == -2); FAIL_MSG("e == %d", e); _ul_getnexp(0.99, &m, &e); CHECK(ncmp(m, 9.9) == 0); FAIL_MSG("m == %g", m); CHECK(e == -1); FAIL_MSG("e == %d", e); _ul_getnexp(10.01, &m, &e); CHECK(ncmp(m, 1.001) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); kg.factor = 1.5; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1.5 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); kg.factor = -1.0; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "-1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 m kg s^-2") == 0); FAIL_MSG("buffer: '%s'", buffer); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$1 \\text{ m} \\text{ kg} \\text{ s}^{-2}$") == 0); FAIL_MSG("buffer: '%s'", buffer); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "\\frac{1 \\text{ m} \\text{ kg}}{\\text{s}^{2}}") == 0); FAIL_MSG("buffer: '%s'", buffer); END_TEST END_TEST_SUITE() int main(void) { ul_debugging(false); if (!ul_init()) { printf("ul_init failed: %s", ul_error()); return 1; } INIT_TEST(); SET_LOGLVL(L_NORMAL); RUN_SUITE(core); RUN_SUITE(parser); RUN_SUITE(format); ul_quit(); return TEST_RESULT; } #endif /*ndef GET_TEST_DEFS*/ //################################################################################################# #ifdef GET_TEST_DEFS #define PRINT(o, lvl, ...) do { if ((o)->loglvl >= lvl) printf(__VA_ARGS__); } while (0) #define CHECK(expr) \ do { \ int _this = ++_cid; \ if (!(expr)) { \ _err++; _fail++; \ PRINT(_o, L_NORMAL, "[%s-%d-%d] Fail: '%s'\n", _name, _id, _this, #expr); \ _last = false;\ } \ else { \ PRINT(_o, L_VERBOSE, "[%s-%d-%d] Pass: '%s'\n", _name, _id, _this, #expr); \ _last = true; \ } \ } while (0) #define FAIL_MSG(msg, ...) \ do {if (!_last) PRINT(_o,L_NORMAL,msg"\n", ##__VA_ARGS__); } while (0) #define PASS_MSG(msg, ...) \ do {if (_last) PRINT(_o,L_VERBOSE,msg"\n", ##__VA_ARGS__); } while (0) #define INFO(fmt, ...) \ do { printf("* " fmt "\n", ##__VA_ARGS__); } while (0) // TEST SUITE #define TEST_SUITE(name) \ int _test_##name(_tops *_o) { \ const char *_name = #name; \ int _fail = 0; \ int _test_id = 0; \ #define END_TEST_SUITE() \ return _fail; } // SINGLE TEST #define TEST \ { int _id = ++_test_id; int _err = 0; int _cid = 0; bool _last = true; \ #define END_TEST \ if (_err > 0) { \ PRINT(_o, L_NORMAL, "[%s-%d] failed with %d error%s.\n", _name, _id, _err, _err > 1 ? "s" : ""); \ } \ else { \ PRINT(_o, L_NORMAL, "[%s-%d] passed.\n", _name, _id); \ } \ } // OTHER typedef struct { int loglvl; } _tops; enum { L_QUIET = 0, L_RESULT = 1, L_NORMAL = 2, L_VERBOSE = 3, L_ALL = 4, }; static inline int _run_suite(int (*suite)(_tops*), const char *name, _tops *o) { int num_errs = suite(o); if (num_errs == 0) { PRINT(o, L_RESULT, "[%s] passed.\n", name); } else { PRINT(o, L_RESULT, "[%s] failed with %d error%s.\n", name, num_errs, num_errs > 1 ? "s" : ""); } return num_errs; } #define INIT_TEST() \ _tops _ops; int _tres = 0; #define SET_LOGLVL(lvl) \ _ops.loglvl = (lvl); #define RUN_SUITE(name) \ _tres += _run_suite(_test_##name, #name, &_ops) #define TEST_RESULT _tres #endif /* GET_TEST_DEFS*/
jan-kuechler/unitlib
d4882fc929740ae88f4cc47d8271923e188297ce
Added ul_copy(dst, src).
diff --git a/unitlib.c b/unitlib.c index 01728ec..577aff2 100644 --- a/unitlib.c +++ b/unitlib.c @@ -1,149 +1,159 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" #define static_assert(e) extern char (*STATIC_ASSERT(void))[sizeof(char[1 - 2*!(e)])] #define sizeofarray(ar) (sizeof((ar))/sizeof((ar)[0])) static FILE *dbg_out = NULL; bool _ul_debugging = false; UL_LINKAGE void _ul_debug(const char *fmt, ...) { assert(dbg_out); va_list ap; va_start(ap, fmt); vfprintf(dbg_out, fmt, ap); va_end(ap); } const char *_ul_symbols[] = { "m", "kg", "s", "A", "K", "mol", "Cd", "L", }; static_assert(sizeofarray(_ul_symbols) == NUM_BASE_UNITS); // The last error message static char errmsg[1024]; UL_LINKAGE void _ul_set_error(const char *func, int line, const char *fmt, ...) { snprintf(errmsg, 1024, "[%s:%d] ", func, line); size_t len = strlen(errmsg); va_list ap; va_start(ap, fmt); vsnprintf(errmsg + len, 1024 - len, fmt, ap); va_end(ap); } UL_API bool ul_equal(const unit_t *a, const unit_t *b) { if (!a || !b) { ERROR("Invalid parameters"); return false; } int i=0; for (; i < NUM_BASE_UNITS; ++i) { if (a->exps[i] != b->exps[i]) return false; } return ncmp(a->factor, b->factor) == 0; } UL_API bool ul_combine(unit_t *unit, const unit_t *with) { add_unit(unit, with, 1); return true; } +UL_API bool ul_copy(unit_t *dst, const unit_t *src) +{ + if (!dst || !src) { + ERROR("Invalid parameter"); + return false; + } + copy_unit(src, dst); + return true; +} + UL_API bool ul_inverse(unit_t *unit) { if (ncmp(unit->factor, 0.0) == 0) { ERROR("Cannot inverse 0.0"); return false; } int i=0; for (; i < NUM_BASE_UNITS; ++i) { unit->exps[i] = -unit->exps[i]; } unit->factor = 1/unit->factor; return true; } UL_API bool ul_sqrt(unit_t *unit) { int i=0; for (; i < NUM_BASE_UNITS; ++i) { if ((unit->exps[i] % 2) != 0) { ERROR("Cannot take root of an odd exponent"); return false; } } for (; i < NUM_BASE_UNITS; ++i) { unit->exps[i] /= 2; } unit->factor = _sqrtn(unit->factor); return false; } UL_API void ul_debugging(bool flag) { _ul_debugging = flag; } UL_API void ul_debugout(const char *path, bool append) { if (dbg_out && dbg_out != stderr) { debug("New debug file: %s", path ? path : "stderr"); fclose(dbg_out); } if (!path) { dbg_out = stderr; } else { dbg_out = fopen(path, append ? "a" : "w"); if (!dbg_out) { dbg_out = stderr; debug("Failed to open '%s' as debugout, using stderr.", path); } } } UL_API const char *ul_error(void) { return errmsg; } UL_API bool ul_init(void) { if(!dbg_out) dbg_out = stderr; debug("Initializing base rules"); _ul_init_rules(); const char *rulePath = getenv("UL_RULES"); if (rulePath) { debug("UL_RULES is set: %s", rulePath); if (!ul_load_rules(rulePath)) { ERROR("Failed to load rules: %s", errmsg); return false; } } return true; } UL_API void ul_quit(void) { _ul_free_rules(); if (dbg_out && dbg_out != stderr) fclose(dbg_out); } diff --git a/unitlib.h b/unitlib.h index 8a85d6b..61b5e5e 100644 --- a/unitlib.h +++ b/unitlib.h @@ -1,185 +1,193 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "config.h" #define UL_NAME "unitlib" #define UL_VERSION "0.3a1" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif #if defined(UL_EXPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllexport) #elif defined(UL_IMPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllimport) #else #define UL_API UL_LINKAGE #endif typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; #define U_ANY -1 typedef enum ul_format { UL_FMT_PLAIN, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, } ul_format_t; typedef struct ul_format_ops { bool sort; int order[NUM_BASE_UNITS]; } ul_fmtops_t; typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** * Deinitializes the unitlib and frees all. This function * has to be called at the end of the program. * internals resources. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ UL_API bool ul_equal(const unit_t *a, const unit_t *b); +/** + * Copies a unit into another + * @param dst Destination unit + * @param src Source unit + * @return success + */ +UL_API bool ul_copy(unit_t *dst, const unit_t *src); + /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ UL_API bool ul_combine(unit_t *unit, const unit_t *with); /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ static inline bool ul_print(const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) { return ul_fprint(stdout, unit, format, fmtp); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); #endif /*UNITLIB_H*/
jan-kuechler/unitlib
a3e2066e7384efd1ea22c2c302ee743a351f77df
Replaced runtime with static assert to ensure the right number of symbols.
diff --git a/unitlib.c b/unitlib.c index 5aeb8b6..01728ec 100644 --- a/unitlib.c +++ b/unitlib.c @@ -1,149 +1,149 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" +#define static_assert(e) extern char (*STATIC_ASSERT(void))[sizeof(char[1 - 2*!(e)])] #define sizeofarray(ar) (sizeof((ar))/sizeof((ar)[0])) static FILE *dbg_out = NULL; bool _ul_debugging = false; UL_LINKAGE void _ul_debug(const char *fmt, ...) { assert(dbg_out); va_list ap; va_start(ap, fmt); vfprintf(dbg_out, fmt, ap); va_end(ap); } const char *_ul_symbols[] = { "m", "kg", "s", "A", "K", "mol", "Cd", "L", }; +static_assert(sizeofarray(_ul_symbols) == NUM_BASE_UNITS); // The last error message static char errmsg[1024]; UL_LINKAGE void _ul_set_error(const char *func, int line, const char *fmt, ...) { snprintf(errmsg, 1024, "[%s:%d] ", func, line); size_t len = strlen(errmsg); va_list ap; va_start(ap, fmt); vsnprintf(errmsg + len, 1024 - len, fmt, ap); va_end(ap); } UL_API bool ul_equal(const unit_t *a, const unit_t *b) { if (!a || !b) { ERROR("Invalid parameters"); return false; } int i=0; for (; i < NUM_BASE_UNITS; ++i) { if (a->exps[i] != b->exps[i]) return false; } return ncmp(a->factor, b->factor) == 0; } UL_API bool ul_combine(unit_t *unit, const unit_t *with) { add_unit(unit, with, 1); return true; } UL_API bool ul_inverse(unit_t *unit) { if (ncmp(unit->factor, 0.0) == 0) { ERROR("Cannot inverse 0.0"); return false; } int i=0; for (; i < NUM_BASE_UNITS; ++i) { unit->exps[i] = -unit->exps[i]; } unit->factor = 1/unit->factor; return true; } UL_API bool ul_sqrt(unit_t *unit) { int i=0; for (; i < NUM_BASE_UNITS; ++i) { if ((unit->exps[i] % 2) != 0) { ERROR("Cannot take root of an odd exponent"); return false; } } for (; i < NUM_BASE_UNITS; ++i) { unit->exps[i] /= 2; } unit->factor = _sqrtn(unit->factor); return false; } UL_API void ul_debugging(bool flag) { _ul_debugging = flag; } UL_API void ul_debugout(const char *path, bool append) { if (dbg_out && dbg_out != stderr) { debug("New debug file: %s", path ? path : "stderr"); fclose(dbg_out); } if (!path) { dbg_out = stderr; } else { dbg_out = fopen(path, append ? "a" : "w"); if (!dbg_out) { dbg_out = stderr; debug("Failed to open '%s' as debugout, using stderr.", path); } } } UL_API const char *ul_error(void) { return errmsg; } UL_API bool ul_init(void) { - assert(sizeofarray(_ul_symbols) == NUM_BASE_UNITS); - if(!dbg_out) dbg_out = stderr; debug("Initializing base rules"); _ul_init_rules(); const char *rulePath = getenv("UL_RULES"); if (rulePath) { debug("UL_RULES is set: %s", rulePath); if (!ul_load_rules(rulePath)) { ERROR("Failed to load rules: %s", errmsg); return false; } } return true; } UL_API void ul_quit(void) { _ul_free_rules(); if (dbg_out && dbg_out != stderr) fclose(dbg_out); }
jan-kuechler/unitlib
7f562fcd1458fb395c14bcdccaebc12894a221ab
Some restructuring in parser.c
diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..8482439 --- /dev/null +++ b/Makefile @@ -0,0 +1,86 @@ +## +# Makefile for unitlib +## + +CC = gcc +CFLAGS = -O2 -std=c99 -Wall -Wextra + +AR = ar +RANLIB = ranlib + +TARGET = libunit.a + +DLL = libunit.dll +IMPLIB = libunit.lib + +HEADER = unitlib.h + +SRCFILES = unitlib.c parser.c format.c +HDRFILES = unitlib.h intern.h + +LIB_INSTALL = /g/Programmieren/lib +HDR_INSTALL = /g/Programmieren/include + +OBJFILES = unitlib.o parser.o format.o + +TESTPROG = _test.exe +SMASHPROG = _smash.exe + +UNITTEST = ultest + +.PHONY: test clean allclean + +all: $(TARGET) + +dll: $(DLL) + +install-dll: dll + cp $(DLL) $(LIB_INSTALL) + cp $(IMPLIB) $(LIB_INSTALL) + cp $(HEADER) $(HDR_INSTALL) + +test: $(TESTPROG) + @./$(TESTPROG) + +utest: $(UNITTEST) + @./$(UNITTEST) + +smash: $(SMASHPROG) + @./$(SMASHPROG) + +$(TARGET): $(OBJFILES) + @$(AR) rc $(TARGET) $(OBJFILES) + @$(RANLIB) $(TARGET) + +$(DLL): $(SRCFILES) $(HDRFILES) + @$(CC) $(CFLAGS) -shared -o $(DLL) $(SRCFILES) -Wl,--out-implib,$(IMPLIB) + +unitlib.o: unitlib.c $(HDRFILES) + @$(CC) $(CFLAGS) -o unitlib.o -c unitlib.c + +parser.o: parser.c $(HDRFILES) + @$(CC) $(CFLAGS) -o parser.o -c parser.c + +format.o: format.c $(HDRFILES) + @$(CC) $(CFLAGS) -o format.o -c format.c + +$(TESTPROG): $(TARGET) _test.c + @$(CC) -o $(TESTPROG) -g -L. _test.c -lunit + +$(SMASHPROG): $(TARGET) _test.c + @$(CC) -o $(SMASHPROG) -L. -DSMASH _test.c -lunit + +$(UNITTEST): $(TARGET) unittest.c + @$(CC) -o $(UNITTEST) -L. unittest.c -lunit + +clean: + @rm -f $(OBJFILES) + @rm -f $(TESTPROG) + @rm -f $(SMASHPROG) + @rm -f $(UNITTEST) + @rm -f debug.log + +allclean: clean + @rm -f $(TARGET) + @rm -f $(DLL) + @rm -f $(IMPLIB) diff --git a/_test.c b/_test.c new file mode 100644 index 0000000..e970183 --- /dev/null +++ b/_test.c @@ -0,0 +1,145 @@ +#include <stdio.h> + +#include "unitlib.h" + +#ifndef SMASH +int main(void) +{ + printf("Testing %s\n", UL_FULL_NAME); + + ul_debugging(true); + ul_debugout("debug.log", false); + if (!ul_init()) { + printf("init failed"); + } + + if (!ul_parse_rule(" N= 1 kg m s^-2 ")) { + printf("Error: %s\n", ul_error()); + } + + unit_t unit; + if (!ul_parse("0.2 N^2 * 0.75 m^-1", &unit)) { + printf("Error: %s\n", ul_error()); + } + + + ul_fmtops_t fmtop; + fmtop.sort = true; + fmtop.order[0] = U_LEMMING; + fmtop.order[1] = U_KILOGRAM; + fmtop.order[2] = U_METER; + fmtop.order[3] = U_ANY; + + printf("0.2 N^2 * 0.75 m^-1 = "); + if (!ul_fprint(stdout, &unit, UL_FMT_PLAIN, &fmtop)) { + printf("Error: %s\n", ul_error()); + } + printf("\n"); + + char buffer[1024]; + if (!ul_snprint(buffer, 1024, &unit, UL_FMT_PLAIN, NULL)) { + printf("Error: %s\n", ul_error()); + } + printf("snprint => '%s'\n", buffer); + + + { + printf("\n----------\n"); + + fmtop.order[2] = U_ANY; + unit_t n; + ul_parse("N", &n); + printf("1 N = "); + ul_print(&n, UL_FMT_PLAIN, &fmtop); + printf("\n----------\n\n"); + } + + ul_print( &unit, UL_FMT_LATEX_FRAC, &fmtop); + printf("\n"); + ul_print(&unit, UL_FMT_LATEX_INLINE, NULL); + printf("\n"); + + { + unit_t unit; + ul_parse("s^-1", &unit); + printf("LaTeX: "); + ul_print(&unit, UL_FMT_LATEX_FRAC, NULL); + printf("\n"); + } + + ul_quit(); + + return 0; +} +#else + +void smashit(const char *str, bool asRule) +{ + bool ok = true; + if (asRule) { + ok = ul_parse_rule(str); + } + else { + unit_t u; + ok = ul_parse(str, &u); + } + if (ok) { + fprintf(stderr, "successfull?\n"); + } + else { + fprintf(stderr, "error: %s\n", ul_error()); + } +} + +int main(void) +{ + ul_init(); + + srand(time(NULL)); + + { + fprintf(stderr, "Smash 1: "); + char test[] = "dil^aöjf lkfjda gäklj#ä#jadf klnhöklj213jl^^- kjäjre"; + smashit(test, false); + + fprintf(stderr, "Smash 2: "); + smashit(test, true); + } + + { + size_t size = 4096; + int *_test = malloc(size); + int i=0; + for (; i < size / sizeof(int); ++i) { + _test[i] = rand(); + } + char *test = (char*)_test; + for (i=0; i < size; ++i) { + if (!test[i]) + test[i] = 42; + } + + fprintf(stderr, "%4d bytes garbage: ", size ); + smashit(test, false); + fprintf(stderr, "as rule: "); + smashit(test, true); + } + + { + char test[] = " \t\t\n\n\r kg = "; + + printf("Evil: "); + smashit(test, true); + } + + { + char test[] = "kg^2!"; + printf("test: "); + ul_debugging(true); + smashit(test, false); + } + + return 0; +} + +#endif diff --git a/config.h b/config.h new file mode 100644 index 0000000..1dd0275 --- /dev/null +++ b/config.h @@ -0,0 +1,36 @@ +#ifndef UL_CONFIG_H +#define UL_CONFIG_H + +/** + * To support long double uncomment the following line + */ +//#define UL_HAS_LONG_DOUBLE + +// Don't change anything beyond this line +//----------------------------------------------------------------------------- + +#ifdef UL_HAS_LONG_DOUBLE + +typedef long double ul_number; +#define _strton strtold +#define _fabsn fabsl +#define _sqrtn sqrtl +#define _pown pow + +#define N_FMT "%Lg" +#define N_EPSILON LDBL_EPSILON + +#else + +typedef double ul_number; +#define _strton strtod +#define _fabsn fabs +#define _sqrtn sqrt +#define _pown powl + +#define N_FMT "%g" +#define N_EPSILON DBL_EPSILON + +#endif + +#endif /*UL_CONFIG_H*/ diff --git a/format.c b/format.c new file mode 100644 index 0000000..eee6414 --- /dev/null +++ b/format.c @@ -0,0 +1,366 @@ +#include <assert.h> +#include <stdio.h> +#include <string.h> +#include "intern.h" +#include "unitlib.h" + +struct status +{ + bool (*putc)(char c, void *info); + void *info; + + const unit_t *unit; + ul_format_t format; + ul_fmtops_t *fmtp; + void *extra; +}; + +typedef bool (*printer_t)(struct status*,int,int,bool*); + +struct f_info +{ + FILE *out; +}; + +static bool f_putc(char c, void *i) +{ + struct f_info *info = i; + return fputc(c, info->out) == c; +} + +struct sn_info +{ + char *buffer; + int idx; + int size; +}; + +static bool sn_putc(char c, void *i) +{ + struct sn_info *info = i; + if (info->idx >= info->size) { + return false; + } + info->buffer[info->idx++] = c; + return true; +} + +#define _putc(s,c) (s)->putc((c),(s)->info) + +#define CHECK(x) do { if (!(x)) return false; } while (0) + +static bool _puts(struct status *s, const char *str) +{ + while (*str) { + char c = *str++; + if (!_putc(s, c)) + return false; + } + return true; +} + +static bool _putd(struct status *stat, int n) +{ + char buffer[1024]; + snprintf(buffer, 1024, "%d", n); + return _puts(stat, buffer); +} + +static bool _putn(struct status *stat, ul_number n) +{ + char buffer[1024]; + snprintf(buffer, 1024, N_FMT, n); + return _puts(stat, buffer); +} + +static void getnexp(ul_number n, ul_number *mantissa, int *exp) +{ + bool neg = false; + if (n < 0) { + neg = true; + n = -n; + } + if ((ncmp(n, 10.0) == -1) && (ncmp(n, 1.0) == 1)) { + *mantissa = neg ? -n : n; + *exp = 0; + return; + } + else if (ncmp(n, 10.0) > -1) { + int e = 0; + do { + e++; + n /= 10; + } while (ncmp(n, 10.0) == 1); + *exp = e; + *mantissa = neg ? -n : n; + } + else if (ncmp(n, 1.0) < 1) { + int e = 0; + while (ncmp(n, 1.0) == -1) { + e--; + n *= 10; + } + *exp = e; + *mantissa = neg ? -n : n; + } +} + +// global for testing purpose, it's not declared in the header +void _ul_getnexp(ul_number n, ul_number *m, int *e) +{ + getnexp(n, m, e); +} + +static bool print_sorted(struct status *stat, printer_t func, bool *first) +{ + bool printed[NUM_BASE_UNITS] = {0}; + bool _first = true; + int i=0; + + bool *fptr = first ? first : &_first; + + // Print any sorted order + for (; i < NUM_BASE_UNITS; ++i) { + int unit = stat->fmtp->order[i]; + if (unit == U_ANY) { + break; + } + int exp = stat->unit->exps[unit]; + CHECK(func(stat, unit, exp , fptr)); + printed[unit] = true; + } + // Print the rest + for (i=0; i < NUM_BASE_UNITS; ++i) { + if (!printed[i]) { + int exp = stat->unit->exps[i]; + if (exp != 0) { + CHECK(func(stat, i, exp , fptr)); + } + } + } + return true; +} + +static bool print_normal(struct status *stat, printer_t func, bool *first) +{ + int i=0; + bool _first = true; + bool *fptr = first ? first : &_first; + for (; i < NUM_BASE_UNITS; ++i) { + CHECK(func(stat,i,stat->unit->exps[i], fptr)); + } + return true; +} + +// Begin - plain +static bool _plain_one(struct status* stat, int unit, int exp, bool *first) +{ + if (exp == 0) + return true; + + if (!*first) + CHECK(_putc(stat, ' ')); + + CHECK(_puts(stat, _ul_symbols[unit])); + // and the exponent + if (exp != 1) { + CHECK(_putc(stat, '^')); + CHECK(_putd(stat, exp)); + } + *first = false; + return true; +} + +static bool p_plain(struct status *stat) +{ + CHECK(_putn(stat, stat->unit->factor)); + CHECK(_putc(stat, ' ')); + if (stat->fmtp && stat->fmtp->sort) { + return print_sorted(stat, _plain_one, NULL); + } + else { + return print_normal(stat, _plain_one, NULL); + } + return true; +} +// End - plain + +// Begin - LaTeX +static bool _latex_one(struct status *stat, int unit, int exp, bool *first) +{ + if (exp == 0) + return true; + if (stat->extra) { + bool pos = *(bool*)stat->extra; + if (exp > 0 && !pos) + return true; + if (exp < 0) { + if (pos) + return true; + exp = -exp; + } + } + if (!*first) + CHECK(_putc(stat, ' ')); + CHECK(_puts(stat, "\\text{")); + if (!*first) + CHECK(_putc(stat, ' ')); + CHECK(_puts(stat, _ul_symbols[unit])); + CHECK(_puts(stat, "}")); + if (exp != 1) { + CHECK(_putc(stat, '^')); + CHECK(_putc(stat, '{')); + CHECK(_putd(stat, exp)); + CHECK(_putc(stat, '}')); + } + *first = false; + return true; +} + +static bool p_latex_frac(struct status *stat) +{ + bool first = true; + bool positive = true; + stat->extra = &positive; + + ul_number m; int e; + getnexp(stat->unit->factor, &m, &e); + + CHECK(_puts(stat, "\\frac{")); + + if (e >= 0) { + CHECK(_putn(stat, m)); + if (e > 0) { + CHECK(_puts(stat, " \\cdot 10^{")); + CHECK(_putd(stat, e)); + CHECK(_putc(stat, '}')); + } + first = false; + } + + if (stat->fmtp && stat->fmtp->sort) { + print_sorted(stat, _latex_one, &first); + } + else { + print_normal(stat, _latex_one, &first); + } + + if (first) { + // nothing up there... + CHECK(_putc(stat, '1')); + } + CHECK(_puts(stat, "}{")); + + first = true; + positive = false; + + if (e < 0) { + e = -e; + CHECK(_putn(stat, m)); + if (e > 0) { + CHECK(_puts(stat, " \\cdot 10^{")); + CHECK(_putd(stat, e)); + CHECK(_putc(stat, '}')); + } + first = false; + } + + if (stat->fmtp && stat->fmtp->sort) { + print_sorted(stat, _latex_one, &first); + } + else { + print_normal(stat, _latex_one, &first); + } + if (first) { + CHECK(_putc(stat, '1')); + } + CHECK(_putc(stat, '}')); + return true; +} + +static bool p_latex_inline(struct status *stat) +{ + int i=0; + bool first = false; + CHECK(_putc(stat, '$')); + + ul_number m; int e; + getnexp(stat->unit->factor, &m, &e); + CHECK(_putn(stat, m)); + if (e != 0) { + CHECK(_puts(stat, " \\cdot 10^{")); + CHECK(_putd(stat, e)); + CHECK(_putc(stat, '}')); + } + + for (i=0; i < NUM_BASE_UNITS; ++i) { + int exp = stat->unit->exps[i]; + if (exp != 0) { + CHECK(_latex_one(stat, i, exp, &first)); + } + } + CHECK(_putc(stat, '$')); + return true; +} +// End - LaTeX + +static bool _print(struct status *stat) +{ + debug("ignoring a factor of "N_FMT, stat->unit->factor); + switch (stat->format) { + case UL_FMT_PLAIN: + return p_plain(stat); + + case UL_FMT_LATEX_FRAC: + return p_latex_frac(stat); + + case UL_FMT_LATEX_INLINE: + return p_latex_inline(stat); + + default: + ERROR("Unknown format: %d", stat->format); + return false; + } +} + +UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, + ul_fmtops_t *fmtp) +{ + struct f_info info = { + .out = f, + }; + + struct status status = { + .putc = f_putc, + .info = &info, + .unit = unit, + .format = format, + .fmtp = fmtp, + .extra = NULL, + }; + + return _print(&status); +} + +UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, + ul_format_t format, ul_fmtops_t *fmtp) +{ + struct sn_info info = { + .buffer = buffer, + .size = buflen, + .idx = 0, + }; + + struct status status = { + .putc = sn_putc, + .info = &info, + .unit = unit, + .format = format, + .fmtp = fmtp, + .extra = NULL, + }; + + memset(buffer, 0, buflen); + + return _print(&status); +} diff --git a/intern.h b/intern.h new file mode 100644 index 0000000..102c40d --- /dev/null +++ b/intern.h @@ -0,0 +1,58 @@ +#ifndef UL_INTERN_H +#define UL_INTERN_H + +#include <float.h> +#include <math.h> +#include "unitlib.h" + +extern const char *_ul_symbols[]; +extern size_t _ul_symlens[]; + +extern bool _ul_debugging; +UL_LINKAGE void _ul_debug(const char *fmt, ...); +#define debug(fmt,...) \ + do { \ + if (_ul_debugging) _ul_debug("[ul - %s] " fmt "\n",\ + __func__, ##__VA_ARGS__);\ + } while(0) + + +UL_LINKAGE void _ul_set_error(const char *func, int line, const char *fmt, ...); +#define ERROR(msg, ...) _ul_set_error(__func__, __LINE__, msg, ##__VA_ARGS__) + +UL_LINKAGE void _ul_init_rules(void); +UL_LINKAGE void _ul_free_rules(void); + +#define EXPS_SIZE(unit) (sizeof((unit)->exps[0]) * NUM_BASE_UNITS) + +static inline void init_unit(unit_t *unit) +{ + memset(unit->exps, 0, EXPS_SIZE(unit)); + unit->factor = 1.0; +} + +static inline void copy_unit(const unit_t *src, unit_t *dst) +{ + memcpy(dst->exps, src->exps, EXPS_SIZE(dst)); + dst->factor = src->factor; +} + +static inline void add_unit(unit_t *to, const unit_t *other, int times) +{ + int i=0; + for (; i < NUM_BASE_UNITS; ++i) { + to->exps[i] += (times * other->exps[i]); + } + to->factor *= _pown(other->factor, times); +} + +static inline int ncmp(ul_number a, ul_number b) +{ + if (_fabsn(a-b) < N_EPSILON) + return 0; + if (a < b) + return -1; + return 1; +} + +#endif /*UL_INTERN_H*/ diff --git a/parser.c b/parser.c new file mode 100644 index 0000000..872f6e4 --- /dev/null +++ b/parser.c @@ -0,0 +1,448 @@ +#include <assert.h> +#include <ctype.h> +#include <stdarg.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include "intern.h" +#include "unitlib.h" + +typedef struct rule +{ + const char *symbol; + unit_t unit; + bool force; + struct rule *next; +} rule_t; + +// A list of all rules +static rule_t *rules = NULL; +// The base rules +static rule_t base_rules[NUM_BASE_UNITS]; + +#define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) + +struct parser_state +{ + int sign; +}; + +enum { + MAX_SYM_SIZE = 128, + MAX_ITEM_SIZE = 1024, +}; + +// Returns the last rule in the list +static rule_t *last_rule(void) +{ + rule_t *cur = rules; + while (cur) { + if (!cur->next) + return cur; + cur = cur->next; + } + assert(false); + return NULL; +} + +static rule_t *get_rule(const char *sym) +{ + assert(sym); + rule_t *cur = rules; + while (cur) { + if (strcmp(cur->symbol, sym) == 0) + return cur; + cur = cur->next; + } + return NULL; +} + +static size_t skipspace(const char *text, size_t start) +{ + assert(text); + size_t i = start; + while (text[i] && isspace(text[i])) + i++; + return i; +} + +static size_t nextspace(const char *text, size_t start) +{ + assert(text); + size_t i=start; + while (text[i] && !isspace(text[i])) + i++; + return i; +} + +static bool try_parse_factor(const char *str, unit_t *unit, + struct parser_state *state) +{ + assert(str); assert(unit); assert(state); + char *endptr; + ul_number f = _strton(str, &endptr); + if (endptr && *endptr) { + debug("'%s' is not a factor", str); + return false; + } + unit->factor *= f; + return true; +} + +static bool is_special(const char *str) +{ + assert(str); + if (strlen(str) == 1) { + switch (str[0]) { + case '*': + return true; + case '/': + return true; + } + } + return false; +} + +static bool handle_special(const char *str, struct parser_state *state) +{ + assert(str); assert(state); + switch (str[0]) { + case '*': + // ignore + return true; + + case '/': + state->sign *= -1; + return true; + } + ERROR("Internal error: is_special/handle_special missmatch for '%s'.", str); + return false; +} + +static bool parse_item(const char *str, unit_t *unit, struct parser_state *state) +{ + assert(str); assert(unit); assert(state); + debug("Parse item: '%s'", str); + + // Split symbol and exponent + char symbol[MAX_SYM_SIZE]; + int exp = 1; + + size_t symend = 0; + while (str[symend] && str[symend] != '^') + symend++; + + if (symend >= MAX_SYM_SIZE) { + ERROR("Symbol to long"); + return false; + } + strncpy(symbol, str, symend); + symbol[symend] = '\0'; + + if (str[symend]) { + // The '^' should not be the last value of the string + if (!str[symend+1]) { + ERROR("Missing exponent after '^' while parsing '%s'", str); + return false; + } + + // Parse the exponent + char *endptr = NULL; + exp = strtol(str+symend+1, &endptr, 10); + + // the whole exp string was valid only if *endptr is '\0' + if (endptr && *endptr) { + ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); + return false; + } + } + debug("Exponent is %d", exp); + + // Find the matching rule + rule_t *rule = get_rule(symbol); + if (!rule) { + ERROR("No matching rule found for '%s'", symbol); + return false; + } + + // And add the definitions + add_unit(unit, &rule->unit, state->sign * exp); + + return true; +} + +UL_API bool ul_parse(const char *str, unit_t *unit) +{ + if (!str || !unit) { + ERROR("Invalid paramters"); + return false; + } + debug("Parse unit: '%s'", str); + + struct parser_state state; + state.sign = 1; + + init_unit(unit); + + size_t len = strlen(str); + size_t start = 0; + do { + char this_item[MAX_ITEM_SIZE ]; + + // Skip leading whitespaces + start = skipspace(str, start); + // And find the next whitespace + size_t end = nextspace(str, start); + + if (end == start) {// End of string + break; + } + // sanity check + if ((end - start) > MAX_ITEM_SIZE ) { + ERROR("Item too long"); + return false; + } + + // copy the item out of the string + strncpy(this_item, str+start, end-start); + this_item[end-start] = '\0'; + + if (is_special(this_item)) { + if (!handle_special(this_item, &state)) + return false; + } + else if (try_parse_factor(this_item, unit, &state)) { + // nothing todo + } + else { + // and parse it + if (!parse_item(this_item, unit, &state)) + return false; + } + + start = end + 1; + } while (start < len); + + return true; +} + +static bool add_rule(const char *symbol, const unit_t *unit, bool force) +{ + assert(symbol); assert(unit); + rule_t *rule = malloc(sizeof(*rule)); + if (!rule) { + ERROR("Failed to allocate memory"); + return false; + } + rule->next = NULL; + + rule->symbol = symbol; + rule->force = force; + + copy_unit(unit, &rule->unit); + + rule_t *last = last_rule(); + last->next = rule; + + return true; +} + +static bool rm_rule(rule_t *rule) +{ + assert(rule); + if (rule->force) { + ERROR("Cannot remove forced rule"); + return false; + } + + rule_t *cur = dynamic_rules; // base rules cannot be removed + rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; + + while (cur && cur != rule) { + prev = cur; + cur = cur->next; + } + + if (cur != rule) { + ERROR("Rule not found."); + return false; + } + + prev->next = rule->next; + return true; +} + +static bool valid_symbol(const char *sym) +{ + assert(sym); + while (*sym) { + if (!isalpha(*sym)) + return false; + sym++; + } + return true; +} + +static char *get_symbol(const char *rule, size_t splitpos, bool *force) +{ + assert(rule); assert(force); + size_t skip = skipspace(rule, 0); + size_t symend = nextspace(rule, skip); + if (symend > splitpos) + symend = splitpos; + + if (skipspace(rule,symend) != splitpos) { + // rule was something like "a b = kg" + ERROR("Invalid symbol, whitespaces are not allowed."); + return NULL; + } + + if ((symend-skip) > MAX_SYM_SIZE) { + ERROR("Symbol to long"); + return NULL; + } + if ((symend-skip) == 0) { + ERROR("Empty symbols are not allowed."); + return NULL; + } + + if (rule[skip] == '!') { + debug("Forced rule."); + *force = true; + skip++; + } + else { + *force = false; + } + + debug("Allocate %d bytes", symend-skip + 1); + char *symbol = malloc(symend-skip + 1); + if (!symbol) { + ERROR("Failed to allocate memory"); + return NULL; + } + + strncpy(symbol, rule + skip, symend-skip); + symbol[symend-skip] = '\0'; + debug("Symbol is '%s'", symbol); + + return symbol; +} + +// parses a string like "symbol = def" +UL_API bool ul_parse_rule(const char *rule) +{ + if (!rule) { + ERROR("Invalid parameter"); + return false; + } + + // split symbol and definition + size_t len = strlen(rule); + size_t splitpos = 0; + + debug("Parsing rule '%s'", rule); + + size_t i=0; + for (; i < len; ++i) { + if (rule[i] == '=') { + debug("Split at %d", i); + splitpos = i; + break; + } + } + if (!splitpos) { + ERROR("Missing '=' in rule definition '%s'", rule); + return false; + } + + // Get the symbol + bool force = false; + char *symbol = get_symbol(rule, splitpos, &force); + if (!symbol) + return false; + + if (!valid_symbol(symbol)) { + ERROR("Symbol '%s' is invalid.", symbol); + free(symbol); + return false; + } + + rule_t *old_rule = NULL; + if ((old_rule = get_rule(symbol)) != NULL) { + if (old_rule->force || !force) { + ERROR("You may not redefine '%s'", symbol); + free(symbol); + return false; + } + // remove the old rule, so it cannot be used in the definition + // of the new one, so something like "!R = R" is not possible + if (force) { + if (!rm_rule(old_rule)) { + free(symbol); + return false; + } + } + } + + rule = rule + splitpos + 1; // ommiting the '=' + debug("Rest definition is '%s'", rule); + + unit_t unit; + if (!ul_parse(rule, &unit)) { + free(symbol); + return false; + } + + return add_rule(symbol, &unit, force); +} + +UL_API bool ul_load_rules(const char *path) +{ + FILE *f = fopen(path, "r"); + if (!f) { + ERROR("Failed to open file '%s'", path); + return false; + } + + bool ok = true; + char line[1024]; + while (fgets(line, 1024, f)) { + size_t skip = skipspace(line, 0); + if (!line[skip] || line[skip] == '#') + continue; // empty line or comment + ok = ul_parse_rule(line); + if (!ok) + break; + } + fclose(f); + return ok; +} + +UL_LINKAGE void _ul_init_rules(void) +{ + int i=0; + for (; i < NUM_BASE_UNITS; ++i) { + base_rules[i].symbol = _ul_symbols[i]; + + init_unit(&base_rules[i].unit); + base_rules[i].force = true; + base_rules[i].unit.exps[i] = 1; + + base_rules[i].next = &base_rules[i+1]; + } + dynamic_rules = NULL; + rules = base_rules; +} + +UL_LINKAGE void _ul_free_rules(void) +{ + debug("Freeing rule list"); + rule_t *cur = dynamic_rules; + while (cur) { + rule_t *next = cur->next; + free((char*)cur->symbol); + free(cur); + cur = next; + } +} diff --git a/unitlib.c b/unitlib.c new file mode 100644 index 0000000..5aeb8b6 --- /dev/null +++ b/unitlib.c @@ -0,0 +1,149 @@ +#include <assert.h> +#include <ctype.h> +#include <stdarg.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "intern.h" +#include "unitlib.h" + +#define sizeofarray(ar) (sizeof((ar))/sizeof((ar)[0])) + +static FILE *dbg_out = NULL; +bool _ul_debugging = false; +UL_LINKAGE void _ul_debug(const char *fmt, ...) +{ + assert(dbg_out); + va_list ap; + va_start(ap, fmt); + vfprintf(dbg_out, fmt, ap); + va_end(ap); +} + +const char *_ul_symbols[] = { + "m", "kg", "s", "A", "K", "mol", "Cd", "L", +}; + +// The last error message +static char errmsg[1024]; +UL_LINKAGE void _ul_set_error(const char *func, int line, const char *fmt, ...) +{ + snprintf(errmsg, 1024, "[%s:%d] ", func, line); + size_t len = strlen(errmsg); + + va_list ap; + va_start(ap, fmt); + vsnprintf(errmsg + len, 1024 - len, fmt, ap); + va_end(ap); +} + +UL_API bool ul_equal(const unit_t *a, const unit_t *b) +{ + if (!a || !b) { + ERROR("Invalid parameters"); + return false; + } + + int i=0; + for (; i < NUM_BASE_UNITS; ++i) { + if (a->exps[i] != b->exps[i]) + return false; + } + return ncmp(a->factor, b->factor) == 0; +} + +UL_API bool ul_combine(unit_t *unit, const unit_t *with) +{ + add_unit(unit, with, 1); + return true; +} + +UL_API bool ul_inverse(unit_t *unit) +{ + if (ncmp(unit->factor, 0.0) == 0) { + ERROR("Cannot inverse 0.0"); + return false; + } + + int i=0; + for (; i < NUM_BASE_UNITS; ++i) { + unit->exps[i] = -unit->exps[i]; + } + + unit->factor = 1/unit->factor; + return true; +} + +UL_API bool ul_sqrt(unit_t *unit) +{ + int i=0; + for (; i < NUM_BASE_UNITS; ++i) { + if ((unit->exps[i] % 2) != 0) { + ERROR("Cannot take root of an odd exponent"); + return false; + } + } + for (; i < NUM_BASE_UNITS; ++i) { + unit->exps[i] /= 2; + } + unit->factor = _sqrtn(unit->factor); + return false; +} + +UL_API void ul_debugging(bool flag) +{ + _ul_debugging = flag; +} + +UL_API void ul_debugout(const char *path, bool append) +{ + if (dbg_out && dbg_out != stderr) { + debug("New debug file: %s", path ? path : "stderr"); + fclose(dbg_out); + } + if (!path) { + dbg_out = stderr; + } + else { + dbg_out = fopen(path, append ? "a" : "w"); + if (!dbg_out) { + dbg_out = stderr; + debug("Failed to open '%s' as debugout, using stderr.", path); + } + } +} + +UL_API const char *ul_error(void) +{ + return errmsg; +} + +UL_API bool ul_init(void) +{ + assert(sizeofarray(_ul_symbols) == NUM_BASE_UNITS); + + if(!dbg_out) + dbg_out = stderr; + + debug("Initializing base rules"); + _ul_init_rules(); + + const char *rulePath = getenv("UL_RULES"); + if (rulePath) { + debug("UL_RULES is set: %s", rulePath); + if (!ul_load_rules(rulePath)) { + ERROR("Failed to load rules: %s", errmsg); + return false; + } + } + + return true; +} + +UL_API void ul_quit(void) +{ + _ul_free_rules(); + if (dbg_out && dbg_out != stderr) + fclose(dbg_out); +} diff --git a/unitlib.h b/unitlib.h new file mode 100644 index 0000000..8a85d6b --- /dev/null +++ b/unitlib.h @@ -0,0 +1,185 @@ +/** + * unitlib.h - Main header for the unitlib + */ +#ifndef UNITLIB_H +#define UNITLIB_H + +#include <stdbool.h> +#include <stddef.h> +#include <stdio.h> + +#include "config.h" + +#define UL_NAME "unitlib" +#define UL_VERSION "0.3a1" +#define UL_FULL_NAME UL_NAME "-" UL_VERSION + +#ifdef __cplusplus +#define UL_LINKAGE extern "C" +#else +#define UL_LINKAGE +#endif + +#if defined(UL_EXPORT_DLL) +#define UL_API UL_LINKAGE __declspec(dllexport) +#elif defined(UL_IMPORT_DLL) +#define UL_API UL_LINKAGE __declspec(dllimport) +#else +#define UL_API UL_LINKAGE +#endif + +typedef enum base_unit +{ + U_METER, + U_KILOGRAM, + U_SECOND, + U_AMPERE, + U_KELVIN, + U_MOL, + U_CANDELA, + U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ + NUM_BASE_UNITS, +} base_unit_t; + +#define U_ANY -1 + +typedef enum ul_format +{ + UL_FMT_PLAIN, + UL_FMT_LATEX_FRAC, + UL_FMT_LATEX_INLINE, +} ul_format_t; + +typedef struct ul_format_ops +{ + bool sort; + int order[NUM_BASE_UNITS]; +} ul_fmtops_t; + +typedef struct unit +{ + int exps[NUM_BASE_UNITS]; + ul_number factor; +} unit_t; + +/** + * Initializes the unitlib. Has to be called before any + * other ul_* function (excl. the ul_debug* functions). + * @return success + */ +UL_API bool ul_init(void); + +/** + * Deinitializes the unitlib and frees all. This function + * has to be called at the end of the program. + * internals resources. + */ +UL_API void ul_quit(void); + +/** + * Enables or disables debugging messages + * @param flag Enable = true + */ +UL_API void ul_debugging(bool flag); + +/** + * Sets the debug output stream + * @param out The outstream + */ +UL_API void ul_debugout(const char *path, bool append); + +/** + * Returns the last error message + * @return The last error message + */ +UL_API const char *ul_error(void); + +/** + * Parses a rule and adds it to the rule list + * @param rule The rule to parse + * @return success + */ +UL_API bool ul_parse_rule(const char *rule); + +/** + * Loads a rule file + * @param path Path to the file + * @return success + */ +UL_API bool ul_load_rules(const char *path); + +/** + * Parses the unit definition from str to unit + * @param str The unit definition + * @param unit The parsed unit will be stored here + * @return success + */ +UL_API bool ul_parse(const char *str, unit_t *unit); + +/** + * Compares two units + * @param a A unit + * @param b Another unit + * @return true if both units are equal + */ +UL_API bool ul_equal(const unit_t *a, const unit_t *b); + +/** + * Multiplies a unit to a unit. + * @param unit One factor and destination of the operation + * @param with The other unit + * @return success + */ +UL_API bool ul_combine(unit_t *unit, const unit_t *with); + +/** + * Builds the inverse of a unit + * @param unit The unit + * @return success + */ +UL_API bool ul_inverse(unit_t *unit); + +/** + * Takes the square root of the unit + * @param unit The unit + * @return success + */ +UL_API bool ul_sqrt(unit_t *unit); + +/** + * Prints the unit to a file according to the format + * @param file The file + * @param unit The unit + * @param format The format + * @param fmtp Additional format parameters + * @return success + */ +UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, + ul_fmtops_t *fmtp); + +/** + * Prints the unit to stdout according to the format + * @param unit The unit + * @param format The format + * @param fmtp Additional format parameters + * @return success + */ +static inline bool ul_print(const unit_t *unit, ul_format_t format, + ul_fmtops_t *fmtp) +{ + return ul_fprint(stdout, unit, format, fmtp); +} + +/** + * Prints the unit to a buffer according to the format + * @param buffer The buffer + * @param buflen Length of the buffer + * @param unit The unit + * @param format The format + * @param fmtp Additional format parameters + * @return success + */ +UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, + ul_format_t format, ul_fmtops_t *fmtp); + +#endif /*UNITLIB_H*/ diff --git a/unittest.c b/unittest.c new file mode 100644 index 0000000..e766192 --- /dev/null +++ b/unittest.c @@ -0,0 +1,430 @@ +#ifndef GET_TEST_DEFS +#include <stdarg.h> +#include <stdlib.h> +#include <string.h> +#include "unitlib.h" +#include "intern.h" + +// yay, self include (-: +#define GET_TEST_DEFS +#include "unittest.c" +#undef GET_TEST_DEFS + +static unit_t make_unit(ul_number fac, ...) +{ + va_list args; + va_start(args, fac); + + unit_t u; + memset(u.exps, 0, NUM_BASE_UNITS * sizeof(int)); + u.factor = fac; + + int b = va_arg(args, int); + int e = va_arg(args, int); + + while (b || e) { + u.exps[b] = e; + b = va_arg(args, int); + e = va_arg(args, int); + } + + return u; +} +#define MAKE_UNIT(...) make_unit(__VA_ARGS__,0,0,0) + +TEST_SUITE(parser) + TEST + unit_t u; + CHECK(ul_parse("m", &u)); + FAIL_MSG("Error: %s", ul_error()); + CHECK(u.exps[U_METER] == 1); + + int i=0; + for (; i < NUM_BASE_UNITS; ++i) { + if (i != U_METER) { + CHECK(u.exps[i] == 0); + } + } + + CHECK(ncmp(u.factor, 1.0) == 0); + END_TEST + + TEST + unit_t u; + + CHECK(ul_parse(" \n kg^2 * m ", &u)); + FAIL_MSG("Error: %s", ul_error()); + CHECK(u.exps[U_KILOGRAM] == 2); + CHECK(u.exps[U_METER] == 1); + CHECK(u.exps[U_SECOND] == 0); + CHECK(ncmp(u.factor, 1.0) == 0); + + CHECK(ul_parse("2 Cd 7 s^-1", &u)); + FAIL_MSG("Error: %s", ul_error()); + CHECK(u.exps[U_CANDELA] == 1); + CHECK(u.exps[U_SECOND] == -1); + CHECK(ncmp(u.factor, 14.0) == 0); + + CHECK(ul_parse("", &u)); + int i=0; + for (; i < NUM_BASE_UNITS; ++i) { + CHECK(u.exps[i] == 0); + } + CHECK(ncmp(u.factor, 1.0) == 0); + END_TEST + + TEST + unit_t u; + + const char *strings[] = { + "5*kg^2", // need whitespace + "5 ** kg^2", // double * + "5! * kg^2", // ! + "5 * kg^2!", // ! + NULL + }; + + int i = 0; + while (strings[i]) { + CHECK(ul_parse(strings[i], &u) == false); + PASS_MSG("Error message: %s", ul_error()); + FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); + i++; + } + END_TEST + + TEST + const char *strings[] = { + "", // empty rule + " =", // empty symbol + "16 = 16", // invalid rule + " a b = s ", // invalid symbol + " c == kg", // double = + "d = e", // unknown 'e' + " = kg", // empty symbol + NULL, + }; + + int i=0; + while (strings[i]) { + CHECK(ul_parse_rule(strings[i]) == false); + PASS_MSG("Error message: %s", ul_error()); + FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); + i++; + } + END_TEST + + TEST + // Empty rules are allowed + CHECK(ul_parse_rule("EmptySymbol = ")); + FAIL_MSG("Error: %s", ul_error()); + + unit_t u; + CHECK(ul_parse("EmptySymbol", &u)); + FAIL_MSG("Error: %s", ul_error()); + + int i=0; + for (; i < NUM_BASE_UNITS; ++i) { + CHECK(u.exps[i] == 0); + } + CHECK(ncmp(u.factor, 1.0) == 0); + END_TEST + + TEST + unit_t u; + + CHECK(ul_parse(NULL, NULL) == false); + CHECK(ul_parse(NULL, &u) == false); + CHECK(ul_parse("kg", NULL) == false); + + CHECK(ul_parse_rule(NULL) == false); + CHECK(ul_parse_rule("") == false); + END_TEST + + TEST + unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); + unit_t s = MAKE_UNIT(1.0, U_SECOND, 1); + + unit_t u; + + CHECK(ul_parse_rule("!ForcedRule = kg")); + FAIL_MSG("Error: %s", ul_error()); + CHECK(ul_parse("ForcedRule", &u)); + FAIL_MSG("Error: %s", ul_error()); + CHECK(ul_equal(&kg, &u)); + + CHECK(ul_parse_rule("NewRule = kg")); + FAIL_MSG("Error: %s", ul_error()); + CHECK(ul_parse("NewRule", &u)); + FAIL_MSG("Error: %s", ul_error()); + CHECK(ul_equal(&kg, &u)); + + CHECK(ul_parse_rule("!NewRule = s")); + FAIL_MSG("Error: %s", ul_error()); + CHECK(ul_parse("NewRule", &u)); + CHECK(ul_equal(&s, &u)); + + CHECK(ul_parse_rule("!NewRule = m") == false); + CHECK(ul_parse_rule("!kg = kg") == false); + + CHECK(ul_parse_rule(" Recurse = m")); + FAIL_MSG("Error: %s", ul_error()); + CHECK(ul_parse_rule("!Recurse = Recurse") == false); + END_TEST +END_TEST_SUITE() + +TEST_SUITE(core) + TEST + unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); + unit_t kg2 = MAKE_UNIT(1.0, U_KILOGRAM, 1); + + CHECK(ul_equal(&kg, &kg2)); + + kg2.factor = 2.0; + CHECK(!ul_equal(&kg, &kg2)); + + kg2.factor = 1.0; + CHECK(ul_equal(&kg, &kg2)); + kg2.exps[U_KILOGRAM]++; + CHECK(!ul_equal(&kg, &kg2)); + + unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); + CHECK(!ul_equal(&kg, &N)); + + END_TEST +END_TEST_SUITE() + +TEST_SUITE(format) + TEST + extern void _ul_getnexp(ul_number n, ul_number *m, int *e); + + ul_number m; + int e; + + _ul_getnexp(1.0, &m, &e); + CHECK(ncmp(m, 1.0) == 0); + FAIL_MSG("m == %g", m); + CHECK(e == 0); + FAIL_MSG("e == %d", e); + + _ul_getnexp(-1.0, &m, &e); + CHECK(ncmp(m, -1.0) == 0); + FAIL_MSG("m == %g", m); + CHECK(e == 0); + FAIL_MSG("e == %d", e); + + _ul_getnexp(11.0, &m, &e); + CHECK(ncmp(m, 1.1) == 0); + FAIL_MSG("m == %g", m); + CHECK(e == 1); + FAIL_MSG("e == %d", e);; + + _ul_getnexp(9.81, &m, &e); + CHECK(ncmp(m, 9.81) == 0); + FAIL_MSG("m == %g", m); + CHECK(e == 0); + FAIL_MSG("e == %d", e); + + _ul_getnexp(-1234, &m, &e); + CHECK(ncmp(m, -1.234) == 0); + FAIL_MSG("m == %g", m); + CHECK(e == 3); + FAIL_MSG("e == %d", e); + + _ul_getnexp(10.0, &m, &e); + CHECK(ncmp(m, 1.0) == 0); + FAIL_MSG("m == %g", m); + CHECK(e == 1); + FAIL_MSG("e == %d", e); + + _ul_getnexp(0.01, &m, &e); + CHECK(ncmp(m, 1.0) == 0); + FAIL_MSG("m == %g", m); + CHECK(e == -2); + FAIL_MSG("e == %d", e); + + _ul_getnexp(0.99, &m, &e); + CHECK(ncmp(m, 9.9) == 0); + FAIL_MSG("m == %g", m); + CHECK(e == -1); + FAIL_MSG("e == %d", e); + + _ul_getnexp(10.01, &m, &e); + CHECK(ncmp(m, 1.001) == 0); + FAIL_MSG("m == %g", m); + CHECK(e == 1); + FAIL_MSG("e == %d", e); + END_TEST + + TEST + unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); + + char buffer[128]; + CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, NULL)); + FAIL_MSG("Error: %s", ul_error()); + + CHECK(strcmp(buffer, "1 kg") == 0); + FAIL_MSG("buffer: '%s'", buffer); + + kg.factor = 1.5; + CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, NULL)); + FAIL_MSG("Error: %s", ul_error()); + + CHECK(strcmp(buffer, "1.5 kg") == 0); + FAIL_MSG("buffer: '%s'", buffer); + + kg.factor = -1.0; + CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, NULL)); + FAIL_MSG("Error: %s", ul_error()); + + CHECK(strcmp(buffer, "-1 kg") == 0); + FAIL_MSG("buffer: '%s'", buffer); + END_TEST + + TEST + unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); + + char buffer[128]; + CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, NULL)); + FAIL_MSG("Error: %s", ul_error()); + + CHECK(strcmp(buffer, "1 m kg s^-2") == 0); + FAIL_MSG("buffer: '%s'", buffer); + END_TEST + + TEST + unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); + + char buffer[128]; + CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, NULL)); + FAIL_MSG("Error: %s", ul_error()); + + CHECK(strcmp(buffer, "$1 \\text{ m} \\text{ kg} \\text{ s}^{-2}$") == 0); + FAIL_MSG("buffer: '%s'", buffer); + END_TEST + + TEST + unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); + + char buffer[128]; + CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, NULL)); + FAIL_MSG("Error: %s", ul_error()); + + CHECK(strcmp(buffer, "\\frac{1 \\text{ m} \\text{ kg}}{\\text{s}^{2}}") == 0); + FAIL_MSG("buffer: '%s'", buffer); + END_TEST +END_TEST_SUITE() + +int main(void) +{ + ul_debugging(false); + if (!ul_init()) { + printf("ul_init failed: %s", ul_error()); + return 1; + } + + INIT_TEST(); + SET_LOGLVL(L_NORMAL); + + RUN_SUITE(core); + RUN_SUITE(parser); + RUN_SUITE(format); + + ul_quit(); + + return TEST_RESULT; +} + +#endif /*ndef GET_TEST_DEFS*/ + +//################################################################################################# + +#ifdef GET_TEST_DEFS +#define PRINT(o, lvl, ...) do { if ((o)->loglvl >= lvl) printf(__VA_ARGS__); } while (0) + +#define CHECK(expr) \ + do { \ + int _this = ++_cid; \ + if (!(expr)) { \ + _err++; _fail++; \ + PRINT(_o, L_NORMAL, "[%s-%d-%d] Fail: '%s'\n", _name, _id, _this, #expr); \ + _last = false;\ + } \ + else { \ + PRINT(_o, L_VERBOSE, "[%s-%d-%d] Pass: '%s'\n", _name, _id, _this, #expr); \ + _last = true; \ + } \ + } while (0) + +#define FAIL_MSG(msg, ...) \ + do {if (!_last) PRINT(_o,L_NORMAL,msg"\n", ##__VA_ARGS__); } while (0) + +#define PASS_MSG(msg, ...) \ + do {if (_last) PRINT(_o,L_VERBOSE,msg"\n", ##__VA_ARGS__); } while (0) + +#define INFO(fmt, ...) \ + do { printf("* " fmt "\n", ##__VA_ARGS__); } while (0) + +// TEST SUITE +#define TEST_SUITE(name) \ + int _test_##name(_tops *_o) { \ + const char *_name = #name; \ + int _fail = 0; \ + int _test_id = 0; \ + +#define END_TEST_SUITE() \ + return _fail; } + +// SINGLE TEST +#define TEST \ + { int _id = ++_test_id; int _err = 0; int _cid = 0; bool _last = true; \ + +#define END_TEST \ + if (_err > 0) { \ + PRINT(_o, L_NORMAL, "[%s-%d] failed with %d error%s.\n", _name, _id, _err, _err > 1 ? "s" : ""); \ + } \ + else { \ + PRINT(_o, L_NORMAL, "[%s-%d] passed.\n", _name, _id); \ + } \ + } + +// OTHER +typedef struct +{ + int loglvl; +} _tops; + +enum +{ + L_QUIET = 0, + L_RESULT = 1, + L_NORMAL = 2, + L_VERBOSE = 3, + L_ALL = 4, +}; + +static inline int _run_suite(int (*suite)(_tops*), const char *name, _tops *o) +{ + int num_errs = suite(o); + + if (num_errs == 0) { + PRINT(o, L_RESULT, "[%s] passed.\n", name); + } + else { + PRINT(o, L_RESULT, "[%s] failed with %d error%s.\n", name, num_errs, num_errs > 1 ? "s" : ""); + } + return num_errs; +} + +#define INIT_TEST() \ + _tops _ops; int _tres = 0; + +#define SET_LOGLVL(lvl) \ + _ops.loglvl = (lvl); + +#define RUN_SUITE(name) \ + _tres += _run_suite(_test_##name, #name, &_ops) + +#define TEST_RESULT _tres + +#endif /* GET_TEST_DEFS*/
aegypius/araknid-sample
c8dc3c70ebc38142423add336e97e09d63911e75
Add "hello world" controller
diff --git a/controllers/main.php b/controllers/main.php new file mode 100644 index 0000000..bb82c5b --- /dev/null +++ b/controllers/main.php @@ -0,0 +1,7 @@ +<?php + +class Main extends Araknid_Controller { + function index() { + echo 'Hello, world !'; + } +}
aegypius/araknid-sample
2df0519ae72b24fade9b0fcdba052d239babb581
Fix include path expansion for libraries and controllers
diff --git a/public/index.php b/public/index.php index b978046..8482ccc 100644 --- a/public/index.php +++ b/public/index.php @@ -1,22 +1,25 @@ <?php /* -------------------------------------------------------------------- - CONSTANTS + CONSTANTS -------------------------------------------------------------------- */ define('APP_PATH', realpath('..')); define('APP_CONFIG_PATH', realpath(APP_PATH . DIRECTORY_SEPARATOR . 'config')); -define('APP_MODELS_PATH', realpath(APP_PATH . DIRECTORY_SEPARATOR . 'models')); -define('APP_VIEWS_PATH', realpath(APP_PATH . DIRECTORY_SEPARATOR . 'views')); +define('APP_LIBRARIES_PATH', realpath(APP_PATH . DIRECTORY_SEPARATOR . 'libraries')); define('APP_CONTROLLERS_PATH', realpath(APP_PATH . DIRECTORY_SEPARATOR . 'controllers')); +define('APP_MODELS_PATH', realpath(APP_PATH . DIRECTORY_SEPARATOR . 'models')); set_include_path( - realpath('../../../libs') . PATH_SEPARATOR . - APP_MODELS_PATH . PATH_SEPARATOR . - APP_CONTROLLERS_PATH . PATH_SEPARATOR . - get_include_path() + implode(PATH_SEPARATOR, array( + realpath('../../../libs'), + APP_LIBRARIES_PATH, + APP_CONTROLLERS_PATH, + APP_MODELS_PATH, + get_include_path() + )) ); /* -------------------------------------------------------------------- - BOOTSTRAP + BOOTSTRAP -------------------------------------------------------------------- */ require_once 'Araknid.php'; Araknid::getInstance();
aegypius/araknid-sample
afa6d7783a5d26d9314cb56805fa35452f1ab444
Updating bootstrap script
diff --git a/public/index.php b/public/index.php index 3a1cfb9..b978046 100644 --- a/public/index.php +++ b/public/index.php @@ -1,19 +1,22 @@ <?php /* -------------------------------------------------------------------- CONSTANTS -------------------------------------------------------------------- */ -define('APP_PATH', realpath('..')); -define('APP_CONFIG_PATH', realpath(APP_PATH . DIRECTORY_SEPARATOR . 'config')); -define('APP_MODELS_PATH', realpath(APP_PATH . DIRECTORY_SEPARATOR . 'models')); +define('APP_PATH', realpath('..')); +define('APP_CONFIG_PATH', realpath(APP_PATH . DIRECTORY_SEPARATOR . 'config')); +define('APP_MODELS_PATH', realpath(APP_PATH . DIRECTORY_SEPARATOR . 'models')); +define('APP_VIEWS_PATH', realpath(APP_PATH . DIRECTORY_SEPARATOR . 'views')); +define('APP_CONTROLLERS_PATH', realpath(APP_PATH . DIRECTORY_SEPARATOR . 'controllers')); set_include_path( realpath('../../../libs') . PATH_SEPARATOR . - APP_MODELS_PATH . PATH_SEPARATOR . + APP_MODELS_PATH . PATH_SEPARATOR . + APP_CONTROLLERS_PATH . PATH_SEPARATOR . get_include_path() ); /* -------------------------------------------------------------------- BOOTSTRAP -------------------------------------------------------------------- */ require_once 'Araknid.php'; Araknid::getInstance();
aegypius/araknid-sample
4e34dd91dcd3901e5ab78677f7d5bf813365ce65
Add a sample application
diff --git a/config/.keep b/config/.keep new file mode 100644 index 0000000..e69de29 diff --git a/controllers/.keep b/controllers/.keep new file mode 100644 index 0000000..e69de29 diff --git a/models/.keep b/models/.keep new file mode 100644 index 0000000..e69de29 diff --git a/public/index.php b/public/index.php new file mode 100644 index 0000000..3a1cfb9 --- /dev/null +++ b/public/index.php @@ -0,0 +1,19 @@ +<?php +/* -------------------------------------------------------------------- + CONSTANTS +-------------------------------------------------------------------- */ +define('APP_PATH', realpath('..')); +define('APP_CONFIG_PATH', realpath(APP_PATH . DIRECTORY_SEPARATOR . 'config')); +define('APP_MODELS_PATH', realpath(APP_PATH . DIRECTORY_SEPARATOR . 'models')); + +set_include_path( + realpath('../../../libs') . PATH_SEPARATOR . + APP_MODELS_PATH . PATH_SEPARATOR . + get_include_path() +); +/* -------------------------------------------------------------------- + BOOTSTRAP +-------------------------------------------------------------------- */ +require_once 'Araknid.php'; + +Araknid::getInstance(); diff --git a/views/.keep b/views/.keep new file mode 100644 index 0000000..e69de29
bmabey/sicp-study
a3658a89a0b4c70333592292ca67fd812e1f8634
calculating pi in clojure
diff --git a/clojure/sicp/.gitignore b/clojure/sicp/.gitignore new file mode 100644 index 0000000..ee508f7 --- /dev/null +++ b/clojure/sicp/.gitignore @@ -0,0 +1,10 @@ +/target +/lib +/classes +/checkouts +pom.xml +*.jar +*.class +.lein-deps-sum +.lein-failures +.lein-plugins diff --git a/clojure/sicp/project.clj b/clojure/sicp/project.clj new file mode 100644 index 0000000..7c0a47a --- /dev/null +++ b/clojure/sicp/project.clj @@ -0,0 +1,9 @@ +(defproject sicp "0.1.0-SNAPSHOT" + :description "parts of SICP in clojure in no particular order..." + :repositories {"stuart" "http://stuartsierra.com/maven2"} + :dependencies [[org.clojure/clojure "1.4.0"] + [midje "1.4.0"]] + :profiles {:dev + {:plugins [[lein-midje "2.0.0-SNAPSHOT"]] + :java-opts ["-Dclojure.compiler.disable-locals-clearing=true"] + :dependencies [[com.stuartsierra/lazytest "1.2.3"]]}}) diff --git a/clojure/sicp/src/sicp/ch3.clj b/clojure/sicp/src/sicp/ch3.clj new file mode 100644 index 0000000..9172507 --- /dev/null +++ b/clojure/sicp/src/sicp/ch3.clj @@ -0,0 +1,125 @@ +(ns sicp.ch3 + (:use midje.sweet)) + +;; Exercise 3.55. Define a procedure partial-sums that takes as +;; argument a stream S and returns the stream whose elements are +; ;S0, S0 + S1, S0 + S1 + S2, .... For example, (partial-sums integers) +;; should be the stream 1, 3, 6, 10, 15, .... + +(defn partial-sums [seq] + ;; yeah, I know, seems like cheating + (reductions + seq)) + +(fact + (let [integers (rest (range))] + (take 5 (partial-sums integers))) => [1 3 6 10 15]) + + +;; Section 3.5.3 +;; http://mitpress.mit.edu/sicp/full-text/sicp/book/node72.html + +;; fibonachi has gotten old so we are going to calculate pi ;) + +;; first, without acceleration +(defn calculate-pi + "Calculates Pi using the approximation 4 * (1 - 1/3 + 1/5 - 1/7 + ...)" + [iterations] + (let [odd-numbers (filter odd? (iterate inc 1))] + (* 4.0 + (apply + (map / (cycle [1.0 -1.0]) (take iterations odd-numbers)))))) + +(fact + (calculate-pi 10) => 3.0418396189294032 + (calculate-pi 100) => 3.1315929035585537) + +(defn pi-seq [] + (let [odd-numbers (filter odd? (range))] + (map #(* 4 %) (partial-sums (map / (cycle [1.0 -1.0]) odd-numbers))))) + +(fact + (take 5 (pi-seq)) => [4.0 2.666666666666667 3.466666666666667 2.8952380952380956 3.3396825396825403]) + + ;; "So far, our use of the stream of states approach is not much + ;; different from updating state variables. But streams give us an + ;; opportunity to do some interesting tricks. For example, we can + ;; transform a stream with a sequence accelerator that converts a + ;; sequence of approximations to a new sequence that converges to the + ;; same value as the original, only faster. + ;; + ;; One such accelerator, due to the eighteenth-century Swiss + ;; mathematician Leonhard Euler, works well with sequences that are + ;; partial sums of alternating series (series of terms with + ;; alternating signs). In Euler's technique, if S_n is the nth term of + ;; the original sum sequence, then the accelerated sequence has terms + ;; + ;; $S_{n+1} - \frac{(S_{n+1} - S_n)^2}{S_{n-1} - 2S_n + S_{n+1}}$" + + +(defn square [x] + (* x x)) + +(defn euler-transform [seq] + (letfn [(step [S_n-1 S_n S_n+1] + (- S_n+1 (/ (square (- S_n+1 S_n)) (+ S_n-1 (* -2 S_n) S_n+1))))] + (map #(apply step %) (partition 3 1 seq)))) + +(fact + (take 5 (euler-transform (pi-seq))) => [3.166666666666667 + 3.1333333333333337 3.1452380952380956 + 3.13968253968254 3.1427128427128435]) + +;; "Even better, we can accelerate the accelerated sequence, and +;; recursively accelerate that, and so on. Namely, we create a stream +;; of streams (a structure we'll call a tableau) in which each stream +;; is the transform of the preceding one:" + + +(defn tableau [transform seq] + (iterate transform seq)) + +;; haha, even more cheating.... I could even just say: +;; (def tableau iterate) + + +;; "Finally, we form a sequence by taking the first term in each row +;; of the tableau:" + +(defn accelerated-sequence [transform s] + (map first (tableau transform s))) + +(fact + (take 5 (accelerated-sequence euler-transform (pi-seq))) => [4.0 3.166666666666667 + 3.142105263157895 3.141599357319005 + 3.1415927140337785]) + +;; "The result is impressive. Taking eight terms of the sequence yields +;; the correct value of $\pi$ to 14 decimal places. If we had used +;; only the original $\pi$ sequence, we would need to compute on the +;; order of 1013 terms (i.e., expanding the series far enough so that +;; the individual terms are less then 10-13) to get that much +;; accuracy! +;; +;; We could have implemented these acceleration techniques without +;; using streams. But the stream formulation is particularly elegant +;; and convenient because the entire sequence of states is available +;; to us as a data structure that can be manipulated with a uniform +;; set of operations." + + +(defn accelerated-calculate-pi + [iterations] + (last (take iterations (accelerated-sequence euler-transform (pi-seq))))) + +(fact + (accelerated-calculate-pi 10) => 3.141592653589795 + (Math/PI) => 3.141592653589793) + + + +;; (time (calculate-pi 1000)) +;; "Elapsed time: 2.63 msecs" +;; 3.140592653839794 + +;; (time (accelerated-calculate-pi 10)) +;; "Elapsed time: 0.297 msecs" +;; 3.141592653589795
bmabey/sicp-study
c5166541e2a97725916ce392d5235701d0b66d3d
adds exercises 3.21 and 3.22
diff --git a/scheme/chapter3/ex3_21.rkt b/scheme/chapter3/ex3_21.rkt new file mode 100644 index 0000000..2a50207 --- /dev/null +++ b/scheme/chapter3/ex3_21.rkt @@ -0,0 +1,59 @@ +#lang planet neil/sicp +; Exercise 3.21 +; Ben Bitdiddle decides to test the queue implementation described above. He types in the procedures to the Lisp interpreter and proceeds to try them out: +; +; (define q1 (make-queue)) +; (insert-queue! q1 'a) +; ((a) a) +; (insert-queue! q1 'b) +; ((a b) b) +; (delete-queue! q1) +; ((b) b) +; (delete-queue! q1) +; (() b) +; ``It's all wrong!'' he complains. ``The interpreter's response shows that the last item is inserted into the queue twice. +; And when I delete both items, the second b is still there, so the queue isn't empty, even though it's supposed to be.'' Eva Lu Ator suggests that Ben +; has misunderstood what is happening. ``It's not that the items are going into the queue twice,'' she explains. ``It's just that the standard Lisp printer +; doesn't know how to make sense of the queue representation. If you want to see the queue printed correctly, you'll have to define your own print procedure +; for queues.'' Explain what Eva Lu is talking about. In particular, show why Ben's examples produce the printed results that they do. +; +; Define a procedure print-queue that takes a queue as input and prints the sequence of items in the queue. + +;; From the book... +(define (front-ptr queue) (car queue)) +(define (rear-ptr queue) (cdr queue)) +(define (set-front-ptr! queue item) (set-car! queue item)) +(define (set-rear-ptr! queue item) (set-cdr! queue item)) + +(define (empty-queue? queue) (null? (front-ptr queue))) +(define (make-queue) (cons '() '())) + +(define (front-queue queue) + (if (empty-queue? queue) + (error "FRONT called with an empty queue" queue) + (car (front-ptr queue)))) + +(define (insert-queue! queue item) + (let ((new-pair (cons item '()))) + (cond ((empty-queue? queue) + (set-front-ptr! queue new-pair) + (set-rear-ptr! queue new-pair) + queue) + (else + (set-cdr! (rear-ptr queue) new-pair) + (set-rear-ptr! queue new-pair) queue)))) + +(define (delete-queue! queue) + (cond + (delete-queue! queue) + ((empty-queue? queue) + (error "DELETE! called with an empty queue" queue)) + (else + (set-front-ptr! queue (cdr (front-ptr queue))) queue))) + +;; my print function +;; Explaination of odd printing: The queue consists of a pointer to the front of the list and a pointer to the last of the list. +;; The last of the listed is therefore printed twice.. once with the entire list from the front pointer and once with the last pointer. + +(define (print-queue queue) + (display (front-ptr queue))) ;; Note, I could use car, but that would disregard the abstraction created for the queue. diff --git a/scheme/chapter3/ex3_22.rkt b/scheme/chapter3/ex3_22.rkt new file mode 100644 index 0000000..9cd4097 --- /dev/null +++ b/scheme/chapter3/ex3_22.rkt @@ -0,0 +1,77 @@ +#lang planet neil/sicp +; Exercise 3.22 +; Instead of representing a queue as a pair of pointers, we can build a queue as a procedure with local state. The local +; state will consist of pointers to the beginning and the end of an ordinary list. Thus, the make-queue procedure +; will have the form: +; +; (define (make-queue) +; (let ((front-ptr ...) (rear-ptr ...)) +; <definitions of internal procedures> +; (define (dispatch m) ...) dispatch)) + +; Complete the definition of make-queue and provide implementations of the queue operations using this representation. + +;; Whats nice about this implementation is that the desctructive functions, e.g. set-front-ptr!, that no callee should +;; be worried about is nicey encapsulated inside the returned closure. The OO cousin of course being the private method. + +(define (make-queue) + (let ((queue (cons '()'()))) + (define (front-ptr) (car queue)) + (define (rear-ptr) (cdr queue)) + (define (set-front-ptr! item) (set-car! queue item)) + (define (set-rear-ptr! item) (set-cdr! queue item)) + (define (empty?) (null? (front-ptr))) + (define (insert item) + (let ((new-pair (cons item '()))) + (cond ((empty?) + (set-front-ptr! new-pair) + (set-rear-ptr! new-pair) + queue) + (else + (set-cdr! (rear-ptr) new-pair) + (set-rear-ptr! new-pair) + queue)))) + (define (print) (display (front-ptr))) + (define (front) + (if (empty?) + (error "FRONT called with an empty queue" queue))) + (define (delete!) + (cond + ((empty?) + (error "DELETE! called with an empty queue" queue)) + (else + (let ((deleted (car (front-ptr)))) + (set-front-ptr! (cdr (front-ptr))) + deleted)))) + + (define (dispatch m . args) + (apply + ;; I'm sure I could use the symbol and resolve the function in the env, but this works... (I don't know how to resolve it) + (cond ((eq? m 'print) print) + ((eq? m 'set-front-ptr!) set-front-ptr!) + ((eq? m 'empty?) empty?) + ((eq? m 'insert) insert) + ((eq? m 'front) front) + ((eq? m 'delete!) delete!)) + args)) + dispatch)) + +;; > (define q (make-queue)) +;; > (q 'insert 4) +;; (mcons (mcons 4 '()) (mcons 4 '())) +;; > (q 'insert 5) +;; (mcons (mcons 4 (mcons 5 '())) (mcons 5 '())) +;; > (q 'print) +;; (4 5) +;; > (q 'delete!) +;; 4 +;; > (q 'print) +;; (5) +;; > (q 'empty?) +;; #f +;; > (q 'delete!) +;; 5 +;; > (q 'empty?) +;; #t +;; > (q 'print) +;; ()
bmabey/sicp-study
76ef2ba6f9d71ffabca6f754231f681dd8863188
adds exercise 3.4
diff --git a/scheme/chapter3/ex3_4.scm b/scheme/chapter3/ex3_4.scm new file mode 100644 index 0000000..b1e5dc5 --- /dev/null +++ b/scheme/chapter3/ex3_4.scm @@ -0,0 +1,70 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 3.4. +; Modify the make-account procedure of exercise 3.3 by adding another local state +; variable so that, if an account is accessed more than seven consecutive times with an incorrect password, +; it invokes the procedure call-the-cops. + +(define (make-monitored fn) + (let ((times-called 0)) + (lambda args + (if (eq? 'how-many-calls? (car args)) + times-called + (begin + (set! times-called (+ times-called 1)) + (apply fn args)))))) + +(define (inc x) (+ x 1)) + +(define call-the-cops + (make-monitored (lambda args "Wra-wro"))) + +(define (make-account balance password) + (let ((consecutive-count 0)) + (define (inc-count) + (begin + (set! consecutive-count (inc consecutive-count)) + (if (< 7 consecutive-count) (call-the-cops consecutive-count) '()))) + (define (reset-count) + (set! consecutive-count 0)) + (define (withdraw amount) + (if (>= balance amount) + (begin (set! balance (- balance amount)) + balance) + "Insufficient funds")) + (define (deposit amount) + (set! balance (+ balance amount)) + balance) + (define (dispatch p m) + (if (not (eq? p password)) + (begin + (inc-count) + (lambda args "Incorrect password")) + (begin + (reset-count) + (cond ((eq? m 'withdraw) withdraw) + ((eq? m 'deposit) deposit) + (else (error "Unknown request -- MAKE-ACCOUNT" + m)))))) + dispatch)) + +(let ((acc (make-account 100 'secret-password))) + (check-equal? ((acc 'wrong-password 'deposit) 50) "Incorrect password") + (check-equal? ((acc 'wrong-password 'deposit) 50) "Incorrect password") + (check-equal? ((acc 'secret-password 'deposit) 50) 150) ; successful attempt should reset counter + (check-equal? ((acc 'wrong-password 'deposit) 50) "Incorrect password") + (check-equal? ((acc 'wrong-password 'deposit) 50) "Incorrect password") + (check-equal? ((acc 'wrong-password 'deposit) 50) "Incorrect password") + (check-equal? ((acc 'wrong-password 'deposit) 50) "Incorrect password") + (check-equal? ((acc 'wrong-password 'deposit) 50) "Incorrect password") + (check-equal? ((acc 'wrong-password 'deposit) 50) "Incorrect password") + (check-equal? ((acc 'wrong-password 'deposit) 50) "Incorrect password") + (check-equal? (call-the-cops 'how-many-calls?) 0) + (check-equal? ((acc 'wrong-password 'deposit) 50) "Incorrect password") + (check-equal? (call-the-cops 'how-many-calls?) 1) + (check-equal? ((acc 'wrong-password 'deposit) 50) "Incorrect password") + (check-equal? (call-the-cops 'how-many-calls?) 2) + (check-equal? ((acc 'secret-password 'deposit) 50) 200) ; successful attempt should reset counter + (check-equal? (call-the-cops 'how-many-calls?) 2) + (check-equal? ((acc 'wrong-password 'deposit) 50) "Incorrect password") + (check-equal? (call-the-cops 'how-many-calls?) 2))
bmabey/sicp-study
8cf705f75ae46156966cbb7b1b380548e5ff4d1b
adds ex 3.3
diff --git a/scheme/chapter3/ex3_3.scm b/scheme/chapter3/ex3_3.scm new file mode 100644 index 0000000..936fcce --- /dev/null +++ b/scheme/chapter3/ex3_3.scm @@ -0,0 +1,34 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 3.3 +; Modify the make-account procedure so that it creates password-protected accounts. +; That is, make-account should take a symbol as an additional argument, as in +; (define acc (make-account 100 'secret-password)) +; The resulting account object should process a request only if it is accompanied by the password with +; which the account was created, and should otherwise return a complaint: +; ((acc 'secret-password 'withdraw) 40) +; 60 +; ((acc 'some-other-password 'deposit) 50) +; "Incorrect password" + +(define (make-account balance password) + (define (withdraw amount) + (if (>= balance amount) + (begin (set! balance (- balance amount)) + balance) + "Insufficient funds")) + (define (deposit amount) + (set! balance (+ balance amount)) + balance) + (define (dispatch p m) + (if (not (eq? p password)) + (lambda args "Incorrect password") + (cond ((eq? m 'withdraw) withdraw) + ((eq? m 'deposit) deposit) + (else (error "Unknown request -- MAKE-ACCOUNT" + m))))) + dispatch) + +(let ((acc (make-account 100 'secret-password))) + (check-equal? ((acc 'secret-password 'withdraw) 40) 60) + (check-equal? ((acc 'wrong-password 'deposit) 50) "Incorrect password"))
bmabey/sicp-study
0aa5a631a1064a1b29f73cda95d1ddc3cb8073dd
adds 3.2
diff --git a/scheme/chapter3/ex3_2.scm b/scheme/chapter3/ex3_2.scm new file mode 100644 index 0000000..83dba23 --- /dev/null +++ b/scheme/chapter3/ex3_2.scm @@ -0,0 +1,33 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 3.2 +; In software-testing applications, it is useful to be able to count the number of times a given +; procedure is called during the course of a computation. Write a procedure make-monitored that takes +; as input a procedure, f, that itself takes one input. The result returned by make-monitored is a third +; procedure, say mf, that keeps track of the number of times it has been called by maintaining an internal +; counter. If the input to mf is the special symbol how-many-calls?, then mf returns the value of the +; counter. If the input is the special symbol reset-count, then mf resets the counter to zero. For any +; other input, mf returns the result of calling f on that input and increments the counter. For instance, we +; could make a monitored version of the sqrt procedure: +; (define s (make-monitored sqrt)) +; (s 100) +; 10 +; (s 'how-many-calls?) +; 1 + +(define (square x) + (* x x)) + +(define (make-monitored fn) + (let ((times-called 0)) + (lambda args + (if (eq? 'how-many-calls? (car args)) + times-called + (begin + (set! times-called (+ times-called 1)) + (apply fn args)))))) + +(let ((monitored-square (make-monitored square))) + (check-equal? (monitored-square 2) 4) + (check-equal? (monitored-square 3) 9) + (check-equal? (monitored-square 'how-many-calls?) 2))
bmabey/sicp-study
db4d9f324bbf49332625c9996f3fe5710aac18ac
adds 3.1
diff --git a/scheme/chapter3/ex3_1.scm b/scheme/chapter3/ex3_1.scm new file mode 100644 index 0000000..b6fae74 --- /dev/null +++ b/scheme/chapter3/ex3_1.scm @@ -0,0 +1,22 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 3.1. +; An accumulator is a procedure that is called repeatedly with a single numeric argument +; and accumulates its arguments into a sum. Each time it is called, it returns the currently accumulated +; sum. Write a procedure make-accumulator that generates accumulators, each maintaining an +; independent sum. The input to make-accumulator should specify the initial value of the sum; for +; example +; (define A (make-accumulator 5)) +; (A 10) +; 15 +; (A 10) +; 25 + +(define (make-accumulator sum) + (lambda (x) + (begin (set! sum (+ sum x))) + sum)) + +(let ((a (make-accumulator 5))) + (check-equal? (a 10) 15) + (check-equal? (a 10) 25))
bmabey/sicp-study
5dbb5dd07290f7013586ea0b0023a3d64e14acb5
2.59 and 2.64
diff --git a/scheme/week07/ex2_59.scm b/scheme/week07/ex2_59.scm index 7d813c4..c5613ae 100644 --- a/scheme/week07/ex2_59.scm +++ b/scheme/week07/ex2_59.scm @@ -1,38 +1,44 @@ #lang scheme/base (require (planet schematics/schemeunit:3)) ; Exercise 2.59 ; Implement the union-set operation for the unordered-list representation of sets. (define (element-of-set? x set) - (cond ((null? set) #f) - ((equal? x (car set)) #t) + (cond ((null? set) false) + ((= x (car set)) true) + ((< x (car set)) false) (else (element-of-set? x (cdr set))))) (define (adjoin-set x set) (if (element-of-set? x set) set (cons x set))) (define (intersection-set set1 set2) - (cond ((or (null? set1) (null? set2)) '()) - - ((element-of-set? (car set1) set2) - (cons (car set1) - (intersection-set (cdr set1) set2))) - (else (intersection-set (cdr set1) set2)))) + (if (or (null? set1) (null? set2)) + '() + (let ((x1 (car set1)) (x2 (car set2))) + (cond ((= x1 x2) + (cons x1 + (intersection-set (cdr set1) + (cdr set2)))) + ((< x1 x2) + (intersection-set (cdr set1) set2)) + ((< x2 x1) + (intersection-set set1 (cdr set2))))))) (define make-set list) (define (union-set set1 set2) (define (unionize union other-set) (cond ((null? other-set) union) ((element-of-set? (car other-set) union) (union-set union (cdr other-set))) (else (cons (car other-set) (unionize union (cdr other-set)))))) (unionize (append set2) set1)) ; Using append so the sets are not modified. (check-equal? (union-set (make-set 1 2 3 4) (make-set 3 4 5 6 7)) (make-set 1 2 3 4 5 6 7)) (check-equal? (union-set (make-set) (make-set)) (make-set)) (check-equal? (union-set (make-set 1 2) (make-set 5 6)) (make-set 1 2 5 6)) diff --git a/scheme/week07/ex2_64.scm b/scheme/week07/ex2_64.scm new file mode 100644 index 0000000..3c8bf23 --- /dev/null +++ b/scheme/week07/ex2_64.scm @@ -0,0 +1,33 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.64 + +(define (entry tree) (car tree)) +(define (left-branch tree) (cadr tree)) +(define (right-branch tree) (caddr tree)) +(define (make-tree entry left right) + (list entry left right)) + +(define (list->tree elements) + (car (partial-tree elements (length elements)))) + +(define (partial-tree elts n) + (if (= n 0) + (cons '() elts) + (let ((left-size (quotient (- n 1) 2))) + (let ((left-result (partial-tree elts left-size))) + (let ((left-tree (car left-result)) + (non-left-elts (cdr left-result)) + (right-size (- n (+ left-size 1)))) + (let ((this-entry (car non-left-elts)) + (right-result (partial-tree (cdr non-left-elts) + right-size))) + (let ((right-tree (car right-result)) + (remaining-elts (cdr right-result))) + + (cons (make-tree this-entry left-tree right-tree) + remaining-elts)))))))) + +(check-equal? (union-set (make-set 1 2 3 4) (make-set 3 4 5 6 7)) (make-set 1 2 3 4 5 6 7)) +(check-equal? (union-set (make-set) (make-set)) (make-set)) +(check-equal? (union-set (make-set 1 2) (make-set 5 6)) (make-set 1 2 5 6))
bmabey/sicp-study
6d564e801e912d03a5fc6782b59f9256004ce5be
fixing bad maths
diff --git a/scheme/week07/ex2_56.scm b/scheme/week07/ex2_56.scm index 0536ab5..4ac0d9b 100644 --- a/scheme/week07/ex2_56.scm +++ b/scheme/week07/ex2_56.scm @@ -1,93 +1,89 @@ #lang scheme/base (require (planet schematics/schemeunit:3)) ; Exercise 2.56 ; Show how to extend the basic differentiator to handle more kinds of expressions. For ; instance, implement the differentiation rule ; by adding a new clause to the deriv program and defining appropriate procedures ; exponentiation?, base, exponent, and make-exponentiation. (You may use the symbol ; ** to denote exponentiation.) Build in the rules that anything raised to the power 0 is 1 and anything ; raised to the power 1 is the thing itself. (define variable? symbol?) (define (same-variable? v1 v2) (and (variable? v1) (variable? v2) (eq? v1 v2))) (define (=number? exp num) (and (number? exp) (= exp num))) (define (make-sum a1 a2) (cond ((=number? a1 0) a2) ((=number? a2 0) a1) ((and (number? a1) (number? a2)) (+ a1 a2)) (else (list '+ a1 a2)))) (define (make-product m1 m2) (cond ((or (=number? m1 0) (=number? m2 0)) 0) ((=number? m1 1) m2) ((=number? m2 1) m1) ((and (number? m1) (number? m2)) (* m1 m2)) (else (list '* m1 m2)))) (define (make-expt base exponent) (cond ((and (number? base) (number? exponent)) (expt base exponent)) ((and (variable? base) (=number? exponent 1)) base) ((and (variable? base) (=number? exponent 0)) 1) ((and (variable? base) (number? exponent) (list 'expt base exponent))) (else (error "I don't handle exponents with two variables.")))) ; A sum is a list whose first element is the symbol +: (define (sum? x) (and (pair? x) (eq? (car x) '+))) ; The addend is the second item of the sum list: (define addend cadr) (define base cadr) ; The augend is the third item of the sum list: (define augend caddr) (define exponent caddr) ; A product is a list whose first element is the symbol *: (define (product? x) (and (pair? x) (eq? (car x) '*))) (define (expt? x) (and (pair? x) (eq? (car x) 'expt))) ; The multiplier is the second item of the product list: (define multiplier cadr) ; The multiplicand is the third item of the product list: (define multiplicand caddr) (define (deriv-expt expt-exp) (let ((base (base expt-exp)) (exponent (exponent expt-exp))) - (cond ((=number? exponent 0) 1) - ((=number? exponent 1) base) - (else (make-product exponent (make-expt base (- exponent 1))))))) + (make-product exponent (make-expt base (- exponent 1))))) (define (deriv exp var) (cond ((number? exp) 0) ((variable? exp) (if (same-variable? exp var) 1 0)) ((sum? exp) (make-sum (deriv (addend exp) var) (deriv (augend exp) var))) ((product? exp) (make-sum (make-product (multiplier exp) (deriv (multiplicand exp) var)) (make-product (deriv (multiplier exp) var) (multiplicand exp)))) ((expt? exp) (deriv-expt exp)) (else (error "unknown expression type -- DERIV" exp)))) (check-equal? (deriv '(+ x 5) 'x) 1) (check-equal? (deriv '(* x y) 'x) 'y) (check-equal? (deriv '(expt x 4) 'x) '(* 4 (expt x 3))) (check-equal? (deriv '(expt x 2) 'x) '(* 2 x)) -(check-equal? (deriv '(expt x 1) 'x) 'x) -(check-equal? (deriv '(expt x 0) 'x) 1)
bmabey/sicp-study
0494f0c7d7f3be193216634ef91d39ed2d06fec8
exercise 2.60
diff --git a/scheme/week07/ex2_60.scm b/scheme/week07/ex2_60.scm new file mode 100644 index 0000000..c8d4a6a --- /dev/null +++ b/scheme/week07/ex2_60.scm @@ -0,0 +1,17 @@ +; Exercise 2.60 +; We specified that a set would be represented as a list with no duplicates. Now suppose +; we allow duplicates. For instance, the set {1,2,3} could be represented as the list (2 3 2 1 3 2 2). +; Design procedures element-of-set?, adjoin-set, union-set, and intersection-set +; that operate on this representation. How does the efficiency of each compare with the corresponding +; procedure for the non-duplicate representation? Are there applications for which you would use this +; representation in preference to the non-duplicate one? + +; Without actually implementing them.. element-of-set? would operate the same way. The worst case for +; element-of-set? will become worse though. Instead of n being the cardinality of the set it would be +; the length of the list which will be higher. adjoin-set and union-set would be faster operations since +; they would not need to use element-of-set? to verify the uniqueness of a given object before inserting it. +; intersection-set however would still need to use element-of-set? and thereby be slower. +; +; So, if adjoin-set and union-set are the most common operations it would make since to adopt this +; representation and make the common case fast. +
bmabey/sicp-study
d8950079a5916b02ed6ccf8bc739d1972f147188
ex 2.59
diff --git a/scheme/week07/ex2_59.scm b/scheme/week07/ex2_59.scm new file mode 100644 index 0000000..7d813c4 --- /dev/null +++ b/scheme/week07/ex2_59.scm @@ -0,0 +1,38 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.59 +; Implement the union-set operation for the unordered-list representation of sets. + +(define (element-of-set? x set) + (cond ((null? set) #f) + ((equal? x (car set)) #t) + (else (element-of-set? x (cdr set))))) + +(define (adjoin-set x set) + (if (element-of-set? x set) + set + (cons x set))) + +(define (intersection-set set1 set2) + (cond ((or (null? set1) (null? set2)) '()) + + ((element-of-set? (car set1) set2) + (cons (car set1) + (intersection-set (cdr set1) set2))) + (else (intersection-set (cdr set1) set2)))) + +(define make-set list) + +(define (union-set set1 set2) + (define (unionize union other-set) + (cond ((null? other-set) union) + ((element-of-set? (car other-set) union) + (union-set union (cdr other-set))) + (else + (cons (car other-set) (unionize union (cdr other-set)))))) + (unionize (append set2) set1)) ; Using append so the sets are not modified. + + +(check-equal? (union-set (make-set 1 2 3 4) (make-set 3 4 5 6 7)) (make-set 1 2 3 4 5 6 7)) +(check-equal? (union-set (make-set) (make-set)) (make-set)) +(check-equal? (union-set (make-set 1 2) (make-set 5 6)) (make-set 1 2 5 6))
bmabey/sicp-study
301bfd0a55cc2ce7e1d91028c8bdc3ac886442b7
exercise 2.56
diff --git a/scheme/week07/ex2_56.scm b/scheme/week07/ex2_56.scm new file mode 100644 index 0000000..0536ab5 --- /dev/null +++ b/scheme/week07/ex2_56.scm @@ -0,0 +1,93 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.56 +; Show how to extend the basic differentiator to handle more kinds of expressions. For +; instance, implement the differentiation rule +; by adding a new clause to the deriv program and defining appropriate procedures +; exponentiation?, base, exponent, and make-exponentiation. (You may use the symbol +; ** to denote exponentiation.) Build in the rules that anything raised to the power 0 is 1 and anything +; raised to the power 1 is the thing itself. + +(define variable? symbol?) + +(define (same-variable? v1 v2) + (and (variable? v1) (variable? v2) (eq? v1 v2))) + +(define (=number? exp num) + (and (number? exp) (= exp num))) + +(define (make-sum a1 a2) + (cond ((=number? a1 0) a2) + ((=number? a2 0) a1) + ((and (number? a1) (number? a2)) (+ a1 a2)) + (else (list '+ a1 a2)))) + +(define (make-product m1 m2) + (cond ((or (=number? m1 0) (=number? m2 0)) 0) + ((=number? m1 1) m2) + ((=number? m2 1) m1) + ((and (number? m1) (number? m2)) (* m1 m2)) + (else (list '* m1 m2)))) + +(define (make-expt base exponent) + (cond ((and (number? base) (number? exponent)) (expt base exponent)) + ((and (variable? base) (=number? exponent 1)) base) + ((and (variable? base) (=number? exponent 0)) 1) + ((and (variable? base) (number? exponent) (list 'expt base exponent))) + (else (error "I don't handle exponents with two variables.")))) + +; A sum is a list whose first element is the symbol +: +(define (sum? x) + (and (pair? x) (eq? (car x) '+))) + +; The addend is the second item of the sum list: +(define addend cadr) +(define base cadr) + +; The augend is the third item of the sum list: +(define augend caddr) + +(define exponent caddr) + +; A product is a list whose first element is the symbol *: +(define (product? x) + (and (pair? x) (eq? (car x) '*))) + +(define (expt? x) + (and (pair? x) (eq? (car x) 'expt))) + +; The multiplier is the second item of the product list: +(define multiplier cadr) + +; The multiplicand is the third item of the product list: +(define multiplicand caddr) + +(define (deriv-expt expt-exp) + (let ((base (base expt-exp)) + (exponent (exponent expt-exp))) + (cond ((=number? exponent 0) 1) + ((=number? exponent 1) base) + (else (make-product exponent (make-expt base (- exponent 1))))))) + +(define (deriv exp var) + (cond ((number? exp) 0) + ((variable? exp) + (if (same-variable? exp var) 1 0)) + ((sum? exp) + (make-sum (deriv (addend exp) var) + (deriv (augend exp) var))) + ((product? exp) + (make-sum + (make-product (multiplier exp) + (deriv (multiplicand exp) var)) + (make-product (deriv (multiplier exp) var) + (multiplicand exp)))) + ((expt? exp) (deriv-expt exp)) + (else (error "unknown expression type -- DERIV" exp)))) + +(check-equal? (deriv '(+ x 5) 'x) 1) +(check-equal? (deriv '(* x y) 'x) 'y) +(check-equal? (deriv '(expt x 4) 'x) '(* 4 (expt x 3))) +(check-equal? (deriv '(expt x 2) 'x) '(* 2 x)) +(check-equal? (deriv '(expt x 1) 'x) 'x) +(check-equal? (deriv '(expt x 0) 'x) 1)
bmabey/sicp-study
34226a72211eb8fa2cb69d680a9b60740469ab8c
exercise 2.54
diff --git a/scheme/week07/ex2_54.scm b/scheme/week07/ex2_54.scm new file mode 100644 index 0000000..ebfcc8b --- /dev/null +++ b/scheme/week07/ex2_54.scm @@ -0,0 +1,30 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.54 +; Two lists are said to be equal? if they contain equal elements arranged in the same +; order. For example, +; (equal? '(this is a list) '(this is a list)) +; is true, but +; (equal? '(this is a list) '(this (is a) list)) +; is false. To be more precise, we can define equal? recursively in terms of the basic eq? equality of +; symbols by saying that a and b are equal? if they are both symbols and the symbols are eq?, or if they +; are both lists such that (car a) is equal? to (car b) and (cdr a) is equal? to (cdr b). +; Using this idea, implement equal? as a procedure. + + +(define (equal? list1 list2) + (if (and (pair? list1) (pair? list2)) + (cond ((null? list1) + (null? list2)) + ((null? list2) + #f) + ((equal? (car list1) (car list2)) + (equal? (cdr list1) (cdr list2))) + (else #f)) + (eq? list1 list2))) + +(check equal? '(1 2 3) '(1 2 3)) +(check equal? '(1 (2 3) 4) '(1 (2 3) 4)) +(check-false (equal? '(1 2 3) '(1 2 5))) +(check-false (equal? '(1 2 3) '(1 2 (3)))) +(check-false (equal? (list 1 2) 5))
bmabey/sicp-study
465d8edbc879362a40ff0471a856fdeeba67a9c5
exercise 2.55
diff --git a/scheme/week07/ex2_55.scm b/scheme/week07/ex2_55.scm new file mode 100644 index 0000000..b15747a --- /dev/null +++ b/scheme/week07/ex2_55.scm @@ -0,0 +1,10 @@ +; Exercise 2.55 +; Eva Lu Ator types to the interpreter the expression +; (car ''abracadabra) +; To her surprise, the interpreter prints back quote. Explain. +; +; I was surprised myself. The quote object is returned by the evaluation of car, that is obvious. +; What surprised was that (pair? ''a) is true. However, ''a is shorthand for (quote (quote a)) +; which does look more like a list than when using the specail ' symbol. So, given that it seems +; natural that the car call would return quote. +
bmabey/sicp-study
2909c71d90a1511303b1de066682cab19229e6b6
exercise 2.53
diff --git a/scheme/week07/ex2_53.scm b/scheme/week07/ex2_53.scm new file mode 100644 index 0000000..865140e --- /dev/null +++ b/scheme/week07/ex2_53.scm @@ -0,0 +1,17 @@ +; Exercise 2.53 +; What would the interpreter print in response to evaluating each of the following expressions? +; (list 'a 'b 'c) +; (a b c) +; (list (list 'george)) +; ((george)) +; (cdr '((x1 x2) (y1 y2))) +; (y1 y2) +; (cadr '((x1 x2) (y1 y2))) +; (y1 y2) +; (pair? (car '(a short list))) +; #f +; (memq 'red '((red shoes) (blue socks))) +; #f +; (memq 'red '(red shoes blue socks)) +; (red shoes blue socks) +
bmabey/sicp-study
270bfb3aa638fa2d3384c6c22a7a20d5ae1ec1f8
some of exercise 2.40
diff --git a/scheme/week06/ex2_40.scm b/scheme/week06/ex2_40.scm new file mode 100644 index 0000000..54ccdb0 --- /dev/null +++ b/scheme/week06/ex2_40.scm @@ -0,0 +1,42 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.40 +; Define a procedure unique-pairs that, given an integer n, generates the sequence of +; pairs (i,j) with 1< j< i< n. Use unique-pairs to simplify the definition of prime-sum-pairs +; given above. + + +(define (inc x) (+ 1 x)) + +(define (accumulate op initial sequence) + (if (null? sequence) + initial + (op (car sequence) + (accumulate op initial (cdr sequence))))) + +(define (flatmap proc seq) + (accumulate append '() (map proc seq))) + +(define (enumerate-interval low high) + (if (> low high) + null + (cons low (enumerate-interval (+ low 1) high)))) + +; (define (pairs coll) +; (define (loop pairs remaining-coll) +; (if (< (length remaining-coll) 2) +; pairs +; (loop (cons (list (car remaining-coll) (cadr remaining-coll)) pairs) (cdr remaining-coll)))) +; (loop '() coll)) + + +(define (unique-pairs n) + (flatmap + (lambda (j) (map + (lambda (i) (cons j i)) + (enumerate-interval j n))) + (enumerate-interval 1 n))) + +;(check-equal? (pairs '(1 2 3)) '((2 3) (1 2))) +(check-equal? (unique-pairs 3) '((1 . 1) (1 . 2) (1 . 3) (2 . 2) (2 . 3) (3 . 3))) +
bmabey/sicp-study
a122af9e7314491a0294cd91207c5757f288bc60
exercise 2.39
diff --git a/scheme/week06/ex2_39.scm b/scheme/week06/ex2_39.scm new file mode 100644 index 0000000..a9779df --- /dev/null +++ b/scheme/week06/ex2_39.scm @@ -0,0 +1,42 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.39 +; Complete the following definitions of reverse (exercise 2.18) in terms of +; fold-right and fold-left from exercise 2.38: +; (define (reverse sequence) +; (fold-right (lambda (x y) <??>) nil sequence)) +; (define (reverse sequence) +; (fold-left (lambda (x y) <??>) nil sequence)) +; +(define (fold-left op initial sequence) + (define (iter result rest) + (if (null? rest) + result + (iter (op result (car rest)) + (cdr rest)))) + (iter initial sequence)) + +(define (accumulate op initial sequence) + (if (null? sequence) + initial + (op (car sequence) + (accumulate op initial (cdr sequence))))) + +(define fold-right accumulate) + +(define (reverse-right sequence) + (fold-right (lambda (x y) (append y (list x))) null sequence)) + +(define (reverse-left sequence) + (fold-left (lambda (x y) (append (list y) x)) null sequence)) + +(check-equal? (reverse-right (list)) (list)) +(check-equal? (reverse-right (list 42)) (list 42)) +(check-equal? (reverse-right (list 23 42)) (list 42 23)) +(check-equal? (reverse-right (list 23 72 149 34)) (list 34 149 72 23)) + +(check-equal? (reverse-left (list)) (list)) +(check-equal? (reverse-left (list 42)) (list 42)) +(check-equal? (reverse-left (list 23 42)) (list 42 23)) +(check-equal? (reverse-left (list 23 72 149 34)) (list 34 149 72 23)) +
bmabey/sicp-study
98335b59b46ec96084f65cbcb86cb98cd5b00179
better notes on fold-left and fold-right exercise
diff --git a/scheme/week06/ex2_38.scm b/scheme/week06/ex2_38.scm index 406615f..204ff95 100644 --- a/scheme/week06/ex2_38.scm +++ b/scheme/week06/ex2_38.scm @@ -1,59 +1,59 @@ #lang scheme/base (require (planet schematics/schemeunit:3)) ; Exercise 2.38. The accumulate procedure is also known as fold-right, because it combines the ; first element of the sequence with the result of combining all the elements to the right. There is also a ; fold-left, which is similar to fold-right, except that it combines elements working in the ; opposite direction: ; (define (fold-left op initial sequence) ; (define (iter result rest) ; (if (null? rest) ; result ; (iter (op result (car rest)) ; (cdr rest)))) ; (iter initial sequence)) ; ; What are the values of ; ; (fold-right / 1 (list 1 2 3)) ; (fold-left / 1 (list 1 2 3)) ; (fold-right list nil (list 1 2 3)) ; (fold-left list nil (list 1 2 3)) ; ; Give a property that op should satisfy to guarantee that fold-right and fold-left will produce ; the same values for any sequence. (define (fold-left op initial sequence) (define (iter result rest) (if (null? rest) result (iter (op result (car rest)) (cdr rest)))) (iter initial sequence)) (define (accumulate op initial sequence) (if (null? sequence) initial (op (car sequence) (accumulate op initial (cdr sequence))))) (define fold-right accumulate) ; (fold-right / 1 (list 1 2 3)) -; 1.5 +; 1.5 (/ 1 (/ 2 3)) ; (fold-left / 1 (list 1 2 3)) -; 0.16666666666666666 (/ 0.5 3) +; 0.16666666666666666 (/ (/ 1 2) 3) ; (fold-right list nil (list 1 2 3)) ; (1 (2 (3 ()))) ; (fold-left list nil (list 1 2 3)) ; (((() 1) 2) 3) ; (list (list (list (list) 1) 2) 3) ; Give a property that op should satisfy to guarantee that fold-right and fold-left will produce ; the same values for any sequence. ; ; Any operation with commutativity such as + or - would produce the same values regardless of if a right or left fold was used. ; On a side note... Clojure's reduce apparently uses a left fold: ; user=> (reduce / [1 2 3]) ; 1/6
bmabey/sicp-study
5541fe5ed919b4f5bb439a0046fb38323043f140
exercise 2.38
diff --git a/scheme/week06/ex2_38.scm b/scheme/week06/ex2_38.scm new file mode 100644 index 0000000..406615f --- /dev/null +++ b/scheme/week06/ex2_38.scm @@ -0,0 +1,59 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.38. The accumulate procedure is also known as fold-right, because it combines the +; first element of the sequence with the result of combining all the elements to the right. There is also a +; fold-left, which is similar to fold-right, except that it combines elements working in the +; opposite direction: +; (define (fold-left op initial sequence) +; (define (iter result rest) +; (if (null? rest) +; result +; (iter (op result (car rest)) +; (cdr rest)))) +; (iter initial sequence)) +; +; What are the values of +; +; (fold-right / 1 (list 1 2 3)) +; (fold-left / 1 (list 1 2 3)) +; (fold-right list nil (list 1 2 3)) +; (fold-left list nil (list 1 2 3)) +; +; Give a property that op should satisfy to guarantee that fold-right and fold-left will produce +; the same values for any sequence. + +(define (fold-left op initial sequence) + (define (iter result rest) + (if (null? rest) + result + (iter (op result (car rest)) + (cdr rest)))) + (iter initial sequence)) + +(define (accumulate op initial sequence) + (if (null? sequence) + initial + (op (car sequence) + (accumulate op initial (cdr sequence))))) + +(define fold-right accumulate) + +; (fold-right / 1 (list 1 2 3)) +; 1.5 +; (fold-left / 1 (list 1 2 3)) +; 0.16666666666666666 (/ 0.5 3) +; (fold-right list nil (list 1 2 3)) +; (1 (2 (3 ()))) +; (fold-left list nil (list 1 2 3)) +; (((() 1) 2) 3) +; (list (list (list (list) 1) 2) 3) + +; Give a property that op should satisfy to guarantee that fold-right and fold-left will produce +; the same values for any sequence. +; +; Any operation with commutativity such as + or - would produce the same values regardless of if a right or left fold was used. + + +; On a side note... Clojure's reduce apparently uses a left fold: +; user=> (reduce / [1 2 3]) +; 1/6
bmabey/sicp-study
f58fb039b60e92d5b9dffba3eb88945c0be3e09c
cuurrying some matrix multiplication for ex 2.37
diff --git a/scheme/week06/ex2_37.scm b/scheme/week06/ex2_37.scm new file mode 100644 index 0000000..d9af039 --- /dev/null +++ b/scheme/week06/ex2_37.scm @@ -0,0 +1,66 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.37 +; Fill in the missing expressions in the following procedures for computing the other matrix operations. +; (The procedure accumulate-n is defined in exercise 2.36.) +; (define (matrix-*-vector m v) +; (map <??> m)) +; (define (transpose mat) +; (accumulate-n <??> <??> mat)) +; (define (matrix-*-matrix m n) +; (let ((cols (transpose n))) +; (map <??> m))) + +(define (accumulate op initial sequence) + (if (null? sequence) + initial + (op (car sequence) + (accumulate op initial (cdr sequence))))) + +(define (accumulate-n op init seqs) + (if (null? (car seqs)) + null + (cons (accumulate op init (map car seqs)) + (accumulate-n op init (map cdr seqs))))) + +(define (dot-product v w) + (accumulate + 0 (map * v w))) + +(define (curry f x) (lambda args (apply f x args))) + +(define (matrix-*-vector m v) + (map (curry dot-product v) m)) + +(define (transpose mat) + (accumulate-n cons null mat)) + +(define (matrix-*-matrix m n) + (let ((cols (transpose n))) + (map (curry matrix-*-vector cols) m))) + + + +(check-equal? + (dot-product '(1 2 3 4) '(1 2 3 4)) + (+ (* 1 1) (* 2 2) (* 3 3) (* 4 4)) + ) + +(check-equal? + (matrix-*-vector '((1 3 5) (2 4 6)) '(1 2 3)) + '(22 28) + ) + +(check-equal? + (transpose '((1 3) (2 4))) + '((1 2) (3 4)) + ) + +(check-equal? + (transpose '((1 4 7) (2 5 8) (3 6 9))) + '((1 2 3) (4 5 6) (7 8 9)) + ) + +(check-equal? + (matrix-*-matrix '((1 4 7) (2 5 8) (3 6 9)) '((1 4 7) (2 5 8) (3 6 9))) + '((30 66 102) (36 81 126) (42 96 150)) + )
bmabey/sicp-study
c415113a6c607b87f9a16a2d213acaef4680e860
exercise 2.36
diff --git a/scheme/week06/ex2_36.scm b/scheme/week06/ex2_36.scm new file mode 100644 index 0000000..23c409b --- /dev/null +++ b/scheme/week06/ex2_36.scm @@ -0,0 +1,30 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.36 +; The procedure accumulate-n is similar to accumulate except that it takes as its +; third argument a sequence of sequences, which are all assumed to have the same number of elements. It +; applies the designated accumulation procedure to combine all the first elements of the sequences, all the +; second elements of the sequences, and so on, and returns a sequence of the results. For instance, if s is a +; sequence containing four sequences, ((1 2 3) (4 5 6) (7 8 9) (10 11 12)), then the +; value of (accumulate-n + 0 s) should be the sequence (22 26 30). Fill in the missing +; expressions in the following definition of accumulate-n: +; (define (accumulate-n op init seqs) +; (if (null? (car seqs)) +; nil +; (cons (accumulate op init <??>) +; (accumulate-n op init <??>)))) + +(define (accumulate op initial sequence) + (if (null? sequence) + initial + (op (car sequence) + (accumulate op initial (cdr sequence))))) + +(define (accumulate-n op init seqs) + (if (null? (car seqs)) + null + (cons (accumulate op init (map car seqs)) + (accumulate-n op init (map cdr seqs))))) + +(let ((s '((1 2 3) (4 5 6) (7 8 9) (10 11 12)))) + (check-equal? (accumulate-n + 0 s) '(22 26 30)))
bmabey/sicp-study
e81f26406c3a5944cce115e2011a58957d070fd5
very clever stuf.. exercise 2.33
diff --git a/scheme/week06/ex2_33.scm b/scheme/week06/ex2_33.scm new file mode 100644 index 0000000..7838a17 --- /dev/null +++ b/scheme/week06/ex2_33.scm @@ -0,0 +1,31 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.33. +; Fill in the missing expressions to complete the following definitions of some basic +; list-manipulation operations as accumulations: +; +; (define (map p sequence) +; (accumulate (lambda (x y) <??>) nil sequence)) +; (define (append seq1 seq2) +; (accumulate cons <??> <??>)) +; (define (length sequence) +; (accumulate <??> 0 sequence)) + +(define (accumulate op initial sequence) + (if (null? sequence) + initial + (op (car sequence) + (accumulate op initial (cdr sequence))))) + +(define (map p sequence) + (accumulate (lambda (first rest) (cons (p first) rest)) null sequence)) +(define (append seq1 seq2) + (accumulate cons seq2 seq1)) +(define (length sequence) + (accumulate (lambda (first rest) (+ 1 rest)) 0 sequence)) + +(define (square x) (* x x)) + +(check-equal? (map square (list 2 4)) (list 4 16)) +(check-equal? (append (list 0 1) (list 2 4)) (list 0 1 2 4)) +(check-equal? (length (list 2 4 1)) 3)
bmabey/sicp-study
03de303f6ce016dd1b4db6563d3a1b3dd5c0b339
whitespace.. I think
diff --git a/scheme/week05/ex2_28.scm b/scheme/week05/ex2_28.scm index 75d896d..c67869c 100644 --- a/scheme/week05/ex2_28.scm +++ b/scheme/week05/ex2_28.scm @@ -1,27 +1,27 @@ #lang scheme/base (require (planet schematics/schemeunit:3)) ; Exercise 2.28 ; Write a procedure fringe that takes as argument a tree (represented as a list) and ; returns a list whose elements are all the leaves of the tree arranged in left-to-right order. For example, ; (define x (list (list 1 2) (list 3 4))) ; (fringe x) ; (1 2 3 4) ; (fringe (list x x)) ; (1 2 3 4 1 2 3 4) (define (fringe tree) - (define (loop tree leaves) - (cond ((null? tree) leaves) - ((not (pair? tree)) (list tree)) - (else (loop + (define (loop tree leaves) + (cond ((null? tree) leaves) + ((not (pair? tree)) (list tree)) + (else (loop (cdr tree) (append leaves (fringe (car tree))))))) (loop tree (list))) (let ((x (list (list 1 2) (list 3 4)))) (check-equal? (fringe x) (list 1 2 3 4)) (check-equal? (fringe (list x x)) (list 1 2 3 4 1 2 3 4))) (check-equal? (fringe (list 1 (list 2) 3)) (list 1 2 3)) (check-equal? (fringe (list 1 2 3)) (list 1 2 3))
bmabey/sicp-study
466b33b40e38190f8ecfe9e871a81fb78c284d08
exercise 2.32
diff --git a/scheme/week05/ex2_32.scm b/scheme/week05/ex2_32.scm new file mode 100644 index 0000000..6e9fcae --- /dev/null +++ b/scheme/week05/ex2_32.scm @@ -0,0 +1,30 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.33 +; We can represent a set as a list of distinct elements, and we can represent the set of all +; subsets of the set as a list of lists. For example, if the set is (1 2 3), then the set of all subsets is +; (() (3) (2) (2 3) (1) (1 3) (1 2) (1 2 3)). Complete the following definition of a +; procedure that generates the set of subsets of a set and give a clear explanation of why it works: +; (define (subsets s) +; (if (null? s) +; (list nil) +; (let ((rest (subsets (cdr s)))) +; (append rest (map <??> rest))))) + +(define (subsets s) + (if (null? s) + (list null) + (let ((rest (subsets (cdr s))) + (head (car s))) + (append rest (map (lambda (x) (cons head x)) rest))))) + +(check-equal? (subsets (list 1 2 3)) + (list (list) (list 3) (list 2) (list 2 3) (list 1) (list 1 3) (list 1 2) (list 1 2 3))) + +; To come up with this solution I assumed I had a working subsets procedure. With that assumption I then +; looked at what I would have for 'rest' in the case of {1 2 3} and what would be needed for the map's lambda. +; In this example 'rest' would be the subsets of {2 3} which are {0 {2} {3}}. I observed that the subsets of +; {1 2 3} are the subsets of {2 3} 'union'ed with those subsets intersected with the set {1}: {{1} {1 2} {1 3}} +; The append procedure (union) takes care of combining the 'rest' subsets with the other subsets yielding +; The key observation, then, is that the subset of set s is equal to s' U t where s' is the +; subset for s - {i} (given i ∈ s), and t is the set of each subset s'_j intersected with i.
bmabey/sicp-study
fda62625b2f33a8817f48588db8c2e67d23dc644
exercise 2.31
diff --git a/scheme/week05/ex2_31.scm b/scheme/week05/ex2_31.scm new file mode 100644 index 0000000..455a37b --- /dev/null +++ b/scheme/week05/ex2_31.scm @@ -0,0 +1,20 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.31 +; Abstract your answer to exercise 2.30 to produce a procedure tree-map with the +; property that square-tree could be defined as +; (define (square-tree tree) (tree-map square tree)) + +(define (square x) (* x x)) + +(define (tree-map proc tree) + (map (lambda (sub-tree) + (if (pair? sub-tree) + (tree-map proc sub-tree) + (proc sub-tree))) + tree)) + +(define (square-tree tree) (tree-map square tree)) + +(check-equal? (square-tree (list 1 (list 2 (list 3 4) 5))) + (list 1 (list 4 (list 9 16) 25)))
bmabey/sicp-study
e8a48e1e6507fa163654094ed06f2761708d7235
exercise 2.30
diff --git a/scheme/week05/ex2_30.scm b/scheme/week05/ex2_30.scm new file mode 100644 index 0000000..06f310d --- /dev/null +++ b/scheme/week05/ex2_30.scm @@ -0,0 +1,33 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.30 +; Define a procedure square-tree analogous to the square-list procedure of +; exercise 2.21. That is, square-list should behave as follows: +; (square-tree +; (list 1 +; (list 2 (list 3 4) 5) +; (list 6 7))) +; +; (1 (4 (9 16) 25) (36 49)) +; Define square-tree both directly (i.e., without using any higher-order procedures) and also by using +; map and recursion. + +(define (square x) (* x x)) + +(define (square-tree tree) + (cond ((null? tree) null) + ((not (pair? tree)) (square tree)) + (else (cons (square-tree (car tree)) + (square-tree (cdr tree)))))) + +(define (square-tree-w-map tree) + (map (lambda (sub-tree) + (if (pair? sub-tree) + (square-tree-w-map sub-tree) + (square sub-tree))) + tree)) + +(check-equal? (square-tree (list 1 (list 2 (list 3 4) 5))) + (list 1 (list 4 (list 9 16) 25))) +(check-equal? (square-tree-w-map (list 1 (list 2 (list 3 4) 5))) + (list 1 (list 4 (list 9 16) 25)))
bmabey/sicp-study
d813d9c1082ba6667e866c2e833ac114354bc01f
exercise 2.28
diff --git a/scheme/week05/ex2_28.scm b/scheme/week05/ex2_28.scm new file mode 100644 index 0000000..75d896d --- /dev/null +++ b/scheme/week05/ex2_28.scm @@ -0,0 +1,27 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.28 +; Write a procedure fringe that takes as argument a tree (represented as a list) and +; returns a list whose elements are all the leaves of the tree arranged in left-to-right order. For example, +; (define x (list (list 1 2) (list 3 4))) +; (fringe x) +; (1 2 3 4) +; (fringe (list x x)) +; (1 2 3 4 1 2 3 4) + + +(define (fringe tree) + (define (loop tree leaves) + (cond ((null? tree) leaves) + ((not (pair? tree)) (list tree)) + (else (loop + (cdr tree) + (append leaves (fringe (car tree))))))) + (loop tree (list))) + +(let ((x (list (list 1 2) (list 3 4)))) + (check-equal? (fringe x) (list 1 2 3 4)) + (check-equal? (fringe (list x x)) (list 1 2 3 4 1 2 3 4))) + +(check-equal? (fringe (list 1 (list 2) 3)) (list 1 2 3)) +(check-equal? (fringe (list 1 2 3)) (list 1 2 3))
bmabey/sicp-study
f0bdbb89e73d3e77cec1a3c913689d305a1b243a
exercise 2.27
diff --git a/scheme/week05/ex2_27.scm b/scheme/week05/ex2_27.scm new file mode 100644 index 0000000..024f2ed --- /dev/null +++ b/scheme/week05/ex2_27.scm @@ -0,0 +1,39 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.27 +; Modify your reverse procedure of exercise 2.18 to produce a deep-reverse +; procedure that takes a list as argument and returns as its value the list with its elements reversed and with +; all sublists deep-reversed as well. For example, +; (define x (list (list 1 2) (list 3 4))) +; x +; ((1 2) (3 4)) +; (reverse x) +; ((3 4) (1 2)) +; (deep-reverse x) +; ((4 3) (2 1)) + + +(define (reverse items) + (define (reverse-iter reversed items) + (if (null? items) + reversed + (reverse-iter (cons (car items) reversed) (cdr items)))) + (reverse-iter (list) items)) + +(define (deep-reverse items) + (define (reverse-iter reversed items) + (cond ((null? items) reversed) + ((not (pair? items)) items) + (else (reverse-iter + (cons (deep-reverse (car items)) reversed) + (cdr items))))) + (reverse-iter (list) items)) + +(check-equal? (reverse (list)) (list)) +(check-equal? (reverse (list 42)) (list 42)) +(check-equal? (reverse (list 23 42)) (list 42 23)) +(check-equal? (reverse (list 23 72 149 34)) (list 34 149 72 23)) + +(let ((x (list (list 1 2) (list 3 4)))) + (check-equal? (reverse x) (list (list 3 4) (list 1 2))) + (check-equal? (deep-reverse x) (list (list 4 3) (list 2 1))))
bmabey/sicp-study
ce160bd90aeea09531f0a29464b4ec72b30e84cf
exercise 2.26
diff --git a/scheme/week05/ex2_26.scm b/scheme/week05/ex2_26.scm new file mode 100644 index 0000000..88b8d69 --- /dev/null +++ b/scheme/week05/ex2_26.scm @@ -0,0 +1,15 @@ +; Exercise 2.26 +; Suppose we define x and y to be two lists: +; (define x (list 1 2 3)) +; (define y (list 4 5 6)) +; +; What result is printed by the interpreter in response to evaluating each of the following expressions: +; (append x y) +; (cons x y) +; (list x y) + + +; (append x y) ; => (1 2 3 4 5 6) +; (cons x y) ; => ((1 2 3) 4 5 6) +; (list x y) ; => ((1 2 3) (4 5 6)) +
bmabey/sicp-study
f0f9ec615d945626819c38eff5ea8cd1665ea4c0
exercise 2.25
diff --git a/scheme/week05/ex2_25.scm b/scheme/week05/ex2_25.scm new file mode 100644 index 0000000..3645b15 --- /dev/null +++ b/scheme/week05/ex2_25.scm @@ -0,0 +1,11 @@ +; Exercise 2.25 +; Give combinations of cars and cdrs that will pick 7 from each of the following lists: +; (1 3 (5 7) 9) +; ((7)) +; (1 (2 (3 (4 (5 (6 7)))))) +; +; Taking each lists as x: +; 1. (car (cdr (car (cdr (cdr x))))) +; 2. (car (car x)) +; 3. (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr x)))))))))))) +
bmabey/sicp-study
1b35fe835a7557c8262be3c393fa25c80d67cd47
exercise 2.24
diff --git a/scheme/week05/ex2_24.scm b/scheme/week05/ex2_24.scm new file mode 100644 index 0000000..065e724 --- /dev/null +++ b/scheme/week05/ex2_24.scm @@ -0,0 +1,17 @@ +; Exercise 2.24 +; Suppose we evaluate the expression (list 1 (list 2 (list 3 4))). Give the +; result printed by the interpreter, the corresponding box-and-pointer structure, and the interpretation of +; this as a tree (as in figure 2.6) +; +; It would evaluate to: +; (1 (2 (3 4))) +; +; ASCII art FTW: +; +; (1 (2 (3 4))) +; /\ +; 1 (2 (3 4)) +; / \ +; 2 (3 4) +; / \ +; 3 4
bmabey/sicp-study
a4b2fa86864c8aa88c5aab2669cd7dbd9376b577
exercise 2.23
diff --git a/scheme/week05/ex2_23.scm b/scheme/week05/ex2_23.scm new file mode 100644 index 0000000..6491ee7 --- /dev/null +++ b/scheme/week05/ex2_23.scm @@ -0,0 +1,25 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.23. The procedure for-each is similar to map. It takes as arguments a procedure and a list +; of elements. However, rather than forming a list of the results, for-each just applies the procedure to +; each of the elements in turn, from left to right. The values returned by applying the procedure to the +; elements are not used at all -- for-each is used with procedures that perform an action, such as +; printing. For example, +; (for-each (lambda (x) (newline) (display x)) +; (list 57 321 88)) +; 57 +; 321 +; 88 +; The value returned by the call to for-each (not illustrated above) can be something arbitrary, such as +; true. Give an implementation of for-each. +; +(define (for-each proc items) + (if (null? items) + null + (let ((head (car items)) (tail (cdr items))) + (proc head) + (for-each proc tail)))) + + +(for-each (lambda (x) (newline) (display x)) + (list 57 321 88))
bmabey/sicp-study
25224c04fa1d4bf3db91757caa6b0c4ab54a9fc6
exercise 2.21
diff --git a/scheme/week05/ex2_21.scm b/scheme/week05/ex2_21.scm new file mode 100644 index 0000000..ed17d74 --- /dev/null +++ b/scheme/week05/ex2_21.scm @@ -0,0 +1,26 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.21. The procedure square-list takes a list of numbers as argument and returns a list of +; the squares of those numbers. +; (square-list (list 1 2 3 4)) +; (1 4 9 16) +; Here are two different definitions of square-list. Complete both of them by filling in the missing +; expressions: +; (define (square-list items) +; (if (null? items) +; nil +; (cons <??> <??>))) +; (define (square-list items) +; (map <??> <??>)) + +(define (square x) (* x x)) + +(define (square-list-wo-map items) + (if (null? items) + null + (cons (square (car items)) (square-list-wo-map (cdr items))))) + +(define (square-list-w-map items) (map square items)) + +(check-equal? (square-list-w-map (list 1 2 3 4)) (list 1 4 9 16)) +(check-equal? (square-list-wo-map (list 1 2 3 4)) (list 1 4 9 16))
bmabey/sicp-study
18d4acc147b0f47283e9ac0e3049f3cb0b4cbb1e
exercise 2.20
diff --git a/scheme/week05/ex2_20.scm b/scheme/week05/ex2_20.scm new file mode 100644 index 0000000..2493dd5 --- /dev/null +++ b/scheme/week05/ex2_20.scm @@ -0,0 +1,43 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.18 +; ... write a procedure same-parity that takes one or more integers and returns a list +; of all the arguments that have the same even-odd parity as the first argument. For example, +; (same-parity 1 2 3 4 5 6 7) +; (1 3 5 7) +; (same-parity 2 3 4 5 6 7) +; (2 4 6) + +(define (empty? items) + (zero? (length items))) + +(define (filter filter-function items) + (if (empty? items) + items + (let ((head (car items)) (tail (cdr items))) + (if (filter-function head) + (cons head (filter filter-function tail)) + (filter filter-function tail))))) + +; This was working but was adding things in reverse order... +; (define (filter-iter filtered items) +; (if (empty? items) +; filtered +; (let ((head (car items))) +; (filter-iter +; (if (filter-function head) +; (cons head filtered) +; filtered) +; (cdr items))))) +; (filter-iter (list) items)) + +(define (same-parity . numbers) + (if (empty? numbers) + numbers + (let ((parity-function (if (even? (car numbers)) even? odd?))) + (filter parity-function numbers)))) + +(check-equal? (same-parity) (list)) +(check-equal? (same-parity 1) (list 1)) +(check-equal? (same-parity 1 2 3 4 5 6 7) (list 1 3 5 7)) +(check-equal? (same-parity 2 3 4 5 6 7) (list 2 4 6))
bmabey/sicp-study
d0ceabce57898c028ac40477ae03e34c61ed3bc8
exercise 2.18
diff --git a/scheme/week05/ex2_18.scm b/scheme/week05/ex2_18.scm new file mode 100644 index 0000000..e5c63e6 --- /dev/null +++ b/scheme/week05/ex2_18.scm @@ -0,0 +1,22 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.18 +; Define a procedure reverse that takes a list as argument and returns a list of the same +; elements in reverse order: +; (reverse (list 1 4 9 16 25)) +; (25 16 9 4 1) + +(define (empty? items) + (zero? (length items))) + +(define (reverse items) + (define (reverse-iter reversed items) + (if (empty? items) + reversed + (reverse-iter (cons (car items) reversed) (cdr items)))) + (reverse-iter (list) items)) + +(check-equal? (reverse (list)) (list)) +(check-equal? (reverse (list 42)) (list 42)) +(check-equal? (reverse (list 23 42)) (list 42 23)) +(check-equal? (reverse (list 23 72 149 34)) (list 34 149 72 23))
bmabey/sicp-study
b61e8934dc3080d8e2ce3e83267f14200042fc85
exercise 2.17
diff --git a/scheme/week05/ex2_17.scm b/scheme/week05/ex2_17.scm new file mode 100644 index 0000000..11231c1 --- /dev/null +++ b/scheme/week05/ex2_17.scm @@ -0,0 +1,22 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.17 +; Define a procedure last-pair that returns the list that contains only the last element +; of a given (nonempty) list: +; (last-pair (list 23 72 149 34)) +; (34) + +(define (last-pair items) + (let ((num-head-items (- (length items) 1))) + (define (last-pair-iter sub-list n) + (if (= num-head-items n) + (cdr sub-list) + (last-pair-iter (cdr sub-list) (+ n 1)))) + (if (<= num-head-items 0) + items + (last-pair-iter items 1)))) + +(check-equal? (last-pair (list)) (list)) +(check-equal? (last-pair (list 42)) (list 42)) +(check-equal? (last-pair (list 23 42)) (list 42)) +(check-equal? (last-pair (list 23 72 149 34)) (list 34))
bmabey/sicp-study
b8333be0ad6c0d967d8621879d8b20e8f2dfcadc
exercise 2.5 in scheme
diff --git a/scheme/week04/ex2_5.scm b/scheme/week04/ex2_5.scm new file mode 100644 index 0000000..d7a243e --- /dev/null +++ b/scheme/week04/ex2_5.scm @@ -0,0 +1,35 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) + +; Exercise 2.5 +; Show that we can represent pairs of nonnegative integers using only numbers and +; arithmetic operations if we represent the pair a and b as the integer that is the product 2^a3^b. Give the +; corresponding definitions of the procedures cons, car, and cdr. + +(define (root x r) + (expt x (/ 1 r))) + +(define (cbrt x) (root x 3)) + +(define (cons a b) + (* (expt 2 a) (expt 3 b))) + +(define (count-factors n p) + (if (zero? (remainder p n)) (+ 1 (count-factors n (/ p n))) + 0)) + +; Gonna curry just because I can... Probably not the best for debugging and doesn't save me anything... +(define (curry f x) (lambda args (apply f x args))) +(define car (curry count-factors 2)) +(define cdr (curry count-factors 3)) + +(check-equal? (cons 2 3) 108) + +(check-equal? (car (cons 0 3)) 0) +(check-equal? (cdr (cons 0 3)) 3) + +(check-equal? (car (cons 4 3)) 4) +(check-equal? (cdr (cons 4 3)) 3) + +(check-equal? (car (cons 4 0)) 4) +(check-equal? (cdr (cons 4 0)) 0)
bmabey/sicp-study
eec92f374e14f0e645f1b358d63183e936e38886
Church numerals are awesome. Exercise 2.6 in scheme.
diff --git a/scheme/week04/ex2_6.scm b/scheme/week04/ex2_6.scm new file mode 100644 index 0000000..31f0d95 --- /dev/null +++ b/scheme/week04/ex2_6.scm @@ -0,0 +1,83 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.6. +; In case representing pairs as procedures wasn't mind-boggling enough, consider that, in a +; language that can manipulate procedures, we can get by without numbers (at least insofar as nonnegative +; integers are concerned) by implementing 0 and the operation of adding 1 as +; +; (define zero (lambda (f) (lambda (x) x))) +; (define (add-1 n) +; (lambda (f) (lambda (x) (f ((n f) x))))) +; +; This representation is known as Church numerals, after its inventor, Alonzo Church, the logician who +; invented lambda calculus. +; +; Define one and two directly (not in terms of zero and add-1). (Hint: Use substitution to evaluate +; (add-1 zero)). Give a direct definition of the addition procedure + (not in terms of repeated +; application of add-1). + + +(define zero (lambda (f) (lambda (x) x))) +(define (add-1 n) + (lambda (f) (lambda (x) (f ((n f) x))))) + + +; In order to determine how to define one directly we can, as suggested, use the substitution method +; on (add-1 zero). Note: I am using g and y instead of f and x for the variables in the zero lambdas +; to avoid confusion. +; +; (add-1 zero) +; (lambda (f) (lambda (x) (f ((zero f) x)))) +; (lambda (f) (lambda (x) (f (((lambda (g) (lambda (y) y)) f) x)))) +; +; At this point we are done expanding it but we can simplify it down. +; With zero fully expanded we see it takes one argument (called g) which it simply ignores and returns +; (lambda (y) y), also know as the identity function. The argument that the outer 'zero' lambda is provided, +; and ignores, is f. So the f is removed leaving only the identity function: +; +; (lambda (f) (lambda (x) (f (identity x)))) +; +; Which then simplifies to: +; +; (lambda (f) (lambda (x) (f x))) +; +; This is our direct definition of one: + +(define one (lambda (f) (lambda (x) (f x)))) + +; With that definition we can reason about creating a procedure which can give us real numbers from the +; Church numerals being represented as lambdas. +; (idea and procedure courtesy of http://www.kendyck.com/archives/2007/07/07/solution-to-sicp-26/) +(define (to-integer n) + (define (inc x) (+ 1 x)) + ((n inc) 0)) + +(check-equal? (to-integer one) 1) + +; Now, lets do the same thing to obtain the direct definition of two using one as a starting point. +; +; (add-1 one) +; (lambda (f) (lambda (x) (f ((one f) x)))) +; (lambda (f) (lambda (x) (f (((lambda (g) (lambda (y) (g y))) f) x)))) +; +; Lets start by taking f for g in the outer 'one' lambda: +; (lambda (f) (lambda (x) (f ((lambda (y) (f y)) x)))) +; +; We can now apply x as y to get our definition of two: +; (lambda (f) (lambda (x) (f (f x)))) + +(define two (lambda (f) (lambda (x) (f (f x))))) + +(check-equal? (to-integer two) 2) + +; For a general way of adding Church numbers I find it easiest to think of the process in terms +; of composing the given lambdas/procedures. In exercise 1.42 we came up with the following compose: + +(define (compose f g) (lambda (x) (f (g x)))) + +; With this we can compose the Church numerals by passing along the 'f' lambda they need to operate: + +(define (add a b) + (lambda (f) (compose (a f) (b f)))) + +(check-equal? (to-integer (add one two)) 3)
bmabey/sicp-study
119e98bfb7581d24d6fce0c352d786abeeef23c3
exercise 2.4 in scheme
diff --git a/scheme/week04/ex2_4.scm b/scheme/week04/ex2_4.scm new file mode 100644 index 0000000..62050ec --- /dev/null +++ b/scheme/week04/ex2_4.scm @@ -0,0 +1,29 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.4. +; Here is an alternative procedural representation of pairs. For this representation, verify that +; (car (cons x y)) yields x for any objects x and y. +; (define (cons x y) +; (lambda (m) (m x y))) +; (define (car z) +; (z (lambda (p q) p))) +; What is the corresponding definition of cdr? (Hint: To verify that this works, make use of the +; substitution model of section 1.1.5.) + +(define (cons x y) + (lambda (m) (m x y))) + +(define (car z) + (z (lambda (p q) p))) + +(define (cdr z) + (z (lambda (p q) q))) + +(check-equal? (car (cons 10 20)) 10) +(check-equal? (cdr (cons 10 20)) 20) + +; What is going on here is the cons is creating a closure around x and y by returning a lambda which +; takes yet another procedure that yields the original x and y to this given procedure. +; Both the car and cdr definitions then, in turn, call the lambda (the pair) with another lambda that returns the +; appropriate variable. For clarity the p and q should be renamed to x and y IMO. I think the book +; authors probably realized this but didn't want to give any hints about what was going on. :)
bmabey/sicp-study
0acd32bbf947d4be90db8389cbb17970f280d556
exercise 2.3 in scheme
diff --git a/scheme/week04/ex2_3.scm b/scheme/week04/ex2_3.scm new file mode 100644 index 0000000..37a289b --- /dev/null +++ b/scheme/week04/ex2_3.scm @@ -0,0 +1,37 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.3 +; Implement a representation for rectangles in a plane. (Hint: You may want to make use of +; exercise 2.2.) In terms of your constructors and selectors, create procedures that compute the perimeter +; and the area of a given rectangle. Now implement a different representation for rectangles. Can you +; design your system with suitable abstraction barriers, so that the same perimeter and area procedures will +; work using either representation? + +(define make-point cons) +(define x-point car) +(define y-point cdr) + +(define make-dimension cons) +(define dimension-width car) +(define dimension-height cdr) + +(define (make-rectangle top-left-x top-left-y width height) + (cons (make-point top-left-x top-left-y) (make-dimension width height))) + +(define rectangle-top-left-point car) +(define rectangle-dimension cdr) + +(define (rectangle-height rectangle) + (dimension-height (rectangle-dimension rectangle))) + +(define (rectangle-width rectangle) + (dimension-width (rectangle-dimension rectangle))) + +(define (rectangle-area rectangle) + (* (rectangle-width rectangle) (rectangle-height rectangle))) + +(define (rectangle-perimeter rectangle) + (+ (* 2 (rectangle-width rectangle)) (* 2 (rectangle-height rectangle)))) + +(check-equal? (rectangle-area (make-rectangle 0 0 5 10)) 50) +(check-equal? (rectangle-perimeter (make-rectangle 0 0 5 10)) 30)
bmabey/sicp-study
cc6474d0d7f561b2d2e523e8e2ac23a7dd742cb8
exercise 2.2 in scheme
diff --git a/scheme/week04/ex2_2.scm b/scheme/week04/ex2_2.scm new file mode 100644 index 0000000..eefdca8 --- /dev/null +++ b/scheme/week04/ex2_2.scm @@ -0,0 +1,33 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.2 +; Consider the problem of representing line segments in a plane. Each segment is +; represented as a pair of points: a starting point and an ending point. Define a constructor +; make-segment and selectors start-segment and end-segment that define the representation of +; segments in terms of points. Furthermore, a point can be represented as a pair of numbers: the x +; coordinate and the y coordinate. Accordingly, specify a constructor make-point and selectors +; x-point and y-point that define this representation. Finally, using your selectors and constructors, +; define a procedure midpoint-segment that takes a line segment as argument and returns its midpoint +; (the point whose coordinates are the average of the coordinates of the endpoints). + + +(define make-point cons) +(define x-point car) +(define y-point cdr) + +(define (make-segment x1 y1 x2 y2) + (cons (make-point x1 y1) (make-point x2 y2))) + +(define start-segment car) +(define end-segment cdr) + +(define (midpoint-segment segment) + (let ((x1 (x-point (start-segment segment))) + (x2 (x-point (end-segment segment))) + (y1 (y-point (start-segment segment))) + (y2 (y-point (end-segment segment))) + ) + (make-point (/ (+ x1 x2) 2) (/ (+ y1 y2) 2)))) + +(check-equal? (midpoint-segment (make-segment 0 0 0 10)) (make-point 0 5)) +(check-equal? (midpoint-segment (make-segment -6 5 7 3)) (make-point (/ 1 2) 4))
bmabey/sicp-study
a77d866b5b990fe4d099b3a001e42c80a6367122
exercise 2.1 in scheme
diff --git a/scheme/week04/ex2_1.scm b/scheme/week04/ex2_1.scm new file mode 100644 index 0000000..7b71488 --- /dev/null +++ b/scheme/week04/ex2_1.scm @@ -0,0 +1,30 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 2.1. +; Define a better version of make-rat that handles both positive and negative arguments. +; Make-rat should normalize the sign so that if the rational number is positive, both the numerator and +; denominator are positive, and if the rational number is negative, only the numerator is negative. + +(define (gcd a b) + (if (= b 0) + a + (gcd b (remainder a b)))) + +(define (make-rat n d) + (define (make n d) + (let ((g (abs (gcd n d)))) + (cons (/ n g) (/ d g)))) + (if (< d 0) + (make (- n) (- d)) + (make n d))) + + +(check-equal? (make-rat 1 2) (cons 1 2)) +(check-equal? (make-rat -1 2) (cons -1 2)) +(check-equal? (make-rat 1 -2) (cons -1 2)) +(check-equal? (make-rat -1 -2) (cons 1 2)) + +(check-equal? (make-rat 2 4) (cons 1 2)) +(check-equal? (make-rat -2 4) (cons -1 2)) +(check-equal? (make-rat 2 -4) (cons -1 2)) +(check-equal? (make-rat -2 -4) (cons 1 2))
bmabey/sicp-study
6b77a04b085b166df81a991288bf5056d620136f
no changes to make-rat seems to be needed for ex2.1 in clojure...
diff --git a/clojure/week04/ex2_1.clj b/clojure/week04/ex2_1.clj new file mode 100644 index 0000000..103d15d --- /dev/null +++ b/clojure/week04/ex2_1.clj @@ -0,0 +1,75 @@ +; Rational number code translated from section 2.1 +(ns sicpstudy.ex2_1 (:use clojure.contrib.test-is)) + +(defn gcd [a b] + (if (= b 0) + a + (gcd b (mod a b)))) + +(defn make-rat [n d] + (let [g (gcd n d)] + [(/ n g) (/ d g)])) + +(defn numer [x] + (first x)) + +(defn denom [x] + (last x)) + +(defn equal-rat? [x y] + (= (* (numer x) (denom y)) + (* (numer y) (denom x)))) + +(defn add-rat [x y] + (make-rat (+ (* (numer x) (denom y)) + (* (numer y) (denom x))) + (* (denom x) (denom y)))) + +(defn sub-rat [x y] + (make-rat (- (* (numer x) (denom y)) + (* (numer y) (denom x))) + (* (denom x) (denom y)))) + +(defn div-rat [x y] + (make-rat (* (numer x) (denom y)) + (* (denom x) (numer y)))) + +(defn mul-rat [x y] + (make-rat (* (numer x) (numer y)) + (* (denom x) (denom y)))) + +(deftest test-equal-rat + (is (equal-rat? (make-rat 1 2) (make-rat 1 2))) + (is (not (equal-rat? (make-rat 3 2) (make-rat 1 2))))) + +(deftest test-make-rat-reduces-to-lowest-terms + (is (equal-rat? (make-rat 5 10) (make-rat 1 2)))) + +(deftest test-make-rat-handles-signs + (is (equal-rat? (make-rat -1 -2) [1 2])) + (is (equal-rat? (make-rat -5 -3) [5 3])) + (is (equal-rat? (make-rat -1 2) [-1 2]))) + +(deftest test-make-rat-only-allows-numer-to-be-negative + (is (equal-rat? (make-rat 2 -4) [-1 2]))) + +(deftest test-numer + (is (= (numer (make-rat 5 7)) 5))) + +(deftest test-denom + (is (= (denom (make-rat 5 7)) 7))) + +(deftest test-add-rat + (is (equal-rat? (add-rat (make-rat 3 4) (make-rat 1 2)) (make-rat 5 4)))) + +(deftest test-sub-rat + (is (equal-rat? (sub-rat (make-rat 3 4) (make-rat 1 2)) (make-rat 1 4)))) + +(deftest test-div-rat + (is (equal-rat? (div-rat (make-rat 1 2) (make-rat 3 5)) (make-rat 5 6)))) + +(deftest test-mul-rat + (is (equal-rat? (mul-rat (make-rat 1 2) (make-rat 5 6)) (make-rat 5 12)))) + +(run-tests) +
bmabey/sicp-study
a07fd7b3657e72b50610506e57d518cba0187ed3
make-rat in clojure- translated from section 2.1
diff --git a/clojure/week04/make-rat_from_book.clj b/clojure/week04/make-rat_from_book.clj new file mode 100644 index 0000000..f0e8871 --- /dev/null +++ b/clojure/week04/make-rat_from_book.clj @@ -0,0 +1,67 @@ +; Rational number code translated from section 2.1 +(ns sicpstudy.make-rat (:use clojure.contrib.test-is)) + +(defn gcd [a b] + (if (= b 0) + a + (gcd b (mod a b)))) + +(defn make-rat [n d] + (let [g (gcd n d)] + [(/ n g) (/ d g)])) + +(defn numer [x] + (first x)) + +(defn denom [x] + (last x)) + +(defn equal-rat? [x y] + (= (* (numer x) (denom y)) + (* (numer y) (denom x)))) + +(defn add-rat [x y] + (make-rat (+ (* (numer x) (denom y)) + (* (numer y) (denom x))) + (* (denom x) (denom y)))) + +(defn sub-rat [x y] + (make-rat (- (* (numer x) (denom y)) + (* (numer y) (denom x))) + (* (denom x) (denom y)))) + +(defn div-rat [x y] + (make-rat (* (numer x) (denom y)) + (* (denom x) (numer y)))) + +(defn mul-rat [x y] + (make-rat (* (numer x) (numer y)) + (* (denom x) (denom y)))) + +(deftest test-equal-rat + (is (equal-rat? (make-rat 1 2) (make-rat 1 2))) + (is (not (equal-rat? (make-rat 3 2) (make-rat 1 2))))) + +(deftest test-make-rat-reduces-to-lowest-terms + (is (equal-rat? (make-rat 5 10) (make-rat 1 2)))) + +(deftest test-numer + (is (= (numer (make-rat 5 7)) 5))) + +(deftest test-denom + (is (= (denom (make-rat 5 7)) 7))) + +(deftest test-add-rat + (is (equal-rat? (add-rat (make-rat 3 4) (make-rat 1 2)) (make-rat 5 4)))) + +(deftest test-sub-rat + (is (equal-rat? (sub-rat (make-rat 3 4) (make-rat 1 2)) (make-rat 1 4)))) + +(deftest test-div-rat + (is (equal-rat? (div-rat (make-rat 1 2) (make-rat 3 5)) (make-rat 5 6)))) + +(deftest test-mul-rat + (is (equal-rat? (mul-rat (make-rat 1 2) (make-rat 5 6)) (make-rat 5 12)))) + +(run-tests) +
bmabey/sicp-study
93d3b06f832aead1a0e5f7ba1b2269ff16fbae6a
exercise 1.43
diff --git a/scheme/week03/ex1_43.scm b/scheme/week03/ex1_43.scm new file mode 100644 index 0000000..09e45dc --- /dev/null +++ b/scheme/week03/ex1_43.scm @@ -0,0 +1,25 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Exercise 1.43. If f is a numerical function and n is a positive integer, then we can form the nth repeated +; application of f, which is defined to be the function whose value at x is f(f(...(f(x))...)). For example, +; if f is the function x -> x + 1, then the nth repeated application of f is the function x -> x + n. If f is the +; operation of squaring a number, then the nth repeated application of f is the function that raises its +; argument to the 2nth power. Write a procedure that takes as inputs a procedure that computes f and a +; positive integer n and returns the procedure that computes the nth repeated application of f. Your +; procedure should be able to be used as follows: +; ((repeated square 2) 5) +; 625 + +(define (square x) (* x x)) +(define (compose f g) (lambda (x) (f (g x)))) + +(define (repeated f n) + (define (repeat-fn f-prime i) + (if (>= i n) f-prime + (repeat-fn (compose f f-prime) (+ i 1)))) + (repeat-fn f 1)) + + +(check-eq? ((repeated square 2) 5) 625) +(check-eq? ((repeated square 0) 2) 4) +
bmabey/sicp-study
a839fd3e2daeab1ef97cb15a838be8b90034e05d
exercise 1.42
diff --git a/scheme/week03/ex1_29.scm b/scheme/week03/ex1_29.scm index 0070856..4224411 100644 --- a/scheme/week03/ex1_29.scm +++ b/scheme/week03/ex1_29.scm @@ -1,48 +1,47 @@ #lang scheme/base -(require (planet schematics/schemeunit:3)) (define (cube x) (* x x x)) (define (even? n) (= (remainder n 2) 0)) (define (integral-simpsons f a b n) (let ((h (/ (- b a) n))) (define (y-k k) (let ((y (f (+ a (* k h))))) (cond ((or (= k n) (= k 0)) y) ((even? k) (* 2 y)) (else (* 4 y))))) (define (loop k total) (if (> k n) total (loop (+ k 1) (+ total (y-k k))))) (* (/ h 3) (loop 0 0)))) (define (sum term a next b) (if (> a b) 0 (+ (term a) (sum term (next a) next b)))) (define (integral f a b dx) (define (add-dx x) (+ x dx)) (* (sum f (+ a (/ dx 2.0)) add-dx b) dx)) (integral cube 0 1 0.01) (integral cube 0 1 0.001) (integral cube 0 1 0.0001) (integral-simpsons cube 0 1 2) (integral-simpsons cube 0 1 100) (integral-simpsons cube 0 1 1000) ; The integral method from the book even after 1000 iterations is unable to arrive to the correct solution. ; (It approximates to 0.24999999874993412 after 1000.) However, Simpson's method finds the exact answer ; even with n just set to 2. diff --git a/scheme/week03/ex1_42.scm b/scheme/week03/ex1_42.scm new file mode 100644 index 0000000..06e9193 --- /dev/null +++ b/scheme/week03/ex1_42.scm @@ -0,0 +1,17 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) +; Ex. 1.42 +; Let f and g be two one-argument functions. The composition f after g is defined to be the +; function x -> f(g(x)). Define a procedure compose that implements composition. For example, if inc is +; a procedure that adds 1 to its argument, +; ((compose square inc) 6) +; 49 + +(define (square x) (* x x)) + +(define (inc x) (+ x 1)) + +(define (compose f g) (lambda (x) (f (g x)))) + +(check-eq? ((compose square inc) 6) 49) +
bmabey/sicp-study
3a58af4726633c21565483e9b1674ffb69f65458
exercise 1.36
diff --git a/scheme/week03/ex1_36.scm b/scheme/week03/ex1_36.scm new file mode 100644 index 0000000..d1311f3 --- /dev/null +++ b/scheme/week03/ex1_36.scm @@ -0,0 +1,72 @@ +#lang scheme/base + +(define tolerance 0.00001) +(define (fixed-point f first-guess) + (define (close-enough? v1 v2) + (< (abs (- v1 v2)) tolerance)) + (define (try guess) + (let ((next (f guess))) + (display next) + (newline) + (if (close-enough? guess next) + next + (try next)))) + (try first-guess)) + + + +(fixed-point (lambda (x) (/ (log 1000) (log x))) 2.0) +; 35 guesses: +; 9.965784284662087 +; 3.004472209841214 +; 6.279195757507157 +; 3.7598507024015393 +; 5.2158437849258945 +; 4.182207192401398 +; 4.82776509834459 +; 4.387593384662677 +; 4.671250085763899 +; 4.481403616895052 +; 4.6053657460929 +; 4.5230849678718865 +; 4.577114682047341 +; 4.541382480151454 +; 4.564903245230833 +; 4.549372679303342 +; 4.559606491913287 +; 4.552853875788271 +; 4.557305529748263 +; 4.554369064436181 +; 4.556305311532999 +; 4.555028263573554 +; 4.555870396702851 +; 4.555315001192079 +; 4.5556812635433275 +; 4.555439715736846 +; 4.555599009998291 +; 4.555493957531389 +; 4.555563237292884 +; 4.555517548417651 +; 4.555547679306398 +; 4.555527808516254 +; 4.555540912917957 +; 4.555532270803653 +; 4.555532270803653 + +(define (average numbers) + (/ (apply + numbers) (length numbers))) + +(display "\nNow with average damping:\n") +(fixed-point (lambda (x) (average (list x (/ (log 1000) (log x))))) 2.0) +; Only takes 10 guesses with average damping: +; 5.9828921423310435 +; 4.922168721308343 +; 4.628224318195455 +; 4.568346513136243 +; 4.5577305909237005 +; 4.555909809045131 +; 4.555599411610624 +; 4.5555465521473675 +; 4.555537551999825 +; 4.555537551999825 +
bmabey/sicp-study
7db375eccc5be758376f1ef1135b7fac92c27eb4
exercise 1.29
diff --git a/scheme/week03/ex1_29.scm b/scheme/week03/ex1_29.scm new file mode 100644 index 0000000..0070856 --- /dev/null +++ b/scheme/week03/ex1_29.scm @@ -0,0 +1,48 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) + +(define (cube x) (* x x x)) + +(define (even? n) + (= (remainder n 2) 0)) + +(define (integral-simpsons f a b n) + (let ((h (/ (- b a) n))) + + (define (y-k k) + (let ((y (f (+ a (* k h))))) + (cond ((or (= k n) (= k 0)) y) + ((even? k) (* 2 y)) + (else (* 4 y))))) + + (define (loop k total) + (if (> k n) total + (loop (+ k 1) (+ total (y-k k))))) + + (* (/ h 3) (loop 0 0)))) + + +(define (sum term a next b) + (if (> a b) + 0 + (+ (term a) + (sum term (next a) next b)))) + +(define (integral f a b dx) + (define (add-dx x) (+ x dx)) + (* (sum f (+ a (/ dx 2.0)) add-dx b) + + dx)) + +(integral cube 0 1 0.01) +(integral cube 0 1 0.001) +(integral cube 0 1 0.0001) + +(integral-simpsons cube 0 1 2) +(integral-simpsons cube 0 1 100) +(integral-simpsons cube 0 1 1000) + +; The integral method from the book even after 1000 iterations is unable to arrive to the correct solution. +; (It approximates to 0.24999999874993412 after 1000.) However, Simpson's method finds the exact answer +; even with n just set to 2. +
bmabey/sicp-study
a5d4be2a26e1e46b8c6ae88bd3168763b5a810c8
exercise 1.23
diff --git a/scheme/week02/ex1_23.scm b/scheme/week02/ex1_23.scm new file mode 100644 index 0000000..4cdd99a --- /dev/null +++ b/scheme/week02/ex1_23.scm @@ -0,0 +1,52 @@ +#lang planet neil/sicp +; SICP exercise 1.23 + +(define (square x) (* x x)) + + +(define (prime? n) + (define (next test-divisor) + (if (= test-divisor 2) 3 + (+ test-divisor 2))) + (define (find-divisor n test-divisor) + (cond ((> (square test-divisor) n) n) + ((divides? test-divisor n) test-divisor) + (else (find-divisor n (next test-divisor))))) + (define (divides? a b) + (= (remainder b a) 0)) + + (define (smallest-divisor n) + (find-divisor n 2)) + + (= n (smallest-divisor n))) + + + + +(define (timed-prime-test n) + (newline) + (display n) + (start-prime-test n (runtime))) +(define (start-prime-test n start-time) + (if (prime? n) + (report-prime (- (runtime) start-time)) + 0)) +(define (report-prime elapsed-time) + (display " *** ") + (display elapsed-time) + 1) + +(define (find-three-primes starting-num) + (define (loop num primes-found) + (if (= primes-found 3) true + (loop (+ num 2) (+ primes-found (timed-prime-test num))))) + (newline) + (loop (+ 1 starting-num) 0)) + +; When ran with the extra checks I got these times: +;(find-three-primes 100000000000000) ; (+ 13032210 13068029 12948528) # => 39048767 +; After I implemented the next procedure I got: +;(find-three-primes 100000000000000) ; (+ 6929346 6756755 6998871) # => 20684972 +; So, it is about half as fast as the orginal as you would expect it to be since we avoid half of the calls to find-divisor. + +
bmabey/sicp-study
3075ce22e53d0186a54cbec0d8e339a0e0015c43
removing fast-prime since it is not needed for this exercise
diff --git a/scheme/week02/ex1_22.scm b/scheme/week02/ex1_22.scm index d23e791..a6af72b 100644 --- a/scheme/week02/ex1_22.scm +++ b/scheme/week02/ex1_22.scm @@ -1,70 +1,51 @@ #lang planet neil/sicp (define (square x) (* x x)) -(define (expmod base exp m) - (cond ((= exp 0) 1) - ((even? exp) - (remainder (square (expmod base (/ exp 2) m)) - m)) - (else - (remainder (* base (expmod base (- exp 1) m)) - m)))) - -(define (fermat-test n) - (define (try-it a) - (= (expmod a n n) a)) - (try-it (+ 1 (random (- n 1))))) - -(define (fast-prime? n times) - (cond ((= times 0) true) - ((fermat-test n) (fast-prime? n (- times 1))) - (else false))) - (define (smallest-divisor n) (find-divisor n 2)) (define (find-divisor n test-divisor) (cond ((> (square test-divisor) n) n) ((divides? test-divisor n) test-divisor) (else (find-divisor n (+ test-divisor 1))))) (define (divides? a b) (= (remainder b a) 0)) (define (prime? n) (= n (smallest-divisor n))) (define (timed-prime-test n) (newline) (display n) (start-prime-test n (runtime))) (define (start-prime-test n start-time) (if (prime? n) (report-prime (- (runtime) start-time)) 0)) (define (report-prime elapsed-time) (display " *** ") (display elapsed-time) 1) (define (find-three-primes starting-num) (define (loop num primes-found) (if (= primes-found 3) true (loop (+ num 2) (+ primes-found (timed-prime-test num))))) (newline) (loop (+ 1 starting-num) 0)) ;(sqrt 10) => 3.1622776601683795 (find-three-primes 1000) ; (+ 23 23 22) => 68 (find-three-primes 10000) ; (+ 59 59 59) => 177: 2.6029411764705883x slower (find-three-primes 100000); (+ 174 305 176) => 655: 3.7005649717514126x slower (find-three-primes 1000000); (+ 549 568 563) => 1680: 2.564885496183206x slower (find-three-primes 100000000000) ; (+ 481263 410991 435095) => 1327349 (find-three-primes 1000000000000) ; (+ 1337185 1315346 1309145) => 3961676: 2.7784911784201154x slower (find-three-primes 10000000000000) ; (+ 4159272 4121860 4173517) => 12454649: 3.1437828333260973x slower (find-three-primes 100000000000000) ; (+ 13032210 13068029 12948528) => 39048767: 3.1352763935780126x slower ; When I bump the numbers up higher I see the (sqrt 10) slowdown that is expected for the algorhtim showing that it is indeed theta(sqrt(n)) runtime.
bmabey/sicp-study
210f1ccd271b8e352716fd56c9a7852773adbd96
ran some higher numbers for ex1_22
diff --git a/scheme/week02/ex1_22.scm b/scheme/week02/ex1_22.scm index 5578404..d23e791 100644 --- a/scheme/week02/ex1_22.scm +++ b/scheme/week02/ex1_22.scm @@ -1,60 +1,70 @@ #lang planet neil/sicp (define (square x) (* x x)) (define (expmod base exp m) (cond ((= exp 0) 1) ((even? exp) (remainder (square (expmod base (/ exp 2) m)) m)) (else (remainder (* base (expmod base (- exp 1) m)) m)))) (define (fermat-test n) (define (try-it a) (= (expmod a n n) a)) (try-it (+ 1 (random (- n 1))))) (define (fast-prime? n times) (cond ((= times 0) true) ((fermat-test n) (fast-prime? n (- times 1))) (else false))) (define (smallest-divisor n) (find-divisor n 2)) (define (find-divisor n test-divisor) (cond ((> (square test-divisor) n) n) ((divides? test-divisor n) test-divisor) (else (find-divisor n (+ test-divisor 1))))) (define (divides? a b) (= (remainder b a) 0)) (define (prime? n) (= n (smallest-divisor n))) (define (timed-prime-test n) (newline) (display n) (start-prime-test n (runtime))) (define (start-prime-test n start-time) (if (prime? n) (report-prime (- (runtime) start-time)) 0)) (define (report-prime elapsed-time) (display " *** ") (display elapsed-time) 1) (define (find-three-primes starting-num) (define (loop num primes-found) (if (= primes-found 3) true (loop (+ num 2) (+ primes-found (timed-prime-test num))))) (newline) (loop (+ 1 starting-num) 0)) -(find-three-primes 1000) -(find-three-primes 10000) -(find-three-primes 100000) -(find-three-primes 1000000) +;(sqrt 10) => 3.1622776601683795 +(find-three-primes 1000) ; (+ 23 23 22) => 68 +(find-three-primes 10000) ; (+ 59 59 59) => 177: 2.6029411764705883x slower +(find-three-primes 100000); (+ 174 305 176) => 655: 3.7005649717514126x slower +(find-three-primes 1000000); (+ 549 568 563) => 1680: 2.564885496183206x slower + +(find-three-primes 100000000000) ; (+ 481263 410991 435095) => 1327349 +(find-three-primes 1000000000000) ; (+ 1337185 1315346 1309145) => 3961676: 2.7784911784201154x slower +(find-three-primes 10000000000000) ; (+ 4159272 4121860 4173517) => 12454649: 3.1437828333260973x slower +(find-three-primes 100000000000000) ; (+ 13032210 13068029 12948528) => 39048767: 3.1352763935780126x slower + + +; When I bump the numbers up higher I see the (sqrt 10) slowdown that is expected for the algorhtim showing that it is indeed theta(sqrt(n)) runtime. +
bmabey/sicp-study
b3bfd5da8b331cfcdb7c3d09ad5bb8e3c3037cc1
whitespace
diff --git a/scheme/week02/ex1_19.scm b/scheme/week02/ex1_19.scm index 7001c34..6d51ed2 100644 --- a/scheme/week02/ex1_19.scm +++ b/scheme/week02/ex1_19.scm @@ -1,46 +1,55 @@ #lang scheme/base (require (planet schematics/schemeunit:3)) ; SICP Exercise 1.19 ; My alegraba for this problem can be found in ex1_19.tex. I should really look into SLaTeX... (define (fib-tree-recusive-process n) (cond ((= n 0) 0) ((= n 1) 1) (else (+ (fib-tree-recusive-process (- n 1)) (fib-tree-recusive-process (- n 2)))))) (define (fib-iterative-process n) (define (fib-iter a b count) (if (= count 0) b (fib-iter (+ a b) a (- count 1)))) (fib-iter 1 0 n)) (define (square x) (* x x)) (define (fib-log n) (define (fib-iter a b p q count) (cond ((= count 0) b) ((even? count) (fib-iter a b (+ (square p) (square q)) ; compute p' (+ (* 2 p q) (square q)) ; compute q' (/ count 2))) (else (fib-iter (+ (* b q) (* a q) (* a p)) (+ (* b p) (* a q)) p q (- count 1))))) (fib-iter 1 0 0 1 n)) +(define (expmod base exp m) + (cond ((= exp 0) 1) + ((even? exp) + (remainder (square (expmod base (/ exp 2) m)) + m)) + (else + (remainder (* base (expmod base (- exp 1) m)) + m)))) + (check-eq? (fib-tree-recusive-process 8) 21) (check-eq? (fib-iterative-process 8) 21) (check-eq? (fib-log 8) 21) (check-eq? (fib-log 20) 6765)
bmabey/sicp-study
bb7e25f9f55d214c2fde26c003517f49d12faad3
exercise 1.26
diff --git a/scheme/week02/ex1_26.scm b/scheme/week02/ex1_26.scm new file mode 100644 index 0000000..659fb95 --- /dev/null +++ b/scheme/week02/ex1_26.scm @@ -0,0 +1,4 @@ +;; Exercies 1.26 +;; +;; By not using the square procedure the expmod procedure gets evaluated twice for each set of arguments. +;; This counteracts the optimizations of expmod and brings the runtime back to θ(n).
bmabey/sicp-study
ade366c00f767cb29734a976bd11cff0f4eb0b36
code for ex1_22.scm
diff --git a/scheme/week02/ex1_22.scm b/scheme/week02/ex1_22.scm new file mode 100644 index 0000000..5578404 --- /dev/null +++ b/scheme/week02/ex1_22.scm @@ -0,0 +1,60 @@ +#lang planet neil/sicp + +(define (square x) (* x x)) + +(define (expmod base exp m) + (cond ((= exp 0) 1) + ((even? exp) + (remainder (square (expmod base (/ exp 2) m)) + m)) + (else + (remainder (* base (expmod base (- exp 1) m)) + m)))) + +(define (fermat-test n) + (define (try-it a) + (= (expmod a n n) a)) + (try-it (+ 1 (random (- n 1))))) + +(define (fast-prime? n times) + (cond ((= times 0) true) + ((fermat-test n) (fast-prime? n (- times 1))) + (else false))) + +(define (smallest-divisor n) + (find-divisor n 2)) +(define (find-divisor n test-divisor) + (cond ((> (square test-divisor) n) n) + ((divides? test-divisor n) test-divisor) + (else (find-divisor n (+ test-divisor 1))))) +(define (divides? a b) + (= (remainder b a) 0)) + +(define (prime? n) + (= n (smallest-divisor n))) + +(define (timed-prime-test n) + (newline) + (display n) + (start-prime-test n (runtime))) +(define (start-prime-test n start-time) + (if (prime? n) + (report-prime (- (runtime) start-time)) + 0)) +(define (report-prime elapsed-time) + (display " *** ") + (display elapsed-time) + 1) + +(define (find-three-primes starting-num) + (define (loop num primes-found) + (if (= primes-found 3) true + (loop (+ num 2) (+ primes-found (timed-prime-test num))))) + (newline) + (loop (+ 1 starting-num) 0)) + +(find-three-primes 1000) +(find-three-primes 10000) +(find-three-primes 100000) +(find-three-primes 1000000) +
bmabey/sicp-study
727b96a721012999b2cd5096ff4b87e4816afea0
that was interesting but kinda busywork IMO.. exercise 1.20
diff --git a/scheme/week02/ex1_20.scm b/scheme/week02/ex1_20.scm new file mode 100644 index 0000000..a6f9afc --- /dev/null +++ b/scheme/week02/ex1_20.scm @@ -0,0 +1,66 @@ +; Exercise 1.20 +; +(define (gcd a b) + (if (= b 0) + a + (gcd b (remainder a b)))) + +;; The process that a procedure generates is of course dependent on the rules used by the +;; interpreter. As an example, consider the iterative gcd procedure given above. Suppose we were to +;; interpret this procedure using normal-order evaluation, as discussed in section 1.1.5. (The +;; normal-order-evaluation rule for if is described in exercise 1.5.) Using the substitution method (for +;; normal order), illustrate the process generated in evaluating (gcd 206 40) and indicate the +;; remainder operations that are actually performed. How many remainder operations are actually +;; performed in the normal-order evaluation of (gcd 206 40)? In the applicative-order evaluation? + + +; normal-order: +(if (= b 0) a (gcd b (r a b))) +(gcd 206 40) +(if (= 40 0) 206 (gcd 40 (r 206 40))) +(gcd 40 (r 206 40)) +(if (= (r 206 40) 0) 40 (gcd (r 206 40) (r 40 (r 206 40)))) +(if (= 6 0) 40 (gcd (r 206 40) (r 40 (r 206 40)))) ; 1 +(gcd (r 206 40) (r 40 (r 206 40))) +(if (= (r 40 (r 206 40)) 0) (r 206 40) (gcd (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))) +(if (= (r 40 6) 0) (r 206 40) (gcd (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))) ; 2 +(if (= 4 0) (r 206 40) (gcd (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))) ; 3 +(gcd (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) +(if (= (r (r 206 40) (r 40 (r 206 40))) 0) (r 40 (r 206 40)) (gcd (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))))) +(if (= (r (r 206 40) (r 40 6)) 0) (r 40 (r 206 40)) (gcd (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))))) ; 4 +(if (= (r (r 206 40) 4) 0) (r 40 (r 206 40)) (gcd (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))))) ; 5 +(if (= (r 6 4) 0) (r 40 (r 206 40)) (gcd (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))))) ; 6 +(if (= 2 0) (r 40 (r 206 40)) (gcd (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))))) ; 7 +(gcd (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))) +(if (= (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) 0) (r (r 206 40) (r 40 (r 206 40))) (gcd (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) (r (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))))) + +(if (= (r (r 40 (r 206 40)) (r (r 206 40) (r 40 6))) 0) (r (r 206 40) (r 40 (r 206 40))) (gcd (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) (r (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))))) ; 8 +(if (= (r (r 40 (r 206 40)) (r (r 206 40) 4)) 0) (r (r 206 40) (r 40 (r 206 40))) (gcd (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) (r (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))))) ; 9 +(if (= (r (r 40 (r 206 40)) (r 6 4)) 0) (r (r 206 40) (r 40 (r 206 40))) (gcd (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) (r (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))))) ; 10 +(if (= (r (r 40 (r 206 40)) 2) 0) (r (r 206 40) (r 40 (r 206 40))) (gcd (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) (r (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))))) ; 11 +(if (= (r (r 40 6) 2) 0) (r (r 206 40) (r 40 (r 206 40))) (gcd (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) (r (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))))) ; 12 +(if (= (r 4 2) 0) (r (r 206 40) (r 40 (r 206 40))) (gcd (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) (r (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))))) ; 13 +(if (= 0 0) (r (r 206 40) (r 40 (r 206 40))) (gcd (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) (r (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))))) ; 14 +(if (= 0 0) (r (r 206 40) (r 40 6)) (gcd (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) (r (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))))) ; 15 +(if (= 0 0) (r (r 206 40) 4) (gcd (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) (r (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))))) ; 16 +(if (= 0 0) (r 6 4) (gcd (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) (r (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))))) ; 17 +(if (= 0 0) 2 (gcd (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) (r (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))))) ; 18 +; remainder (r) was evaluated 18 times before the answer 2 was returned. Every single call to remainder, but one, was repeated. + +; Applicative-order with the special-form of if. +(if (= b 0) a (gcd b (r a b))) +(gcd 206 40) +(if (= 40 0) 206 (gcd 40 (r 206 40))) +(if (= 40 0) 206 (gcd 40 6)) ; 1 +(gcd 40 6) +(if (= 6 0) 40 (gcd 6 (r 40 6))) +(if (= 6 0) 40 (gcd 6 4)) ; 2 +(gcd 6 4) +(if (= 4 0) 6 (gcd 4 (r 6 4))) +(if (= 4 0) 6 (gcd 4 2)) ; 3 +(gcd 4 2) +(if (= 2 0) 4 (gcd 2 (r 4 2))) +(if (= 2 0) 4 (gcd 2 0)) ; 4 +(gcd 2 0) +(if (= 0 0) 2 (gcd 0 (r 2 0))) ; --> 2 +; remainder (r) was evaluated 4 times before the answer 2 was returned.
bmabey/sicp-study
2222656ea16814baab2b694f57a857ee98b8d01c
ignore latex produced files
diff --git a/.gitignore b/.gitignore index 1aac70f..901ee16 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,8 @@ sicp.pdf lecture_videos *.sw? *.*~ +*.dvi +*.aux +*.log +*.pdf
bmabey/sicp-study
7055441e06a9b7cf9c081e0de9869137e38ae72f
my alegebra for exercise 1.19
diff --git a/scheme/week02/ex1_19.scm b/scheme/week02/ex1_19.scm index 160e36d..7001c34 100644 --- a/scheme/week02/ex1_19.scm +++ b/scheme/week02/ex1_19.scm @@ -1,46 +1,46 @@ #lang scheme/base (require (planet schematics/schemeunit:3)) ; SICP Exercise 1.19 -; Did algebra on paper... +; My alegraba for this problem can be found in ex1_19.tex. I should really look into SLaTeX... (define (fib-tree-recusive-process n) (cond ((= n 0) 0) ((= n 1) 1) (else (+ (fib-tree-recusive-process (- n 1)) (fib-tree-recusive-process (- n 2)))))) (define (fib-iterative-process n) (define (fib-iter a b count) (if (= count 0) b (fib-iter (+ a b) a (- count 1)))) (fib-iter 1 0 n)) (define (square x) (* x x)) (define (fib-log n) (define (fib-iter a b p q count) (cond ((= count 0) b) ((even? count) (fib-iter a b (+ (square p) (square q)) ; compute p' (+ (* 2 p q) (square q)) ; compute q' (/ count 2))) (else (fib-iter (+ (* b q) (* a q) (* a p)) (+ (* b p) (* a q)) p q (- count 1))))) (fib-iter 1 0 0 1 n)) (check-eq? (fib-tree-recusive-process 8) 21) (check-eq? (fib-iterative-process 8) 21) (check-eq? (fib-log 8) 21) (check-eq? (fib-log 20) 6765) diff --git a/scheme/week02/ex1_19.tex b/scheme/week02/ex1_19.tex new file mode 100644 index 0000000..f99a614 --- /dev/null +++ b/scheme/week02/ex1_19.tex @@ -0,0 +1,68 @@ +\documentclass[a4paper,12pt]{article} +\begin{document} +\section*{SICP Exercise 1.9} + +\subsection*{Question} +There is a clever algorithm for computing the Fibonacci numbers in a logarithmic +number of steps. Recall the transformation of the state variables $a$ and $b$ in the fib-iter process of +section 1.2.2: $a \leftarrow a + b$ and $b \leftarrow a$. Call this transformation $T$, and observe that applying $T$ over and over +again $n$ times, starting with $1$ and $0$, produces the pair $Fib(n + 1)$ and $Fib(n)$. In other words, the +Fibonacci numbers are produced by applying $T^n$, the $n$th power of the transformation $T$, starting with the +pair $(1,0)$. Now consider $T$ to be the special case of $p = 0$ and $q = 1$ in a family of transformations $T_{pq}$, +where $T_{pq}$ transforms the pair $(a,b)$ according to $a \leftarrow bq + aq + ap$ and $b \leftarrow bp + aq$. Show that if we +apply such a transformation $T_pq$ twice, the effect is the same as using a single transformation $T_{p'q'}$ of the +same form, and compute $p'$ and $q'$ in terms of $p$ and $q$. This gives us an explicit way to square these +transformations, and thus we can compute $T^n$ using successive squaring, as in the fast-expt +procedure. + +\subsection*{Answer} + +We have $T_{pq}$ defined as: +\begin{eqnarray*} +a' & = & bq + aq + ap \\ +b' & = & bp + aq +\end{eqnarray*} + +We are asked to find $p'$ and $q'$ such that $T_{p'q'} = T^2_{pq} $. In other words we want to find $p'$ and $q'$ such that: +\begin{eqnarray} +a'' & = & bq' + aq' + ap' \\ +b'' & = & bp' + aq' +\end{eqnarray} + +To do this we start by expanding $T_{pq}$ into itself as if we are solving for $a''$ and $b''$: +\begin{eqnarray*} +a'' & = & b'q + a'q + a'p \\ +a'' & = & (bp + aq)q + (bq + aq + ap)q + (bq + aq + ap)p \\ +b'' & = & b'p + a'q \\ +b'' & = & (bp + aq)p + (bq + aq + ap)q +\end{eqnarray*} + +The goal then is to manipulate $a''$ and $b''$ to be in the form of equations 1 and 2 so we can solve for $p'$ and $q'$. Starting with the easier of the two equations ($b''$): +\begin{eqnarray*} +b'' & = & (bp + aq)p + (bq + aq + ap)q \\ +b'' & = & bp^2 + apq + bq^2 + aq^2 + apq \\ +b'' & = & b(p^2 + q^2) + a(2pq + q^2) \\ +{therefore} \\ +p' & = & p^2 + q^2 \\ +q' & = & 2pq + q^2 +\end{eqnarray*} + +We do the same for $a''$ to ensure the discoverd $p'$ and $q'$ solve it as well: +\begin{eqnarray*} +a'' & = & b'q + a'q + a'p \\ +a'' & = & (bp + aq)q + (bq + aq + ap)q + (bq + aq + ap)p \\ +a'' & = & bpq + aq^2 + bq^2 + aq^2 + apq + bpq + apq + ap^2 \\ +a'' & = & 2bpq + aq^2 + bq^2 + aq^2 + 2apq + ap^2 \\ +a'' & = & b(2pq + q^2) + a(2pq + q^2) + a(p^2 + q^2) +\end{eqnarray*} + +Both $a''$ and $b''$ were solvable with the same $p'$ and $q'$ so we have our answer to plug into the given procedure: +\begin{eqnarray*} +p' & = & p^2 + q^2 \\ +q' & = & 2pq + q^2 +\end{eqnarray*} + +\end{document} + + +
bmabey/sicp-study
729bdc73b20b4d1b7a5f1b57bd1124270c759712
exercise 1.19
diff --git a/scheme/week02/ex1_19.scm b/scheme/week02/ex1_19.scm new file mode 100644 index 0000000..160e36d --- /dev/null +++ b/scheme/week02/ex1_19.scm @@ -0,0 +1,46 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) + +; SICP Exercise 1.19 +; Did algebra on paper... + +(define (fib-tree-recusive-process n) + (cond ((= n 0) 0) + ((= n 1) 1) + (else + (+ (fib-tree-recusive-process (- n 1)) (fib-tree-recusive-process (- n 2)))))) + + +(define (fib-iterative-process n) + (define (fib-iter a b count) + (if (= count 0) + b + (fib-iter (+ a b) a (- count 1)))) + + (fib-iter 1 0 n)) + +(define (square x) (* x x)) + +(define (fib-log n) + (define (fib-iter a b p q count) + (cond ((= count 0) b) + ((even? count) + (fib-iter + a + b + (+ (square p) (square q)) ; compute p' + (+ (* 2 p q) (square q)) ; compute q' + (/ count 2))) + (else (fib-iter (+ (* b q) (* a q) (* a p)) + (+ (* b p) (* a q)) + p + q + (- count 1))))) + (fib-iter 1 0 0 1 n)) + + + +(check-eq? (fib-tree-recusive-process 8) 21) +(check-eq? (fib-iterative-process 8) 21) +(check-eq? (fib-log 8) 21) +(check-eq? (fib-log 20) 6765)
bmabey/sicp-study
4197e56be145963c8b7f272b37145caa290df4af
exercise 1.16
diff --git a/ruby/ex1_16.rb b/ruby/ex1_16.rb new file mode 100644 index 0000000..fbc0709 --- /dev/null +++ b/ruby/ex1_16.rb @@ -0,0 +1,56 @@ + +def exp_recur(b, n) + if n == 0 + 1 + elsif n.even? + exp_recur(b, n / 2).square + else + b * exp_recur(b, n - 1) + end +end + +def exp_iter_slow(b, n) + product = b + n -= 1 + while n > 0 + product *= b + n -= 1 + end + product +end + +def exp_iter_fast(b, n) + product = 1 + until n == 0 + if n.even? + n = n / 2 + b = b * b + else + product = b * product + n -= 1 + end + end + product +end + + +class Fixnum + + def even? + self % 2 == 0 + end + + def zero? + self == 0 + end + + def odd? + !even? + end + + def square + self * self + end + +end + diff --git a/scheme/week02/ex1_16.scm b/scheme/week02/ex1_16.scm new file mode 100644 index 0000000..ae19110 --- /dev/null +++ b/scheme/week02/ex1_16.scm @@ -0,0 +1,34 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) + +(define (even? n) + (= (remainder n 2) 0)) + +(define (square x) + (* x x)) + +; recursive process +(define (fast-expt-recur b n) + (cond ((= n 0) 1) + ((even? n) (square (fast-expt-recur b (/ n 2)))) + (else (* b (fast-expt-recur b (- n 1)))))) + +; iterative process +(define (fast-expt b n) + (define (fast-expt-incr b n a) + (cond ((zero? n) a ) + ((even? n) (fast-expt-incr (square b) (/ n 2) a)) + (else (fast-expt-incr b (- n 1) (* b a))))) + (fast-expt-incr b n 1)) + +(check-eq? (fast-expt-recur 0 23) 0) +(check-eq? (fast-expt-recur 1 23) 1) +(check-eq? (fast-expt-recur 2 2) 4) +(check-eq? (fast-expt-recur 2 8) 256) +(check-eq? (fast-expt-recur 3 7) 2187) + +(check-eq? (fast-expt 0 23) 0) +(check-eq? (fast-expt 1 23) 1) +(check-eq? (fast-expt 2 2) 4) +(check-eq? (fast-expt 2 8) 256) +(check-eq? (fast-expt 3 7) 2187)
bmabey/sicp-study
ee526b6ea941379fdf57ef3514a68e39a058e5dc
exercise 1.11
diff --git a/scheme/week02/ex1_11.scm b/scheme/week02/ex1_11.scm new file mode 100644 index 0000000..6ee41f9 --- /dev/null +++ b/scheme/week02/ex1_11.scm @@ -0,0 +1,30 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) + +; recursive process +(define (f n) + (if (< n 3) + n + (+ (f (- n 1)) (* 2 (f (- n 2))) (* 3 (f (- n 3)))))) + +; iterative process +(define (fi n) + (define (f-iter x y z max-count) + (if (= max-count 0) + z + (f-iter (+ x (* 2 y) (* 3 z)) x y (- max-count 1)))) + + (f-iter 2 1 0 n) + ) + +(check-eq? (f 2) 2) +(check-eq? (f 3) 4) +(check-eq? (f 4) 11) + +(check-eq? (fi 2) 2) +(check-eq? (fi 3) 4) +(check-eq? (fi 4) 11) +(check-eq? (fi 20) (f 20)) + + +
bmabey/sicp-study
e0a6a950a61fdecd6e20ad2d97b4584ed9db0695
exercise 1.9
diff --git a/scheme/week02/ex1_09.scm b/scheme/week02/ex1_09.scm new file mode 100644 index 0000000..4f9bbc0 --- /dev/null +++ b/scheme/week02/ex1_09.scm @@ -0,0 +1,41 @@ +;; SICP 1.9 + +;; Exercise 1.9. Each of the following two procedures defines a +;; method for adding two positive integers in terms of the procedures +;; inc, which increments its argument by 1, and dec, which decrements +;; its argument by 1. + +(define (+ a b) + (if (= a 0) + b + (inc (+ (dec a) b)))) + +; (+ 4 5) +; (inc (+ 3 5)) +; (inc (inc (+ 2 5))) +; (inc (inc (inc (+ 1 5)))) +; (inc (inc (inc (inc (+ 0 5))))) +; (inc (inc (inc (inc 5)))) +; (inc (inc (inc 6))) +; (inc (inc 7)) +; (inc 8) +; 9 + +; The above solution is a linear recursive process because it builds of a chain +; of deferred operations which grows linearly with the supplied 'a' variable. + +(define (+ a b) + (if (= a 0) + b + (+ (dec a) (inc b)))) + +; (+ 4 5) +; (+ 3 6) +; (+ 2 7) +; (+ 1 8) +; (+ 0 9) +; 9 + +; This solution is a recursive *procedure* but an iterative *process* due +; to the fact that the state of the proccess is always encoded in 'a' and 'b'. +
bmabey/sicp-study
786ddb396e851f90d67fe3782ce5429d49cabc9a
using schemeunit on 1.3
diff --git a/scheme/week01/ex1_3.scm b/scheme/week01/ex1_3.scm index fcea633..d3f80ae 100644 --- a/scheme/week01/ex1_3.scm +++ b/scheme/week01/ex1_3.scm @@ -1,30 +1,30 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) + ;; SICP 1.3 ;; Exercise 1.3. Define a procedure that takes three numbers as ;; arguments and returns the sum of the squares of the two larger ;; numbers. -(define (square x) (* x x)) -(define (squared-sum x y) - (+ (square x) (square y)) - ) (define (squared-sum-of-two-greatest x y z) + (define (square x) (* x x)) + (define (squared-sum x y) + (+ (square x) (square y)) + ) (if (> x y) (if (> y z) (squared-sum x y) (squared-sum x z) ) (if (> x z) (squared-sum y x) (squared-sum y z) ) ) ) -(squared-sum-of-two-greatest 2 1 3) -; # => 13 -(squared-sum-of-two-greatest 5 5 9) -; # => 106 -(squared-sum-of-two-greatest 1 3 4) -; # => 25 +(check-eq? (squared-sum-of-two-greatest 2 1 3) 13) +(check-eq? (squared-sum-of-two-greatest 5 5 9) 106) +(check-eq? (squared-sum-of-two-greatest 1 3 4) 25)
bmabey/sicp-study
d17478682607ef7d565a974dfa6acf9ef57273c4
scheme unit example from intro page
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1aac70f --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +sicp.pdf +lecture_videos +*.sw? +*.*~ diff --git a/README.textile b/README.textile new file mode 100644 index 0000000..74241b1 --- /dev/null +++ b/README.textile @@ -0,0 +1,5 @@ +h1. Worked Examples for SICP + +This is my worked examples for the "SICP book":http://mitpress.mit.edu/sicp/full-text/book/book.html. The work is divided up into weekly studies, based around the "video lectures":http://www.archive.org/details/mit_ocw_sicp. I am doing this in conjuction with the "Wizard Book Study Group":http://groups.google.com/group/wizardbookstudy?hl=en. + +My goal is to work the exercises in Scheme and then try to do them in Clojure. Since I am pretty new to both langauges I may have to focus just on Scheme. We'll see how it goes. :) diff --git a/clojure/week01/ex1_3.clj b/clojure/week01/ex1_3.clj new file mode 100644 index 0000000..4356da1 --- /dev/null +++ b/clojure/week01/ex1_3.clj @@ -0,0 +1,25 @@ +(defn square [x] (* x x)) + +(defn squared-sum [x y] + (+ (square x) (square y)) +) + +(defn squared-sum-of-two-greatest [x y z] + (if (> x y) + (if (> y z) + (squared-sum x y) + (squared-sum x z) + ) + (if (> x z) + (squared-sum y x) + (squared-sum y z) + ) + ) +) + +(squared-sum-of-two-greatest 2 1 3) +; # => 13 +(squared-sum-of-two-greatest 5 5 9) +; # => 106 +(squared-sum-of-two-greatest 1 3 4) +; # => 25 diff --git a/clojure/week01/ex1_7.clj b/clojure/week01/ex1_7.clj new file mode 100644 index 0000000..95de373 --- /dev/null +++ b/clojure/week01/ex1_7.clj @@ -0,0 +1,33 @@ +(defn square [x] + (* x x)) + +(defn abs [x] + (if (< x 0) (- x) x)) + +(defn average [numbers] + (/ (apply + numbers) (count numbers))) + +(defn within-delta? [x y delta] + (<= (abs (- x y)) delta)) + +(defn sqrt [x] + (let [improve (fn [guess x] + (average (list guess (/ x guess)))) + sqrt-iter (fn [old-guess guess x] + (if (within-delta? old-guess guess 0.000001) + guess + (recur guess (improve guess x) x) + ))] + (sqrt-iter 0.0 1.0 x))) + +(sqrt 9) + +(sqrt (+ 100 37)) + +(sqrt (+ (sqrt 2) (sqrt 3))) + +(square (sqrt 1000)) + +(sqrt 0.005) +(sqrt 123456789012345678901234567890) + diff --git a/clojure/week01/ex1_8.clj b/clojure/week01/ex1_8.clj new file mode 100644 index 0000000..174133d --- /dev/null +++ b/clojure/week01/ex1_8.clj @@ -0,0 +1,33 @@ +; Newton's Method for finding Cube Root, using the approach in 1.7. +(ns sicpstudy.week01 (:use clojure.contrib.test-is)) + +(defn square [x] + (* x x)) + +(defn abs [x] + (if (< x 0) (- x) x)) + +(defn within-delta? [x y delta] + (<= (abs (- x y)) delta)) + +(defn cbrt [x] + (let [improve (fn [guess x] + (/ (+ (/ x (square guess)) (* 2 guess)) 3)) + cbrt-iter (fn [old-guess guess x] + (if (within-delta? old-guess guess 0.000001) + guess + (recur guess (improve guess x) x) + ))] + (cbrt-iter 0.0 1.0 x))) + +(cbrt 27) +(cbrt 8E15) +(cbrt 8E-15) + + +(deftest test-cbrt + (is (within-delta? (cbrt 8E15) 2E5 0.000001)) + (is (within-delta? (cbrt 8E-15) 2E-5 0.000001)) + (is (within-delta? (cbrt 27) 3.0 0.000001))) + +(run-tests) diff --git a/clojure/week01/sqrt_from_book.clj b/clojure/week01/sqrt_from_book.clj new file mode 100644 index 0000000..e1f1419 --- /dev/null +++ b/clojure/week01/sqrt_from_book.clj @@ -0,0 +1,32 @@ +; This is my direct translation of the sqrt procedure from SICP 1.1.7 into Clojure + +(defn square [x] + (* x x)) + + +(defn abs [x] + (if (< x 0) (- x) x)) + +(defn average [x y] + (/ (+ x y) 2)) + +(defn improve [guess x] + (average guess (/ x guess))) + +(defn good-enough? [guess x] + (< (abs (- (square guess) x)) 0.001)) + +(defn sqrt-iter [guess x] + (if (good-enough? guess x) + guess + (sqrt-iter (improve guess x) x) + )) + +(defn sqrt [x] + (sqrt-iter 1.0 x)) + +(sqrt 9) +(sqrt (+ 100 37)) +(sqrt (+ (sqrt 2) (sqrt 3))) +(square (sqrt 1000)) + diff --git a/scheme/scheme-unit-example/file-test.scm b/scheme/scheme-unit-example/file-test.scm new file mode 100644 index 0000000..f84c7b1 --- /dev/null +++ b/scheme/scheme-unit-example/file-test.scm @@ -0,0 +1,6 @@ + #lang scheme/base +(require (planet schematics/schemeunit:3) + "file.scm") + +(check-equal? (my-+ 1 1) 2 "Simple addition") +(check-equal? (my-* 1 2) 2 "Simple multiplication") diff --git a/scheme/scheme-unit-example/file.scm b/scheme/scheme-unit-example/file.scm new file mode 100644 index 0000000..a1f0b9a --- /dev/null +++ b/scheme/scheme-unit-example/file.scm @@ -0,0 +1,14 @@ + #lang scheme/base + + (define (my-+ a b) + (if (zero? a) + b + (my-+ (sub1 a) (add1 b)))) + + (define (my-* a b) + (if (zero? a) + b + (my-* (sub1 a) (my-+ b b)))) + + (provide my-+ + my-*) diff --git a/scheme/week01/ex1_1.scm b/scheme/week01/ex1_1.scm new file mode 100644 index 0000000..1c6e73b --- /dev/null +++ b/scheme/week01/ex1_1.scm @@ -0,0 +1,35 @@ +; Exercise 1.1. Below is a sequence of expressions. What is the result printed by the interpreter in +; response to each expression? Assume that the sequence is to be evaluated in the order in which it is +; presented. + +10 +; => 10 +(+ 5 3 4) +; => 12 +(- 9 1) +; => 8 +(/ 6 2) +; => 3 +(+ (* 2 4) (- 4 6)) +; => 6 +(define a 3) +(define b (+ a 1)) +(+ a b (* a b)) +; => 19 +(= a b) +; => false +(if (and (> b a) (< b (* a b))) + b + a) +; => 4 (b) +(cond ((= a 4) 6) + ((= b 4) (+ 6 7 a)) + (else 25)) +; => 16 +(+ 2 (if (> b a) b a)) +; => 6 +(* (cond ((> a b) a) + ((< a b) b) + (else -1)) + (+ a 1)) +; => 16 diff --git a/scheme/week01/ex1_2.scm b/scheme/week01/ex1_2.scm new file mode 100644 index 0000000..ff083a5 --- /dev/null +++ b/scheme/week01/ex1_2.scm @@ -0,0 +1,5 @@ +; Translate the following expression into prefix form http://mitpress.mit.edu/sicp/full-text/book/ch1-Z-G-3.gif +; The gif is horrible quality.. so some integers may be wrong.... + +(/ (+ 5 4 (- 2 (- 3 (+ 6 (/ 4 5))))) + (* 3 (- 6 2) (- 2 7))) diff --git a/scheme/week01/ex1_3.scm b/scheme/week01/ex1_3.scm new file mode 100644 index 0000000..fcea633 --- /dev/null +++ b/scheme/week01/ex1_3.scm @@ -0,0 +1,30 @@ +;; SICP 1.3 + +;; Exercise 1.3. Define a procedure that takes three numbers as +;; arguments and returns the sum of the squares of the two larger +;; numbers. + +(define (square x) (* x x)) +(define (squared-sum x y) + (+ (square x) (square y)) + ) + +(define (squared-sum-of-two-greatest x y z) + (if (> x y) + (if (> y z) + (squared-sum x y) + (squared-sum x z) + ) + (if (> x z) + (squared-sum y x) + (squared-sum y z) + ) + ) + ) + +(squared-sum-of-two-greatest 2 1 3) +; # => 13 +(squared-sum-of-two-greatest 5 5 9) +; # => 106 +(squared-sum-of-two-greatest 1 3 4) +; # => 25 diff --git a/scheme/week01/ex1_4.scm b/scheme/week01/ex1_4.scm new file mode 100644 index 0000000..e9e3ed6 --- /dev/null +++ b/scheme/week01/ex1_4.scm @@ -0,0 +1,17 @@ +;; SICP 1.4 + +;; Exercise 1.4. Observe that our model of evaluation allows for +;; combinations whose operators are compound expressions. Use this +;; observation to describe the behavior of the following procedure: + +(define (a-plus-abs-b a b) + ((if (> b 0) + -) a b)) + + +; The behaviour of interest in this code sample is when the if procedure +; is evaluated it returns an operator which is then applied to the +; remaining elemetns of the list. This is interesting to me because of the +; implicit application of the operator (- or +). Since the if procedure is +; evalutaed and expanded out first it reduces to: +; (+ a b) ; | b > 0 +; (- a b) ; | b <= 0 diff --git a/scheme/week01/ex1_5.scm b/scheme/week01/ex1_5.scm new file mode 100644 index 0000000..91e3635 --- /dev/null +++ b/scheme/week01/ex1_5.scm @@ -0,0 +1,26 @@ +;; SICP Exercise 1.5 +;; Ben Bitdiddle has invented a test to determine whether the interpreter he is faced with is +;; using applicative-order evaluation or normal-order evaluation. He defines the following two procedures: +(define (p) (p)) +(define (test x y) + (if (= x 0) + 0 + y)) +;; Then he evaluates the expression +; (test 0 (p)) + +;; What behavior will Ben observe with an interpreter that uses applicative-order evaluation? What +;; behavior will he observe with an interpreter that uses normal-order evaluation? Explain your answer. +;; (Assume that the evaluation rule for the special form if is the same whether the interpreter is using +;; normal or applicative order: The predicate expression is evaluated first, and the result determines +;; whether to evaluate the consequent or the alternative expression.) +;; **** +;; +;; When an interpreter uses applicative-order evaluation the operands are evaluated along with the operators +;; *before* the procedure is applied. This means that the 'p' procedure is ran when the interpreter evaluates +;; (p) before it applies the test procedure. When 'p' is called then the interpreter enters an endless loop +;; as it recursively calls 'p'. +;; +;; With normal-order evaluation the operands are lazily evaluated, meaning evaluation is delayed until the +;; called procedure requires them. In the case where the above code is interpreted normal-order then 0 will +;; be returned when x = 0. diff --git a/scheme/week01/ex1_6.scm b/scheme/week01/ex1_6.scm new file mode 100644 index 0000000..c125b5c --- /dev/null +++ b/scheme/week01/ex1_6.scm @@ -0,0 +1,30 @@ +;; Exercise 1.6. +;; Alyssa P. Hacker doesn't see why if needs to be provided as a special form. ``Why can't I +;; just define it as an ordinary procedure in terms of cond?'' she asks. Alyssa's friend Eva Lu Ator claims +;; this can indeed be done, and she defines a new version of if: +(define (new-if predicate then-clause else-clause) + (cond (predicate then-clause) + (else else-clause))) +;; Eva demonstrates the program for Alyssa: +(new-if (= 2 3) 0 5) +5 +(new-if (= 1 1) 0 5) +0 +;; Delighted, Alyssa uses new-if to rewrite the square-root program: +(define (sqrt-iter guess x) + (new-if (good-enough? guess x) + guess + (sqrt-iter (improve guess x) + x))) +;; What happens when Alyssa attempts to use this to compute square roots? Explain. + + +; When Alyssa attempts to use this new-if in sqrt-iter then an endless loop will ensue. +; This is explained by applicative-order evaluation done by the interpreter, meaning the +; else-clause will always be evaluated no matter what the predicate is. +; +; This exercise puzzled me for a minute because we know the 'if' procedure works fine. The +; answer to this puzzle was in section 1.1.6. 'cond' and 'if' are *special forms* and are +; evaluated differently than regular forms. An if statement behaves just as you expect +; it would - it delays evaluation of any of the clauses until the predicate dictates that +; it is the appropriate clause to evaluate and return it's value. diff --git a/scheme/week01/ex1_7.scm b/scheme/week01/ex1_7.scm new file mode 100644 index 0000000..2e85b86 --- /dev/null +++ b/scheme/week01/ex1_7.scm @@ -0,0 +1,55 @@ +;; Exercise 1.7. +;; The good-enough? test used in computing square roots will not be very effective for +;; finding the square roots of very small numbers. Also, in real computers, arithmetic operations are almost +;; always performed with limited precision. This makes our test inadequate for very large numbers. Explain +;; these statements, with examples showing how the test fails for small and large numbers. An alternative +;; strategy for implementing good-enough? is to watch how guess changes from one iteration to the +;; next and to stop when the change is a very small fraction of the guess. Design a square-root procedure +;; that uses this kind of end test. Does this work better for small and large numbers? + +; The problem with the good-enough? procedure for small numbers is that there radicant is much smaller than +; the 0.001 hardcoded threshold. The logic prevents the improvement of the guess past this threshold. +; For example, the square-root of 0.005 is ~0.007110678 but the computed value with the 0.001 threshold +; is 0.031781009679092864 since the logic prevents any further improvements. +; +; The problem with large numbers is you enter an endless loop as the program is unable to improve the guess +; any further. An example of this is (sqrt 123456789012345678901234567890). At some point the value of the guess +; becomes 4.4351364182882e16 and the improve guess continues to return the same value unable to improve it. As +; the question alluded to math on computers is done with limited precision. This fact is evident as the floating +; point value guess is not changed with subsequent applications of improve on it and the original number. +; +; Below is my implementation of the proposed solution. Instead of having a good-enough? function I introduced a +; within-delta? function that sqrt-iter used to compare old and current guesses. To enable this state to be carried +; by all the recursive calls I added it as an argument to the sqrt-iter. With this solution small and large numbers +; are computed correctly. + +(define (square x) + (* x x)) + +(define (average numbers) + (/ (apply + numbers) (length numbers))) + +(define (within-delta? x y delta) + (<= (abs (- x y)) delta)) + +(define (sqrt x) + (define (improve guess x) + (average (list guess (/ x guess)))) + (define (sqrt-iter old-guess guess x) + (if (within-delta? old-guess guess 0.000001) + guess + (sqrt-iter guess (improve guess x) + x))) + + (sqrt-iter 0.0 1.0 x)) + +(sqrt 9) + +(sqrt (+ 100 37)) + +(sqrt (+ (sqrt 2) (sqrt 3))) + +(square (sqrt 1000)) + +(sqrt 0.005) +(sqrt 123456789012345678901234567890) diff --git a/scheme/week01/ex1_8.scm b/scheme/week01/ex1_8.scm new file mode 100644 index 0000000..c69816f --- /dev/null +++ b/scheme/week01/ex1_8.scm @@ -0,0 +1,33 @@ +#lang scheme/base +(require (planet schematics/schemeunit:3)) + +;; Exercise 1.8. Newton's method for cube roots is based on the fact that if y is an approximation to the +;; cube root of x, then a better approximation is given by the value +;; ((x / y^2) + 2y) / 3 +;; Use this formula to implement a cube-root procedure analogous to the square-root procedure. (In +;; section 1.3.4 we will see how to implement Newton's method in general as an abstraction of these +;; square-root and cube-root procedures.) + + + +; square and within-delta? seem reasonably helpful/general so I'm not boxing them in to cbrt +(define (square x) + (* x x)) + +(define (within-delta? x y delta) + (<= (abs (- x y)) delta)) + +(define (cbrt x) + (define (improve guess x) + (/ (+ (/ x (square guess)) (* 2 guess)) 3)) + (define (cbrt-iter old-guess guess x) + (if (within-delta? old-guess guess 0.000001) + guess + (cbrt-iter guess (improve guess x) + x))) + + (cbrt-iter 0.0 1.0 x)) + +(check-= (cbrt 27) 3.0 0.000001) +(check-= (cbrt 8E-15) 2E-5 1.0) +(check-= (cbrt 8E15) 2E5 1.0) diff --git a/scheme/week01/sqrt.scm b/scheme/week01/sqrt.scm new file mode 100644 index 0000000..c8a877b --- /dev/null +++ b/scheme/week01/sqrt.scm @@ -0,0 +1,28 @@ +(define (square x) + (* x x)) + +(define (average x y) + (/ (+ x y) 2)) + +(define (improve guess x) + (average guess (/ x guess))) + +(define (good-enough? guess x) + (< (abs (- (square guess) x)) 0.001)) + +(define (sqrt-iter guess x) + (if (good-enough? guess x) + guess + (sqrt-iter (improve guess x) + x))) + +(define (sqrt x) + (sqrt-iter 1.0 x)) + +(sqrt 9) + +(sqrt (+ 100 37)) + +(sqrt (+ (sqrt 2) (sqrt 3))) + +(square (sqrt 1000))
inorton/xrhash
908bd59c8a8ea51cb17fd277f8981f99d07892e8
add strings dict example
diff --git a/SConstruct b/SConstruct index ecf49d6..eb17ca1 100644 --- a/SConstruct +++ b/SConstruct @@ -1,7 +1,7 @@ import os env = Environment() env.Append(CFLAGS="-Wall -Werror") env.Append(CFLAGS="-g -O0") env.SConscript("src/lib/SConscript",exports="env"); - +env.SConscript("src/examples/SConscript",exports="env"); diff --git a/src/examples/SConscript b/src/examples/SConscript index 2ae852b..fcae505 100644 --- a/src/examples/SConscript +++ b/src/examples/SConscript @@ -1,3 +1,5 @@ Import("env"); -env.Program("spacemap.c",LIBS=["xrhash","ncurses"]) +env.Program("stringdict.c",LIBS=["xrhash"]) +# env.Program("spacemap.c",LIBS=["xrhash","ncurses"]) + diff --git a/src/examples/stringdict.c b/src/examples/stringdict.c new file mode 100644 index 0000000..083cb2a --- /dev/null +++ b/src/examples/stringdict.c @@ -0,0 +1,63 @@ +#include <xrhash.h> +#include <xrhash_fast.h> + +#include <stdio.h> +#include <string.h> + + +void free_dict( XRHash * dict ); + +int main( int argc, char** argv ){ + XRHash * dict = xr_init_hash( xr_hash__strhash, xr_hash__strcmp ); + + /* add things to the hash */ + + if ( xr_hash_contains( dict, "mary" ) != XRHASH_EXISTS_TRUE ) + printf("does not contain mary\n"); + + xr_hash_add( dict, "fred", strdup("my name is fred") ); + xr_hash_add( dict, "mary", strdup("my name is mary") ); + xr_hash_add( dict, "sally", strdup("my name is sally") ); + xr_hash_add( dict, "bob", strdup("my name is bob") ); + + if ( xr_hash_contains( dict, "mary" ) == XRHASH_EXISTS_TRUE ) + printf("does contain mary\n"); + + + /* iterate the hash */ + xrhash_fast_iterator * iter = xr_init_fasthashiterator( dict ); + + char * hashkey = NULL; + do { + hashkey = (char*) xr_hash_fastiteratekey( iter ); + if ( hashkey != NULL ){ + char * data; + xr_hash_get( dict, (void*)hashkey, (void**)&data ); + printf("key = %s, value = %s\n", hashkey, data ); + } else { + break; + } + } while ( 1 ); + xr_hash_fastiterator_free( iter ); + + free_dict( dict ); + + return 0; +} + +/* free the strdup'd strings we added at each item value */ +void free_dict( XRHash * dict ) { + XRHashIter * iter = xr_init_hashiterator( dict ); + void * k = NULL; + void * data = NULL; + while ( ( k = xr_hash_iteratekey( iter ) ) != NULL ) { + if ( xr_hash_get( dict, k, (void**)&data) == XRHASH_EXISTS_TRUE ){ + printf("free %s\n", (char*)k); + free ( data ); + } + } + free(iter); + xr_hash_free( dict ); +} + +
inorton/xrhash
f332e09e3b78042d76ca96fcecaf49765068ff8b
pkc-config fixed
diff --git a/configure.in b/configure.in index 03d6e33..4df04ff 100644 --- a/configure.in +++ b/configure.in @@ -1,36 +1,32 @@ # -*- Autoconf -*- # Process this file with autoconf to produce a configure script. AC_PREREQ([2.67]) -FULL-PACKAGE-NAME=libxrhash -VERSION=0.1 -BUG-REPORT-ADDRESS - -AC_INIT([FULL-PACKAGE-NAME], [VERSION], [BUG-REPORT-ADDRESS]) +AC_INIT([libxrhash], [0.1], [[email protected]]) AC_CONFIG_SRCDIR([src/lib/xrhash.c]) # Checks for programs. AC_PROG_CC AC_PROG_RANLIB # Checks for libraries. # Checks for header files. AC_CHECK_HEADERS([stdlib.h string.h sys/time.h unistd.h]) # Checks for typedefs, structures, and compiler characteristics. AC_C_INLINE AC_TYPE_SIZE_T # Checks for library functions. AC_FUNC_MALLOC AC_FUNC_REALLOC AC_CHECK_FUNCS([gettimeofday memset strdup]) AC_CONFIG_FILES([Makefile platform.make xrhash.pc src/lib/Makefile src/lib/tests/Makefile]) AC_OUTPUT diff --git a/xrhash.pc.in b/xrhash.pc.in index 772e10f..9732d42 100644 --- a/xrhash.pc.in +++ b/xrhash.pc.in @@ -1,12 +1,12 @@ prefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ -Name: libxrhash +Name: @PACKAGE_NAME@ Description: C Associative Array (Dictionary) URL: https://github.com/inorton/xrhash -Version: @VERSION@ +Version: @PACKAGE_VERSION@ Libs: -L${libdir} -lxrhash Cflags: -I${includedir} -I${includedir}/xrhash
inorton/xrhash
30bce757d0c3d717581aeacace6e03ff84a9d1e1
create include folder properly
diff --git a/src/lib/Makefile.in b/src/lib/Makefile.in index a2b6e98..3cd6733 100644 --- a/src/lib/Makefile.in +++ b/src/lib/Makefile.in @@ -1,41 +1,42 @@ ifeq ($(SRCROOT),) SRCROOT=${CURDIR} endif include ${SRCROOT}/platform.make OBJS=xrhash.o xrhash_fast.o HEADERS=xrhash.h xrhash_fast.h LIBNAME=xrhash LIBDIR=${libdir} INCLUDEDIR=${includedir} STATIC_TARGET=$(LIBPREFIX)$(LIBNAME).$(STATIC_SUFFIX) XRHASHLIB=${CURDIR}/$(STATIC_TARGET) export XRHASHLIB export SRCROOT CFLAGS+=-I${CURDIR} export CFLAGS all: $(STATIC_TARGET) clean: @rm -f $(OBJS) $(STATIC_TARGET) $(MAKE) -C tests clean test: $(STATIC_TARGET) $(MAKE) -e -C tests SRCROOT='${SRCROOT}' $(MAKE) -e -C tests test install: $(STATIC_TARGET) $(HEADERS) cp -f $(STATIC_TARGET) $(LIBDIR) + mkdir -p ${INCLUDEDIR}/xrhash cp -f $(HEADERS) ${INCLUDEDIR}/xrhash/. $(OBJS): $(HEADERS) $(STATIC_TARGET): $(OBJS) ar ru $@ $^ ranlib $@
inorton/xrhash
b5800b2c13c2f0603fa1271d7aa29ae2614bc7d6
more autotools and pkg-config stuff
diff --git a/Makefile.in b/Makefile.in index 49ac1ec..3406a2e 100644 --- a/Makefile.in +++ b/Makefile.in @@ -1,18 +1,25 @@ ifeq ($(SRCROOT),) SRCROOT=${CURDIR} endif include ${SRCROOT}/platform.make +PKGCONFIGDIR=${libdir}/pkgconfig + export SRCROOT -all: test +all: xrhash + +xrhash: $(MAKE) -C src/lib clean: $(MAKE) -C src/lib clean -test: +test: xrhash $(MAKE) -C src/lib test - +install: all + $(MAKE) -C src/lib install + cp -f xrhash.pc ${PKGCONFIGDIR}/. + cp -f src/lib/libxrhash.a ${LIBDIR}/. diff --git a/configure.in b/configure.in index 09d5fc0..03d6e33 100644 --- a/configure.in +++ b/configure.in @@ -1,29 +1,36 @@ # -*- Autoconf -*- # Process this file with autoconf to produce a configure script. AC_PREREQ([2.67]) + +FULL-PACKAGE-NAME=libxrhash +VERSION=0.1 +BUG-REPORT-ADDRESS + AC_INIT([FULL-PACKAGE-NAME], [VERSION], [BUG-REPORT-ADDRESS]) AC_CONFIG_SRCDIR([src/lib/xrhash.c]) # Checks for programs. AC_PROG_CC AC_PROG_RANLIB # Checks for libraries. # Checks for header files. AC_CHECK_HEADERS([stdlib.h string.h sys/time.h unistd.h]) # Checks for typedefs, structures, and compiler characteristics. AC_C_INLINE AC_TYPE_SIZE_T # Checks for library functions. AC_FUNC_MALLOC AC_FUNC_REALLOC AC_CHECK_FUNCS([gettimeofday memset strdup]) AC_CONFIG_FILES([Makefile + platform.make + xrhash.pc src/lib/Makefile src/lib/tests/Makefile]) AC_OUTPUT diff --git a/platform.make b/platform.make.in similarity index 65% rename from platform.make rename to platform.make.in index 516d798..4515c02 100644 --- a/platform.make +++ b/platform.make.in @@ -1,9 +1,14 @@ CFLAGS=$(XCFLAGS) -Wall -Werror LIBPREFIX=lib STATIC_SUFFIX=a DYNAMIC_SUFFIX=so +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +includedir=@includedir@ + export CFLAGS export LIBPREFIX export STATIC_SUFFIX export DYNAMIC_SUFFIX diff --git a/src/lib/Makefile.in b/src/lib/Makefile.in index 827f249..a2b6e98 100644 --- a/src/lib/Makefile.in +++ b/src/lib/Makefile.in @@ -1,33 +1,41 @@ ifeq ($(SRCROOT),) SRCROOT=${CURDIR} endif include ${SRCROOT}/platform.make OBJS=xrhash.o xrhash_fast.o +HEADERS=xrhash.h xrhash_fast.h LIBNAME=xrhash +LIBDIR=${libdir} +INCLUDEDIR=${includedir} STATIC_TARGET=$(LIBPREFIX)$(LIBNAME).$(STATIC_SUFFIX) XRHASHLIB=${CURDIR}/$(STATIC_TARGET) export XRHASHLIB export SRCROOT CFLAGS+=-I${CURDIR} export CFLAGS all: $(STATIC_TARGET) clean: @rm -f $(OBJS) $(STATIC_TARGET) $(MAKE) -C tests clean test: $(STATIC_TARGET) $(MAKE) -e -C tests SRCROOT='${SRCROOT}' $(MAKE) -e -C tests test +install: $(STATIC_TARGET) $(HEADERS) + cp -f $(STATIC_TARGET) $(LIBDIR) + cp -f $(HEADERS) ${INCLUDEDIR}/xrhash/. + +$(OBJS): $(HEADERS) $(STATIC_TARGET): $(OBJS) ar ru $@ $^ ranlib $@ diff --git a/xrhash.pc.in b/xrhash.pc.in new file mode 100644 index 0000000..772e10f --- /dev/null +++ b/xrhash.pc.in @@ -0,0 +1,12 @@ +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +includedir=@includedir@ + +Name: libxrhash +Description: C Associative Array (Dictionary) +URL: https://github.com/inorton/xrhash +Version: @VERSION@ +Libs: -L${libdir} -lxrhash +Cflags: -I${includedir} -I${includedir}/xrhash +
inorton/xrhash
62a33be67c14fa76815878727833c4abf178ee08
auto tools builds tests now
diff --git a/src/lib/Makefile b/src/lib/Makefile index 1979050..827f249 100644 --- a/src/lib/Makefile +++ b/src/lib/Makefile @@ -1,32 +1,33 @@ ifeq ($(SRCROOT),) SRCROOT=${CURDIR} endif include ${SRCROOT}/platform.make OBJS=xrhash.o xrhash_fast.o LIBNAME=xrhash STATIC_TARGET=$(LIBPREFIX)$(LIBNAME).$(STATIC_SUFFIX) XRHASHLIB=${CURDIR}/$(STATIC_TARGET) export XRHASHLIB export SRCROOT CFLAGS+=-I${CURDIR} export CFLAGS all: $(STATIC_TARGET) clean: @rm -f $(OBJS) $(STATIC_TARGET) $(MAKE) -C tests clean test: $(STATIC_TARGET) $(MAKE) -e -C tests SRCROOT='${SRCROOT}' + $(MAKE) -e -C tests test $(STATIC_TARGET): $(OBJS) ar ru $@ $^ ranlib $@ diff --git a/src/lib/Makefile.in b/src/lib/Makefile.in index 1979050..827f249 100644 --- a/src/lib/Makefile.in +++ b/src/lib/Makefile.in @@ -1,32 +1,33 @@ ifeq ($(SRCROOT),) SRCROOT=${CURDIR} endif include ${SRCROOT}/platform.make OBJS=xrhash.o xrhash_fast.o LIBNAME=xrhash STATIC_TARGET=$(LIBPREFIX)$(LIBNAME).$(STATIC_SUFFIX) XRHASHLIB=${CURDIR}/$(STATIC_TARGET) export XRHASHLIB export SRCROOT CFLAGS+=-I${CURDIR} export CFLAGS all: $(STATIC_TARGET) clean: @rm -f $(OBJS) $(STATIC_TARGET) $(MAKE) -C tests clean test: $(STATIC_TARGET) $(MAKE) -e -C tests SRCROOT='${SRCROOT}' + $(MAKE) -e -C tests test $(STATIC_TARGET): $(OBJS) ar ru $@ $^ ranlib $@ diff --git a/src/lib/tests/Makefile b/src/lib/tests/Makefile index 7e98524..12e47e2 100644 --- a/src/lib/tests/Makefile +++ b/src/lib/tests/Makefile @@ -1,13 +1,16 @@ include ${SRCROOT}/platform.make OBJS=testutils.o xrhash-test.o TARGET=xrhash-test LIBS=$(XRHASHLIB) all: $(TARGET) clean: - @rm -f $(OBJS) + @rm -f $(OBJS) $(TARGET) + +test: $(TARGET) + ./$(TARGET) $(TARGET): $(OBJS) $(XRHASHLIB) $(CC) -o $@ $^ diff --git a/src/lib/tests/Makefile.in b/src/lib/tests/Makefile.in index 7e98524..12e47e2 100644 --- a/src/lib/tests/Makefile.in +++ b/src/lib/tests/Makefile.in @@ -1,13 +1,16 @@ include ${SRCROOT}/platform.make OBJS=testutils.o xrhash-test.o TARGET=xrhash-test LIBS=$(XRHASHLIB) all: $(TARGET) clean: - @rm -f $(OBJS) + @rm -f $(OBJS) $(TARGET) + +test: $(TARGET) + ./$(TARGET) $(TARGET): $(OBJS) $(XRHASHLIB) $(CC) -o $@ $^
inorton/xrhash
25e4a1c1da94d65a4f71b6269839b5dedf4adda0
auto tools
diff --git a/Makefile.in b/Makefile.in new file mode 100644 index 0000000..49ac1ec --- /dev/null +++ b/Makefile.in @@ -0,0 +1,18 @@ +ifeq ($(SRCROOT),) + SRCROOT=${CURDIR} +endif + +include ${SRCROOT}/platform.make + +export SRCROOT + +all: test + $(MAKE) -C src/lib + +clean: + $(MAKE) -C src/lib clean + +test: + $(MAKE) -C src/lib test + + diff --git a/autogen.sh b/autogen.sh new file mode 100755 index 0000000..171a939 --- /dev/null +++ b/autogen.sh @@ -0,0 +1 @@ +autoconf diff --git a/configure.in b/configure.in new file mode 100644 index 0000000..09d5fc0 --- /dev/null +++ b/configure.in @@ -0,0 +1,29 @@ +# -*- Autoconf -*- +# Process this file with autoconf to produce a configure script. + +AC_PREREQ([2.67]) +AC_INIT([FULL-PACKAGE-NAME], [VERSION], [BUG-REPORT-ADDRESS]) +AC_CONFIG_SRCDIR([src/lib/xrhash.c]) + +# Checks for programs. +AC_PROG_CC +AC_PROG_RANLIB + +# Checks for libraries. + +# Checks for header files. +AC_CHECK_HEADERS([stdlib.h string.h sys/time.h unistd.h]) + +# Checks for typedefs, structures, and compiler characteristics. +AC_C_INLINE +AC_TYPE_SIZE_T + +# Checks for library functions. +AC_FUNC_MALLOC +AC_FUNC_REALLOC +AC_CHECK_FUNCS([gettimeofday memset strdup]) + +AC_CONFIG_FILES([Makefile + src/lib/Makefile + src/lib/tests/Makefile]) +AC_OUTPUT diff --git a/src/lib/platform.make b/platform.make similarity index 100% rename from src/lib/platform.make rename to platform.make diff --git a/src/lib/Makefile.in b/src/lib/Makefile.in new file mode 100644 index 0000000..1979050 --- /dev/null +++ b/src/lib/Makefile.in @@ -0,0 +1,32 @@ +ifeq ($(SRCROOT),) + SRCROOT=${CURDIR} +endif + +include ${SRCROOT}/platform.make + +OBJS=xrhash.o xrhash_fast.o +LIBNAME=xrhash + +STATIC_TARGET=$(LIBPREFIX)$(LIBNAME).$(STATIC_SUFFIX) +XRHASHLIB=${CURDIR}/$(STATIC_TARGET) + +export XRHASHLIB +export SRCROOT +CFLAGS+=-I${CURDIR} +export CFLAGS + +all: $(STATIC_TARGET) + +clean: + @rm -f $(OBJS) $(STATIC_TARGET) + $(MAKE) -C tests clean + +test: $(STATIC_TARGET) + $(MAKE) -e -C tests SRCROOT='${SRCROOT}' + + +$(STATIC_TARGET): $(OBJS) + ar ru $@ $^ + ranlib $@ + + diff --git a/src/lib/tests/Makefile.in b/src/lib/tests/Makefile.in new file mode 100644 index 0000000..7e98524 --- /dev/null +++ b/src/lib/tests/Makefile.in @@ -0,0 +1,13 @@ +include ${SRCROOT}/platform.make + +OBJS=testutils.o xrhash-test.o +TARGET=xrhash-test +LIBS=$(XRHASHLIB) + +all: $(TARGET) + +clean: + @rm -f $(OBJS) + +$(TARGET): $(OBJS) $(XRHASHLIB) + $(CC) -o $@ $^
inorton/xrhash
ebbf0826ee87f556cc6c698bb137bfdf7b442348
Makefiles
diff --git a/src/lib/Makefile b/src/lib/Makefile new file mode 100644 index 0000000..1979050 --- /dev/null +++ b/src/lib/Makefile @@ -0,0 +1,32 @@ +ifeq ($(SRCROOT),) + SRCROOT=${CURDIR} +endif + +include ${SRCROOT}/platform.make + +OBJS=xrhash.o xrhash_fast.o +LIBNAME=xrhash + +STATIC_TARGET=$(LIBPREFIX)$(LIBNAME).$(STATIC_SUFFIX) +XRHASHLIB=${CURDIR}/$(STATIC_TARGET) + +export XRHASHLIB +export SRCROOT +CFLAGS+=-I${CURDIR} +export CFLAGS + +all: $(STATIC_TARGET) + +clean: + @rm -f $(OBJS) $(STATIC_TARGET) + $(MAKE) -C tests clean + +test: $(STATIC_TARGET) + $(MAKE) -e -C tests SRCROOT='${SRCROOT}' + + +$(STATIC_TARGET): $(OBJS) + ar ru $@ $^ + ranlib $@ + + diff --git a/src/lib/platform.make b/src/lib/platform.make new file mode 100644 index 0000000..516d798 --- /dev/null +++ b/src/lib/platform.make @@ -0,0 +1,9 @@ +CFLAGS=$(XCFLAGS) -Wall -Werror +LIBPREFIX=lib +STATIC_SUFFIX=a +DYNAMIC_SUFFIX=so + +export CFLAGS +export LIBPREFIX +export STATIC_SUFFIX +export DYNAMIC_SUFFIX diff --git a/src/lib/tests/Makefile b/src/lib/tests/Makefile new file mode 100644 index 0000000..7e98524 --- /dev/null +++ b/src/lib/tests/Makefile @@ -0,0 +1,13 @@ +include ${SRCROOT}/platform.make + +OBJS=testutils.o xrhash-test.o +TARGET=xrhash-test +LIBS=$(XRHASHLIB) + +all: $(TARGET) + +clean: + @rm -f $(OBJS) + +$(TARGET): $(OBJS) $(XRHASHLIB) + $(CC) -o $@ $^ diff --git a/src/lib/xrhash_fast.c b/src/lib/xrhash_fast.c index 2e30de5..3733d36 100644 --- a/src/lib/xrhash_fast.c +++ b/src/lib/xrhash_fast.c @@ -1,70 +1,70 @@ -#include <xrhash.h> -#include <xrhash_fast.h> +#include "xrhash.h" +#include "xrhash_fast.h" xrhash_fast_iterator * xr_init_fasthashiterator( XRHash * xr ) { xrhash_fast_iterator * fast = NULL; fast = (xrhash_fast_iterator *)malloc(1*sizeof(xrhash_fast_iterator)); if ( fast == NULL ) return fast; fast->iter = xr_init_hashiterator( xr ); if ( fast->iter != NULL ){ fast->cache_progress = 0; fast->cache_index = 0; fast->cache = (void**)calloc( sizeof(void**), fast->iter->xr->count ); fast->cache_len = fast->iter->xr->count; } return fast; } void xr_hash_resetfastiterator( xrhash_fast_iterator * fast ) { fast->cache_index = 0; if ( fast->iter->hash_generation != fast->iter->xr->hash_generation ){ /* hash has changed */ xr_hash_resetiterator( fast->iter ); if ( fast->cache_len != fast->iter->xr->count ){ /* hash size has changed too */ fast->cache_len = fast->iter->xr->count; fast->cache = (void**) realloc( fast->cache, fast->iter->xr->count * sizeof( void** ) ); fast->cache_progress = 0; } } else { /* hash is unchanged */ } } void xr_hash_fastiterator_free( xrhash_fast_iterator * fast ) { if ( fast != NULL ){ if ( fast->cache != NULL ){ free(fast->cache); free(fast->iter); memset( fast, 0, sizeof(xrhash_fast_iterator) ); } free(fast); } } void * xr_hash_fastiteratekey( xrhash_fast_iterator * fast ) { if ( fast->iter->hash_generation == fast->iter->xr->hash_generation ){ if ( fast->cache_index < fast->cache_len ){ if ( fast->cache_index < fast->cache_progress ){ return fast->cache[fast->cache_index++]; } else { /* iterate and copy key */ void * key = xr_hash_iteratekey( fast->iter ); fast->cache[fast->cache_index++] = key; fast->cache_progress++; return key; } } return NULL; /* end of hash */ } else { fprintf(stderr,"hash changed during iteration\n"); abort(); } } diff --git a/src/lib/xrhash_fast.h b/src/lib/xrhash_fast.h index 4de8fa1..0b7690e 100644 --- a/src/lib/xrhash_fast.h +++ b/src/lib/xrhash_fast.h @@ -1,24 +1,24 @@ #ifndef XRHASH_FAST_H #define XRHASH_FAST_H -#include <xrhash.h> +#include "xrhash.h" typedef struct xrhash_fast_iterator { XRHashIter * iter; void ** cache; size_t cache_len; size_t cache_index; size_t cache_progress; } xrhash_fast_iterator; xrhash_fast_iterator * xr_init_fasthashiterator( XRHash * xr ); void xr_hash_resetfastiterator( xrhash_fast_iterator * fast ); void xr_hash_fastiterator_free( xrhash_fast_iterator * fast ); void * xr_hash_fastiteratekey( xrhash_fast_iterator * fast ); #endif diff --git a/xrhash-examples.md.pc b/xrhash-examples.md.pc index 998d435..df9fa95 100644 --- a/xrhash-examples.md.pc +++ b/xrhash-examples.md.pc @@ -1,5 +1,5 @@ Name: xrhash-examples Description: Version: 0.1 -Libs: -L/home/inb/Projects/git/xr/src/xrhash/bin/Debug -lxrhash -Cflags: -I/home/inb/Projects/git/xr/src/xrhash/src/examples +Libs: -L"/home/inb/Projects/git/xr/src/xrhash/bin/Debug" -lxrhash +Cflags: -I"/home/inb/Projects/git/xr/src/xrhash/src/examples" diff --git a/xrhash-lib.md.pc b/xrhash-lib.md.pc index ba55f7b..8b4edde 100644 --- a/xrhash-lib.md.pc +++ b/xrhash-lib.md.pc @@ -1,5 +1,5 @@ Name: xrhash-lib Description: Version: 0.1 -Libs: -L/home/inb/Projects/git/xr/src/xrhash/bin/Debug -lxrhash -Cflags: -I/home/inb/Projects/git/xr/src/xrhash/src/lib +Libs: -L"/home/inb/Projects/git/xr/src/xrhash/bin/Debug" -lxrhash +Cflags: -I"/home/inb/Projects/git/xr/src/xrhash/src/lib"
inorton/xrhash
e0af3f49a089a499ca482e5aab59a7f6a0418258
monodevelop project
diff --git a/xrhash-examples.cproj b/xrhash-examples.cproj new file mode 100644 index 0000000..c399919 --- /dev/null +++ b/xrhash-examples.cproj @@ -0,0 +1,55 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="3.5" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProductVersion>9.0.21022</ProductVersion> + <SchemaVersion>2.0</SchemaVersion> + <ProjectGuid>{E31D218E-73B5-4916-BEF5-F61AE75E7578}</ProjectGuid> + <Language>C</Language> + <Target>Bin</Target> + <Packages> + <Packages> + <Package file="/home/inb/Projects/git/xr/src/xrhash/xrhash-lib.md.pc" name="xrhash-lib" IsProject="true" /> + </Packages> + </Packages> + <Compiler> + <Compiler ctype="GccCompiler" /> + </Compiler> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <DebugSymbols>true</DebugSymbols> + <OutputPath>bin\Debug</OutputPath> + <WarningLevel>All</WarningLevel> + <WarningsAsErrors>true</WarningsAsErrors> + <SourceDirectory>.</SourceDirectory> + <DefineSymbols>DEBUG MONODEVELOP</DefineSymbols> + <Libs> + <Libs> + <Lib>curses</Lib> + </Libs> + </Libs> + <OutputName>xrhash</OutputName> + <Externalconsole>true</Externalconsole> + <Includes> + <Includes> + <Include>${ProjectDir}/src/examples</Include> + </Includes> + </Includes> + <CompileTarget>StaticLibrary</CompileTarget> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <OutputPath>bin\Release</OutputPath> + <DefineSymbols>MONODEVELOP</DefineSymbols> + <SourceDirectory>.</SourceDirectory> + <OptimizationLevel>3</OptimizationLevel> + <OutputName>xrhash</OutputName> + <CompileTarget>Bin</CompileTarget> + </PropertyGroup> + <ItemGroup> + <Compile Include="src\examples\spacemap.c" /> + </ItemGroup> + <ItemGroup> + <None Include="src\examples\spacemap.h" /> + </ItemGroup> +</Project> \ No newline at end of file diff --git a/xrhash-examples.md.pc b/xrhash-examples.md.pc new file mode 100644 index 0000000..998d435 --- /dev/null +++ b/xrhash-examples.md.pc @@ -0,0 +1,5 @@ +Name: xrhash-examples +Description: +Version: 0.1 +Libs: -L/home/inb/Projects/git/xr/src/xrhash/bin/Debug -lxrhash +Cflags: -I/home/inb/Projects/git/xr/src/xrhash/src/examples diff --git a/xrhash-lib.cproj b/xrhash-lib.cproj new file mode 100644 index 0000000..1f8319e --- /dev/null +++ b/xrhash-lib.cproj @@ -0,0 +1,46 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="3.5" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProductVersion>9.0.21022</ProductVersion> + <SchemaVersion>2.0</SchemaVersion> + <ProjectGuid>{935AADA5-6420-4F90-AB5E-FCAD71E8CFDA}</ProjectGuid> + <Target>Bin</Target> + <Language>C</Language> + <Compiler> + <Compiler ctype="GccCompiler" /> + </Compiler> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <DebugSymbols>true</DebugSymbols> + <OutputPath>bin\Debug</OutputPath> + <WarningLevel>All</WarningLevel> + <DefineSymbols>DEBUG MONODEVELOP</DefineSymbols> + <SourceDirectory>.</SourceDirectory> + <WarningsAsErrors>true</WarningsAsErrors> + <OutputName>xrhash</OutputName> + <CompileTarget>StaticLibrary</CompileTarget> + <Includes> + <Includes> + <Include>${ProjectDir}/src/lib</Include> + </Includes> + </Includes> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <OutputPath>bin\Release</OutputPath> + <DefineSymbols>MONODEVELOP</DefineSymbols> + <SourceDirectory>.</SourceDirectory> + <OptimizationLevel>3</OptimizationLevel> + <OutputName>xrhash</OutputName> + <CompileTarget>Bin</CompileTarget> + </PropertyGroup> + <ItemGroup> + <Compile Include="src\lib\xrhash.c" /> + <Compile Include="src\lib\xrhash_fast.c" /> + </ItemGroup> + <ItemGroup> + <None Include="src\lib\xrhash.h" /> + <None Include="src\lib\xrhash_fast.h" /> + </ItemGroup> +</Project> \ No newline at end of file diff --git a/xrhash-lib.md.pc b/xrhash-lib.md.pc new file mode 100644 index 0000000..ba55f7b --- /dev/null +++ b/xrhash-lib.md.pc @@ -0,0 +1,5 @@ +Name: xrhash-lib +Description: +Version: 0.1 +Libs: -L/home/inb/Projects/git/xr/src/xrhash/bin/Debug -lxrhash +Cflags: -I/home/inb/Projects/git/xr/src/xrhash/src/lib