2 * units.c Copyright (c) 1993 by Adrian Mariano (adrian@cam.cornell.edu)
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. The name of the author may not be used to endorse or promote products
10 * derived from this software without specific prior written permission.
11 * Disclaimer: This software is provided by the author "as is". The author
12 * shall not be liable for any damages caused in any way by this software.
14 * I would appreciate (though I do not require) receiving a copy of any
15 * improvements you might make to this program.
19 static const char rcsid[] =
34 #include <sys/capsicum.h>
37 #define UNITSFILE "/usr/share/misc/definitions.units"
41 #define MAXPREFIXES 100
43 #define MAXSUBUNITS 500
45 #define PRIMITIVECHAR '!'
47 static const char *powerstring = "^";
48 static const char *numfmt = "%.8g";
53 } unittable[MAXUNITS];
56 char *numerator[MAXSUBUNITS];
57 char *denominator[MAXSUBUNITS];
66 } prefixtable[MAXPREFIXES];
69 static char NULLUNIT[] = "";
74 static int prefixcount;
75 static bool verbose = false;
76 static bool terse = false;
77 static const char * outputformat;
78 static const char * havestr;
79 static const char * wantstr;
81 static int addsubunit(char *product[], char *toadd);
82 static int addunit(struct unittype *theunit, const char *toadd, int flip, int quantity);
83 static void cancelunit(struct unittype * theunit);
84 static int compare(const void *item1, const void *item2);
85 static int compareproducts(char **one, char **two);
86 static int compareunits(struct unittype * first, struct unittype * second);
87 static int completereduce(struct unittype * unit);
88 static char *dupstr(const char *str);
89 static void initializeunit(struct unittype * theunit);
90 static char *lookupunit(const char *unit);
91 static void readunits(const char *userfile);
92 static int reduceproduct(struct unittype * theunit, int flip);
93 static int reduceunit(struct unittype * theunit);
94 static void showanswer(struct unittype * have, struct unittype * want);
95 static void showunit(struct unittype * theunit);
96 static void sortunit(struct unittype * theunit);
97 static void usage(void);
98 static void zeroerror(void);
100 static const char* promptstr = "";
102 static const char * prompt(EditLine *e __unused) {
107 dupstr(const char *str)
119 readunits(const char *userfile)
122 char line[512], *lineptr;
124 cap_rights_t unitfilerights;
130 unitfile = fopen(userfile, "r");
132 errx(1, "unable to open units file '%s'", userfile);
135 unitfile = fopen(UNITSFILE, "r");
140 env = getenv("PATH");
142 direc = strtok(env, SEPARATOR);
144 snprintf(filename, sizeof(filename),
145 "%s/%s", direc, UNITSFILE);
146 unitfile = fopen(filename, "rt");
149 direc = strtok(NULL, SEPARATOR);
153 errx(1, "can't find units file '%s'", UNITSFILE);
156 cap_rights_init(&unitfilerights, CAP_READ, CAP_FSTAT);
157 if (cap_rights_limit(fileno(unitfile), &unitfilerights) < 0
159 err(1, "cap_rights_limit() failed");
160 while (!feof(unitfile)) {
161 if (!fgets(line, sizeof(line), unitfile))
165 if (*lineptr == '/' || *lineptr == '#')
167 lineptr += strspn(lineptr, " \n\t");
168 len = strcspn(lineptr, " \n\t");
170 if (!strlen(lineptr))
172 if (lineptr[strlen(lineptr) - 1] == '-') { /* it's a prefix */
173 if (prefixcount == MAXPREFIXES) {
174 warnx("memory for prefixes exceeded in line %d", linenum);
177 lineptr[strlen(lineptr) - 1] = 0;
178 prefixtable[prefixcount].prefixname = dupstr(lineptr);
179 for (i = 0; i < prefixcount; i++)
180 if (!strcmp(prefixtable[i].prefixname, lineptr)) {
181 warnx("redefinition of prefix '%s' on line %d ignored",
186 lineptr += strspn(lineptr, " \n\t");
187 len = strcspn(lineptr, "\n\t");
189 warnx("unexpected end of prefix on line %d",
194 prefixtable[prefixcount++].prefixval = dupstr(lineptr);
196 else { /* it's not a prefix */
197 if (unitcount == MAXUNITS) {
198 warnx("memory for units exceeded in line %d", linenum);
201 unittable[unitcount].uname = dupstr(lineptr);
202 for (i = 0; i < unitcount; i++)
203 if (!strcmp(unittable[i].uname, lineptr)) {
204 warnx("redefinition of unit '%s' on line %d ignored",
209 lineptr += strspn(lineptr, " \n\t");
210 if (!strlen(lineptr)) {
211 warnx("unexpected end of unit on line %d",
215 len = strcspn(lineptr, "\n\t");
217 unittable[unitcount++].uval = dupstr(lineptr);
224 initializeunit(struct unittype * theunit)
226 theunit->numerator[0] = theunit->denominator[0] = NULL;
227 theunit->factor = 1.0;
228 theunit->offset = 0.0;
229 theunit->quantity = 0;
234 addsubunit(char *product[], char *toadd)
238 for (ptr = product; *ptr && *ptr != NULLUNIT; ptr++);
239 if (ptr >= product + MAXSUBUNITS) {
240 warnx("memory overflow in unit reduction");
245 *ptr = dupstr(toadd);
251 showunit(struct unittype * theunit)
257 printf(numfmt, theunit->factor);
259 printf("&%.8g", theunit->offset);
260 for (ptr = theunit->numerator; *ptr; ptr++) {
261 if (ptr > theunit->numerator && **ptr &&
262 !strcmp(*ptr, *(ptr - 1)))
266 printf("%s%d", powerstring, counter);
273 printf("%s%d", powerstring, counter);
276 for (ptr = theunit->denominator; *ptr; ptr++) {
277 if (ptr > theunit->denominator && **ptr &&
278 !strcmp(*ptr, *(ptr - 1)))
282 printf("%s%d", powerstring, counter);
293 printf("%s%d", powerstring, counter);
301 warnx("unit reduces to zero");
305 Adds the specified string to the unit.
306 Flip is 0 for adding normally, 1 for adding reciprocal.
307 Quantity is 1 if this is a quantity to be converted rather than a pure unit.
309 Returns 0 for successful addition, nonzero on error.
313 addunit(struct unittype * theunit, const char *toadd, int flip, int quantity)
315 char *scratch, *savescr;
317 char *divider, *slash, *offset;
323 savescr = scratch = dupstr(toadd);
324 for (slash = scratch + 1; *slash; slash++)
326 (tolower(*(slash - 1)) != 'e' ||
327 !strchr(".0123456789", *(slash + 1))))
329 slash = strchr(scratch, '/');
334 item = strtok(scratch, " *\t\n/");
336 if (strchr("0123456789.", *item)) { /* item is a number */
337 double num, offsetnum;
340 theunit->quantity = 1;
342 offset = strchr(item, '&');
345 offsetnum = atof(offset+1);
349 divider = strchr(item, '|');
357 if (doingtop ^ flip) {
358 theunit->factor *= num;
359 theunit->offset *= num;
361 theunit->factor /= num;
362 theunit->offset /= num;
364 num = atof(divider + 1);
369 if (doingtop ^ flip) {
370 theunit->factor /= num;
371 theunit->offset /= num;
373 theunit->factor *= num;
374 theunit->offset *= num;
383 if (doingtop ^ flip) {
384 theunit->factor *= num;
385 theunit->offset *= num;
387 theunit->factor /= num;
388 theunit->offset /= num;
392 theunit->offset += offsetnum;
394 else { /* item is not a number */
397 if (strchr("23456789",
398 item[strlen(item) - 1])) {
399 repeat = item[strlen(item) - 1] - '0';
400 item[strlen(item) - 1] = 0;
402 for (; repeat; repeat--)
403 if (addsubunit(doingtop ^ flip ? theunit->numerator : theunit->denominator, item))
406 item = strtok(NULL, " *\t/\n");
414 } while (doingtop >= 0);
421 compare(const void *item1, const void *item2)
423 return strcmp(*(const char * const *)item1, *(const char * const *)item2);
428 sortunit(struct unittype * theunit)
433 for (count = 0, ptr = theunit->numerator; *ptr; ptr++, count++);
434 qsort(theunit->numerator, count, sizeof(char *), compare);
435 for (count = 0, ptr = theunit->denominator; *ptr; ptr++, count++);
436 qsort(theunit->denominator, count, sizeof(char *), compare);
441 cancelunit(struct unittype * theunit)
446 den = theunit->denominator;
447 num = theunit->numerator;
449 while (*num && *den) {
450 comp = strcmp(*den, *num);
452 /* if (*den!=NULLUNIT) free(*den);
453 if (*num!=NULLUNIT) free(*num);*/
468 Looks up the definition for the specified unit.
469 Returns a pointer to the definition or a null pointer
470 if the specified unit does not appear in the units table.
473 static char buffer[100]; /* buffer for lookupunit answers with
477 lookupunit(const char *unit)
482 for (i = 0; i < unitcount; i++) {
483 if (!strcmp(unittable[i].uname, unit))
484 return unittable[i].uval;
487 if (unit[strlen(unit) - 1] == '^') {
489 copy[strlen(copy) - 1] = 0;
490 for (i = 0; i < unitcount; i++) {
491 if (!strcmp(unittable[i].uname, copy)) {
492 strlcpy(buffer, copy, sizeof(buffer));
499 if (unit[strlen(unit) - 1] == 's') {
501 copy[strlen(copy) - 1] = 0;
502 for (i = 0; i < unitcount; i++) {
503 if (!strcmp(unittable[i].uname, copy)) {
504 strlcpy(buffer, copy, sizeof(buffer));
509 if (copy[strlen(copy) - 1] == 'e') {
510 copy[strlen(copy) - 1] = 0;
511 for (i = 0; i < unitcount; i++) {
512 if (!strcmp(unittable[i].uname, copy)) {
513 strlcpy(buffer, copy, sizeof(buffer));
521 for (i = 0; i < prefixcount; i++) {
522 size_t len = strlen(prefixtable[i].prefixname);
523 if (!strncmp(prefixtable[i].prefixname, unit, len)) {
524 if (!strlen(unit + len) || lookupunit(unit + len)) {
525 snprintf(buffer, sizeof(buffer), "%s %s",
526 prefixtable[i].prefixval, unit + len);
537 reduces a product of symbolic units to primitive units.
538 The three low bits are used to return flags:
540 bit 0 (1) set on if reductions were performed without error.
541 bit 1 (2) set on if no reductions are performed.
542 bit 2 (4) set on if an unknown unit is discovered.
549 reduceproduct(struct unittype * theunit, int flip)
554 int didsomething = 2;
557 product = theunit->denominator;
559 product = theunit->numerator;
561 for (; *product; product++) {
564 if (!strlen(*product))
566 toadd = lookupunit(*product);
568 printf("unknown unit '%s'\n", *product);
571 if (strchr(toadd, PRIMITIVECHAR))
574 if (*product != NULLUNIT) {
578 if (addunit(theunit, toadd, flip, 0))
587 Reduces numerator and denominator of the specified unit.
588 Returns 0 on success, or 1 on unknown unit error.
592 reduceunit(struct unittype * theunit)
598 ret = reduceproduct(theunit, 0) | reduceproduct(theunit, 1);
607 compareproducts(char **one, char **two)
609 while (*one || *two) {
610 if (!*one && *two != NULLUNIT)
612 if (!*two && *one != NULLUNIT)
614 if (*one == NULLUNIT)
616 else if (*two == NULLUNIT)
618 else if (strcmp(*one, *two))
627 /* Return zero if units are compatible, nonzero otherwise */
630 compareunits(struct unittype * first, struct unittype * second)
633 compareproducts(first->numerator, second->numerator) ||
634 compareproducts(first->denominator, second->denominator);
639 completereduce(struct unittype * unit)
641 if (reduceunit(unit))
649 showanswer(struct unittype * have, struct unittype * want)
654 if (compareunits(have, want)) {
655 printf("conformability error\n");
657 printf("\t%s = ", havestr);
663 printf("\t%s = ", wantstr);
669 else if (have->offset != want->offset) {
671 printf("WARNING: conversion of non-proportional quantities.\n");
672 if (have->quantity) {
673 asprintf(&oformat, "\t%s\n", outputformat);
675 (have->factor + have->offset-want->offset)/want->factor);
679 asprintf(&oformat, "\t (-> x*%sg %sg)\n\t (<- y*%sg %sg)\n",
680 outputformat, outputformat, outputformat, outputformat);
682 have->factor / want->factor,
683 (have->offset-want->offset)/want->factor,
684 want->factor / have->factor,
685 (want->offset - have->offset)/have->factor);
689 ans = have->factor / want->factor;
692 printf("\t%s = ", havestr);
693 printf(outputformat, ans);
694 printf(" * %s", wantstr);
698 printf(outputformat, ans);
703 printf(outputformat, ans);
708 printf("\t%s = (1 / ", havestr);
709 printf(outputformat, 1/ans);
710 printf(") * %s\n", wantstr);
714 printf(outputformat, 1/ans);
725 "usage: units [-f unitsfile] [-H historyfile] [-UVq] [from-unit to-unit]\n");
729 static struct option longopts[] = {
730 {"help", no_argument, NULL, 'h'},
731 {"exponential", no_argument, NULL, 'e'},
732 {"file", required_argument, NULL, 'f'},
733 {"history", required_argument, NULL, 'H'},
734 {"output-format", required_argument, NULL, 'o'},
735 {"quiet", no_argument, NULL, 'q'},
736 {"terse", no_argument, NULL, 't'},
737 {"unitsfile", no_argument, NULL, 'U'},
738 {"verbose", no_argument, NULL, 'v'},
739 {"version", no_argument, NULL, 'V'},
745 main(int argc, char **argv)
748 struct unittype have, want;
757 char const * history_file;
762 outputformat = numfmt;
764 while ((optchar = getopt_long(argc, argv, "+ehf:oqtvHUV", longopts, NULL)) != -1) {
767 outputformat = "%6e";
771 if (strlen(optarg) == 0)
777 history_file = optarg;
786 outputformat = optarg;
792 fprintf(stderr, "FreeBSD units\n");
795 if (access(UNITSFILE, F_OK) == 0)
796 printf("%s\n", UNITSFILE);
798 printf("Units data file not found");
812 if (optind == argc - 2) {
813 if (cap_enter() < 0 && errno != ENOSYS)
814 err(1, "unable to enter capability mode");
816 havestr = argv[optind];
817 wantstr = argv[optind + 1];
818 initializeunit(&have);
819 addunit(&have, havestr, 0, 1);
820 completereduce(&have);
821 initializeunit(&want);
822 addunit(&want, wantstr, 0, 1);
823 completereduce(&want);
824 showanswer(&have, &want);
826 inhistory = history_init();
827 el = el_init(argv[0], stdin, stdout, stderr);
828 el_set(el, EL_PROMPT, &prompt);
829 el_set(el, EL_EDITOR, "emacs");
830 el_set(el, EL_SIGNAL, 1);
831 el_set(el, EL_HIST, history, inhistory);
833 history(inhistory, &ev, H_SETSIZE, 800);
835 err(1, "Could not initialize history");
837 if (cap_enter() < 0 && errno != ENOSYS)
838 err(1, "unable to enter capability mode");
841 printf("%d units, %d prefixes\n", unitcount,
845 initializeunit(&have);
847 promptstr = "You have: ";
848 havestr = el_gets(el, &inputsz);
849 if (havestr == NULL) {
854 history(inhistory, &ev, H_ENTER,
856 } while (addunit(&have, havestr, 0, 1) ||
857 completereduce(&have));
862 initializeunit(&want);
864 promptstr = "You want: ";
865 wantstr = el_gets(el, &inputsz);
866 if (wantstr == NULL) {
871 history(inhistory, &ev, H_ENTER,
873 } while (addunit(&want, wantstr, 0, 1) ||
874 completereduce(&want));
878 showanswer(&have, &want);
881 history_end(inhistory);