2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * units.c Copyright (c) 1993 by Adrian Mariano (adrian@cam.cornell.edu)
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. The name of the author may not be used to endorse or promote products
12 * derived from this software without specific prior written permission.
13 * Disclaimer: This software is provided by the author "as is". The author
14 * shall not be liable for any damages caused in any way by this software.
16 * I would appreciate (though I do not require) receiving a copy of any
17 * improvements you might make to this program.
21 static const char rcsid[] =
36 #include <capsicum_helpers.h>
39 #define UNITSFILE "/usr/share/misc/definitions.units"
43 #define MAXPREFIXES 100
45 #define MAXSUBUNITS 500
47 #define PRIMITIVECHAR '!'
49 static const char *powerstring = "^";
50 static const char *numfmt = "%.8g";
55 } unittable[MAXUNITS];
58 char *numerator[MAXSUBUNITS];
59 char *denominator[MAXSUBUNITS];
68 } prefixtable[MAXPREFIXES];
71 static char NULLUNIT[] = "";
76 static int prefixcount;
77 static bool verbose = false;
78 static bool terse = false;
79 static const char * outputformat;
80 static const char * havestr;
81 static const char * wantstr;
83 static int addsubunit(char *product[], char *toadd);
84 static int addunit(struct unittype *theunit, const char *toadd, int flip, int quantity);
85 static void cancelunit(struct unittype * theunit);
86 static int compare(const void *item1, const void *item2);
87 static int compareproducts(char **one, char **two);
88 static int compareunits(struct unittype * first, struct unittype * second);
89 static int completereduce(struct unittype * unit);
90 static char *dupstr(const char *str);
91 static void initializeunit(struct unittype * theunit);
92 static char *lookupunit(const char *unit);
93 static void readunits(const char *userfile);
94 static int reduceproduct(struct unittype * theunit, int flip);
95 static int reduceunit(struct unittype * theunit);
96 static void showanswer(struct unittype * have, struct unittype * want);
97 static void showunit(struct unittype * theunit);
98 static void sortunit(struct unittype * theunit);
99 static void usage(void);
100 static void zeroerror(void);
102 static const char* promptstr = "";
104 static const char * prompt(EditLine *e __unused) {
109 dupstr(const char *str)
121 readunits(const char *userfile)
124 char line[512], *lineptr;
126 cap_rights_t unitfilerights;
132 unitfile = fopen(userfile, "r");
134 errx(1, "unable to open units file '%s'", userfile);
137 unitfile = fopen(UNITSFILE, "r");
142 env = getenv("PATH");
144 direc = strtok(env, SEPARATOR);
146 snprintf(filename, sizeof(filename),
147 "%s/%s", direc, UNITSFILE);
148 unitfile = fopen(filename, "rt");
151 direc = strtok(NULL, SEPARATOR);
155 errx(1, "can't find units file '%s'", UNITSFILE);
158 cap_rights_init(&unitfilerights, CAP_READ, CAP_FSTAT);
159 if (caph_rights_limit(fileno(unitfile), &unitfilerights) < 0)
160 err(1, "cap_rights_limit() failed");
161 while (!feof(unitfile)) {
162 if (!fgets(line, sizeof(line), unitfile))
166 if (*lineptr == '/' || *lineptr == '#')
168 lineptr += strspn(lineptr, " \n\t");
169 len = strcspn(lineptr, " \n\t");
171 if (!strlen(lineptr))
173 if (lineptr[strlen(lineptr) - 1] == '-') { /* it's a prefix */
174 if (prefixcount == MAXPREFIXES) {
175 warnx("memory for prefixes exceeded in line %d", linenum);
178 lineptr[strlen(lineptr) - 1] = 0;
179 prefixtable[prefixcount].prefixname = dupstr(lineptr);
180 for (i = 0; i < prefixcount; i++)
181 if (!strcmp(prefixtable[i].prefixname, lineptr)) {
182 warnx("redefinition of prefix '%s' on line %d ignored",
187 lineptr += strspn(lineptr, " \n\t");
188 len = strcspn(lineptr, "\n\t");
190 warnx("unexpected end of prefix on line %d",
195 prefixtable[prefixcount++].prefixval = dupstr(lineptr);
197 else { /* it's not a prefix */
198 if (unitcount == MAXUNITS) {
199 warnx("memory for units exceeded in line %d", linenum);
202 unittable[unitcount].uname = dupstr(lineptr);
203 for (i = 0; i < unitcount; i++)
204 if (!strcmp(unittable[i].uname, lineptr)) {
205 warnx("redefinition of unit '%s' on line %d ignored",
210 lineptr += strspn(lineptr, " \n\t");
211 if (!strlen(lineptr)) {
212 warnx("unexpected end of unit on line %d",
216 len = strcspn(lineptr, "\n\t");
218 unittable[unitcount++].uval = dupstr(lineptr);
225 initializeunit(struct unittype * theunit)
227 theunit->numerator[0] = theunit->denominator[0] = NULL;
228 theunit->factor = 1.0;
229 theunit->offset = 0.0;
230 theunit->quantity = 0;
235 addsubunit(char *product[], char *toadd)
239 for (ptr = product; *ptr && *ptr != NULLUNIT; ptr++);
240 if (ptr >= product + MAXSUBUNITS) {
241 warnx("memory overflow in unit reduction");
246 *ptr = dupstr(toadd);
252 showunit(struct unittype * theunit)
258 printf(numfmt, theunit->factor);
260 printf("&%.8g", theunit->offset);
261 for (ptr = theunit->numerator; *ptr; ptr++) {
262 if (ptr > theunit->numerator && **ptr &&
263 !strcmp(*ptr, *(ptr - 1)))
267 printf("%s%d", powerstring, counter);
274 printf("%s%d", powerstring, counter);
277 for (ptr = theunit->denominator; *ptr; ptr++) {
278 if (ptr > theunit->denominator && **ptr &&
279 !strcmp(*ptr, *(ptr - 1)))
283 printf("%s%d", powerstring, counter);
294 printf("%s%d", powerstring, counter);
302 warnx("unit reduces to zero");
306 Adds the specified string to the unit.
307 Flip is 0 for adding normally, 1 for adding reciprocal.
308 Quantity is 1 if this is a quantity to be converted rather than a pure unit.
310 Returns 0 for successful addition, nonzero on error.
314 addunit(struct unittype * theunit, const char *toadd, int flip, int quantity)
316 char *scratch, *savescr;
318 char *divider, *slash, *offset;
324 savescr = scratch = dupstr(toadd);
325 for (slash = scratch + 1; *slash; slash++)
327 (tolower(*(slash - 1)) != 'e' ||
328 !strchr(".0123456789", *(slash + 1))))
330 slash = strchr(scratch, '/');
335 item = strtok(scratch, " *\t\n/");
337 if (strchr("0123456789.", *item)) { /* item is a number */
338 double num, offsetnum;
341 theunit->quantity = 1;
343 offset = strchr(item, '&');
346 offsetnum = atof(offset+1);
350 divider = strchr(item, '|');
359 if (doingtop ^ flip) {
360 theunit->factor *= num;
361 theunit->offset *= num;
363 theunit->factor /= num;
364 theunit->offset /= num;
366 num = atof(divider + 1);
372 if (doingtop ^ flip) {
373 theunit->factor /= num;
374 theunit->offset /= num;
376 theunit->factor *= num;
377 theunit->offset *= num;
387 if (doingtop ^ flip) {
388 theunit->factor *= num;
389 theunit->offset *= num;
391 theunit->factor /= num;
392 theunit->offset /= num;
396 theunit->offset += offsetnum;
398 else { /* item is not a number */
401 if (strchr("23456789",
402 item[strlen(item) - 1])) {
403 repeat = item[strlen(item) - 1] - '0';
404 item[strlen(item) - 1] = 0;
406 for (; repeat; repeat--) {
407 if (addsubunit(doingtop ^ flip ? theunit->numerator : theunit->denominator, item)) {
413 item = strtok(NULL, " *\t/\n");
421 } while (doingtop >= 0);
428 compare(const void *item1, const void *item2)
430 return strcmp(*(const char * const *)item1, *(const char * const *)item2);
435 sortunit(struct unittype * theunit)
440 for (count = 0, ptr = theunit->numerator; *ptr; ptr++, count++);
441 qsort(theunit->numerator, count, sizeof(char *), compare);
442 for (count = 0, ptr = theunit->denominator; *ptr; ptr++, count++);
443 qsort(theunit->denominator, count, sizeof(char *), compare);
448 cancelunit(struct unittype * theunit)
453 den = theunit->denominator;
454 num = theunit->numerator;
456 while (*num && *den) {
457 comp = strcmp(*den, *num);
459 /* if (*den!=NULLUNIT) free(*den);
460 if (*num!=NULLUNIT) free(*num);*/
475 Looks up the definition for the specified unit.
476 Returns a pointer to the definition or a null pointer
477 if the specified unit does not appear in the units table.
480 static char buffer[100]; /* buffer for lookupunit answers with
484 lookupunit(const char *unit)
489 for (i = 0; i < unitcount; i++) {
490 if (!strcmp(unittable[i].uname, unit))
491 return unittable[i].uval;
494 if (unit[strlen(unit) - 1] == '^') {
496 copy[strlen(copy) - 1] = 0;
497 for (i = 0; i < unitcount; i++) {
498 if (!strcmp(unittable[i].uname, copy)) {
499 strlcpy(buffer, copy, sizeof(buffer));
506 if (unit[strlen(unit) - 1] == 's') {
508 copy[strlen(copy) - 1] = 0;
509 for (i = 0; i < unitcount; i++) {
510 if (!strcmp(unittable[i].uname, copy)) {
511 strlcpy(buffer, copy, sizeof(buffer));
516 if (copy[strlen(copy) - 1] == 'e') {
517 copy[strlen(copy) - 1] = 0;
518 for (i = 0; i < unitcount; i++) {
519 if (!strcmp(unittable[i].uname, copy)) {
520 strlcpy(buffer, copy, sizeof(buffer));
528 for (i = 0; i < prefixcount; i++) {
529 size_t len = strlen(prefixtable[i].prefixname);
530 if (!strncmp(prefixtable[i].prefixname, unit, len)) {
531 if (!strlen(unit + len) || lookupunit(unit + len)) {
532 snprintf(buffer, sizeof(buffer), "%s %s",
533 prefixtable[i].prefixval, unit + len);
544 reduces a product of symbolic units to primitive units.
545 The three low bits are used to return flags:
547 bit 0 (1) set on if reductions were performed without error.
548 bit 1 (2) set on if no reductions are performed.
549 bit 2 (4) set on if an unknown unit is discovered.
556 reduceproduct(struct unittype * theunit, int flip)
561 int didsomething = 2;
564 product = theunit->denominator;
566 product = theunit->numerator;
568 for (; *product; product++) {
571 if (!strlen(*product))
573 toadd = lookupunit(*product);
575 printf("unknown unit '%s'\n", *product);
578 if (strchr(toadd, PRIMITIVECHAR))
581 if (*product != NULLUNIT) {
585 if (addunit(theunit, toadd, flip, 0))
594 Reduces numerator and denominator of the specified unit.
595 Returns 0 on success, or 1 on unknown unit error.
599 reduceunit(struct unittype * theunit)
605 ret = reduceproduct(theunit, 0) | reduceproduct(theunit, 1);
614 compareproducts(char **one, char **two)
616 while (*one || *two) {
617 if (!*one && *two != NULLUNIT)
619 if (!*two && *one != NULLUNIT)
621 if (*one == NULLUNIT)
623 else if (*two == NULLUNIT)
625 else if (strcmp(*one, *two))
636 /* Return zero if units are compatible, nonzero otherwise */
639 compareunits(struct unittype * first, struct unittype * second)
642 compareproducts(first->numerator, second->numerator) ||
643 compareproducts(first->denominator, second->denominator);
648 completereduce(struct unittype * unit)
650 if (reduceunit(unit))
658 showanswer(struct unittype * have, struct unittype * want)
663 if (compareunits(have, want)) {
664 printf("conformability error\n");
666 printf("\t%s = ", havestr);
672 printf("\t%s = ", wantstr);
678 else if (have->offset != want->offset) {
680 printf("WARNING: conversion of non-proportional quantities.\n");
681 if (have->quantity) {
682 asprintf(&oformat, "\t%s\n", outputformat);
684 (have->factor + have->offset-want->offset)/want->factor);
688 asprintf(&oformat, "\t (-> x*%sg %sg)\n\t (<- y*%sg %sg)\n",
689 outputformat, outputformat, outputformat, outputformat);
691 have->factor / want->factor,
692 (have->offset-want->offset)/want->factor,
693 want->factor / have->factor,
694 (want->offset - have->offset)/have->factor);
698 ans = have->factor / want->factor;
701 printf("\t%s = ", havestr);
702 printf(outputformat, ans);
703 printf(" * %s", wantstr);
707 printf(outputformat, ans);
712 printf(outputformat, ans);
717 printf("\t%s = (1 / ", havestr);
718 printf(outputformat, 1/ans);
719 printf(") * %s\n", wantstr);
723 printf(outputformat, 1/ans);
734 "usage: units [-ehqtUVv] [-f unitsfile] [-o format] [from to]\n");
738 static struct option longopts[] = {
739 {"exponential", no_argument, NULL, 'e'},
740 {"file", required_argument, NULL, 'f'},
741 {"history", required_argument, NULL, 'H'},
742 {"help", no_argument, NULL, 'h'},
743 {"output-format", required_argument, NULL, 'o'},
744 {"quiet", no_argument, NULL, 'q'},
745 {"terse", no_argument, NULL, 't'},
746 {"unitsfile", no_argument, NULL, 'U'},
747 {"version", no_argument, NULL, 'V'},
748 {"verbose", no_argument, NULL, 'v'},
754 main(int argc, char **argv)
757 struct unittype have, want;
766 char const * history_file;
771 outputformat = numfmt;
773 while ((optchar = getopt_long(argc, argv, "+ehf:o:qtvH:UV", longopts, NULL)) != -1) {
776 outputformat = "%6e";
780 if (strlen(optarg) == 0)
786 history_file = optarg;
795 outputformat = optarg;
801 fprintf(stderr, "FreeBSD units\n");
804 if (access(UNITSFILE, F_OK) == 0)
805 printf("%s\n", UNITSFILE);
807 printf("Units data file not found");
820 if (optind == argc - 2) {
821 if (caph_enter() < 0)
822 err(1, "unable to enter capability mode");
824 havestr = argv[optind];
825 wantstr = argv[optind + 1];
826 initializeunit(&have);
827 addunit(&have, havestr, 0, 1);
828 completereduce(&have);
829 initializeunit(&want);
830 addunit(&want, wantstr, 0, 1);
831 completereduce(&want);
832 showanswer(&have, &want);
834 inhistory = history_init();
835 el = el_init(argv[0], stdin, stdout, stderr);
836 el_set(el, EL_PROMPT, &prompt);
837 el_set(el, EL_EDITOR, "emacs");
838 el_set(el, EL_SIGNAL, 1);
839 el_set(el, EL_HIST, history, inhistory);
841 history(inhistory, &ev, H_SETSIZE, 800);
843 err(1, "Could not initialize history");
845 if (caph_enter() < 0)
846 err(1, "unable to enter capability mode");
849 printf("%d units, %d prefixes\n", unitcount,
853 initializeunit(&have);
855 promptstr = "You have: ";
856 havestr = el_gets(el, &inputsz);
857 if (havestr == NULL) {
862 history(inhistory, &ev, H_ENTER,
864 } while (addunit(&have, havestr, 0, 1) ||
865 completereduce(&have));
870 initializeunit(&want);
872 promptstr = "You want: ";
873 wantstr = el_gets(el, &inputsz);
874 if (wantstr == NULL) {
879 history(inhistory, &ev, H_ENTER,
881 } while (addunit(&want, wantstr, 0, 1) ||
882 completereduce(&want));
886 showanswer(&have, &want);
889 history_end(inhistory);