Index: head/usr.bin/units/units.1 =================================================================== --- head/usr.bin/units/units.1 (revision 357448) +++ head/usr.bin/units/units.1 (revision 357449) @@ -1,205 +1,461 @@ .\" $FreeBSD$ -.Dd August 12, 2017 +.Dd February 3, 2020 .Dt UNITS 1 .Os .Sh NAME .Nm units -.Nd conversion program +.Nd conversion calculator .Sh SYNOPSIS .Nm -.Op Fl f Ar filename -.Op Fl H Ar filename -.Op Fl qvUV -.Op Ar from-unit to-unit -.Sh OPTIONS +.Op Fl ehqtUVv +.Op Fl f Ar unitsfile +.Op Fl o Ar format +.Op Ar from to +.Sh DESCRIPTION +The +.Nm +program converts quantities expressed in various scales to +their equivalents in other scales. +It can only +handle multiplicative or affine scale changes. +.Pp +.Nm +can work interactively by prompting +the user for input +.Pq see Sx EXAMPLES +or non-interactively, providing a conversion for given arguments +.Ar from +and +.Ar to . +.Pp The following options are available: -.Bl -tag -width indent -.It Fl h \&No , Fl -help -Show an overview of options -.It Fl f Ar filename \&No , Fl -file Ar filename +.Bl -tag -width "from to" +.It Fl e , Fl -exponential +Same as +.Fl o +.Cm %6e +(see the description of the +.Fl o +flag). +.It Fl f Ar unitsfile , Fl -file Ar unitsfile Specify the name of the units data file to load. -.It Fl H Ar filename \&No , Fl -history Ar filename +This option may be specified multiple times. +.It Fl H Ar historyfile , Fl -history Ar historyfile Ignored, for compatibility with GNU units. -.It Fl e , Fl -exponential -Behave as if -o '%6e' was typed. -.It Fl q \&No , Fl -quiet +.It Fl h , Fl -help +Show an overview of options. +.It Fl o Ar format , Fl -output-format Ar format +Select the output format string by which numbers are printed. +Defaults to +.Dq Li %.8g . +.It Fl q , Fl -quiet Suppress prompting of the user for units and the display of statistics about the number of units loaded. -.It Fl U \&No , Fl -unitsfile -If the default unit file exists prints its location. -If not, print -.Qo -Units data file not found -.Qc -.It Fl t \&No , Fl -terse -Only print the result. This is used when calling +.It Fl t , Fl -terse +Only print the result. +This is used when calling .Nm from other programs for easy to parse results. -.It Fl v \&No , Fl -verbose +.It Fl U , Fl -unitsfile +Print the location of the default unit file if it exists. +Otherwise, print +.Dq Units data file not found . +.It Fl V , Fl -version +Print the version number +.Pq which is fixed at Dq Fx units , +the path to the units data file and exit. +.It Fl v , Fl -verbose Print the units in the conversion output. Be more verbose in general. -.It Fl o Ar format \&No , Fl -output-format Ar format -Select the output format string by which numbers are printed. -.It Fl V \&No , Fl -version -Print the version number, usage, and then exit. -.It Ar from-unit to-unit +.It Ar from to Allow a single unit conversion to be done directly from the command line. The program will not print prompts. -It will print out the -result of the single specified conversion. +It will print out the result of the single specified conversion. +Both arguments, i.e., +.Ar from +and +.Ar to , +can be just a unit +.Pq e.g., Dq Cm cm , +a quantity +.Pq e.g., Dq Cm 42 , +or a quantity with a unit +.Pq e.g., Dq Cm 42 cm .El -.Sh DESCRIPTION -The -.Nm -program converts quantities expressed in various scales to -their equivalents in other scales. -The -.Nm -program can only -handle multiplicative or affine scale changes. -It works interactively by prompting -the user for input: -.Bd -literal - You have: meters - You want: feet - * 3.2808399 - / 0.3048 - - You have: cm^3 - You want: gallons - * 0.00026417205 - / 3785.4118 - - You have: meters/s - You want: furlongs/fortnight - * 6012.8848 - / 0.00016630952 - - You have: 1|2 inch - You want: cm - * 1.27 - / 0.78740157 - - You have: 85 degF - You want: degC - 29.444444 -.Ed -.Pp -Powers of units can be specified using the '^' character as shown in -the example, or by simple concatenation: 'cm3' is equivalent to 'cm^3'. -Multiplication of units can be specified by using spaces, a dash or -an asterisk. -Division of units is indicated by the slash ('/'). -Note that multiplication has a higher precedence than division, -so 'm/s/s' is the same as 'm/s^2' or 'm/s s'. +.Ss Mathematical operators +.Bl -dash -compact +.It +Powers of units can be specified using the +.Dq Ic ^ +character as shown in the example, or by simple concatenation: +.Dq Ic cm3 +is +equivalent to +.Dq Ic cm^3 . +See the +.Sx BUGS +section +for details on the limitations of exponent values. +.It +Multiplication of units can be specified by using spaces +.Pq Dq " " , +a dash +.Pq Dq - +or an asterisk +.Pq Dq * . +.It +Division of units is indicated by the slash +.Pq Dq Ic / . +.It Division of numbers -must be indicated using the vertical bar ('|'). -To convert half a -meter, you would write '1|2 meter'. -If you write '1/2 meter' then the -units program would interpret that as equivalent to '0.5/meter'. -If you enter incompatible unit types, the units program will -print a message indicating that the units are not conformable and -it will display the reduced form for each unit: -.Bd -literal - You have: ergs/hour - You want: fathoms kg^2 / day - conformability error - 2.7777778e-11 kg m^2 / sec^3 - 2.1166667e-05 kg^2 m / sec -.Ed +must be indicated using the vertical bar +.Pq Dq Ic \&| Ns . +.El .Pp +Note that multiplication has a higher precedence than division, +so +.Dq Ic m/s/s +is the same as +.Dq Ic m/s^2 +or +.Dq Ic m/s s . +.Ss Units The conversion information is read from a units data file. The default file includes definitions for most familiar units, abbreviations and metric prefixes. Some constants of nature included are: .Pp .Bl -column -offset indent -compact "mercury" .It "pi ratio of circumference to diameter" .It "c speed of light" .It "e charge on an electron" .It "g acceleration of gravity" .It "force same as g" .It "mole Avogadro's number" .It "water pressure per unit height of water" .It "mercury pressure per unit height of mercury" .It "au astronomical unit" .El .Pp -The unit 'pound' is a unit of mass. +The unit +.Dq Ic pound +is a unit of mass. Compound names are run together -so 'pound force' is a unit of force. -The unit 'ounce' is also a unit -of mass. -The fluid ounce is 'floz'. +so +.Dq Ic pound force +is a unit of force. +The unit +.Dq Ic ounce +is also a unit of mass. +The fluid ounce is +.Dq Ic floz . British units that differ from -their US counterparts are prefixed with 'br', and currency is prefixed -with its country name: 'belgiumfranc', 'britainpound'. +their US counterparts are prefixed with +.Dq br , +and currency is prefixed with its country name: +.Dq Ic belgiumfranc , +.Dq Ic britainpound . When searching for a unit, if the specified string does not appear exactly as a unit name, then .Nm -will try to remove a trailing 's' or a -trailing 'es' and check again for a match. -.Pp +will try to remove a trailing +.Dq s +or a trailing +.Dq es +and check again for a match. +.Ss Units file format To find out what units are available read the standard units file. If you want to add your own units you can supply your own file. A unit is specified on a single line by giving its name and an equivalence. Be careful to define new units in terms of old ones so that a reduction leads to the -primitive units which are marked with '!' characters. +primitive units which are marked with +.Dq \&! +characters. The .Nm program will not detect infinite loops that could be caused by careless unit definitions. Comments in the unit definition file -begin with a '#' or '/' character at the beginning of a line. +begin with a +.Dq # +or +.Dq / +character at the beginning of a line. .Pp Prefixes are defined in the same way as standard units, but with -a trailing dash at the end of the prefix name. +a trailing dash +.Pq Dq - +at the end of the prefix name. If a unit is not found -even after removing trailing 's' or 'es', then it will be checked -against the list of prefixes. +even after removing trailing +.Dq s +or +.Dq es , +then it will be checked against the list of prefixes. Prefixes will be removed until a legal base unit is identified. +.Sh ENVIRONMENT +.Bl -tag -width PATH +.It Ev PATH +The colon-separated list of root directories at which +.Nm +tries to find +.Pa /usr/share/misc/definitions.units . .Pp +For example if +.Ev PATH +is set to +.Dq Li /tmp:/:/usr/local , +no +.Fl f +flags are provided, and +.Pa /usr/share/misc/definitions.units +is missing then +.Nm +tries to open the following files as the default units file: +.Pa /tmp/usr/share/misc/definitions.units , +.Pa /usr/share/misc/definitions.units , +and +.Pa /usr/local/usr/share/misc/definitions.units . +.El +.Sh FILES +.Bl -tag -width /usr/share/misc/definitions.units -compact +.It Pa /usr/share/misc/definitions.units +The standard units file. +.El +.Sh EXIT STATUS +.Ex -std +.Sh EXAMPLES +.Bl -tag -width 0n +.It Sy Example 1 : No Interactive usage +.Pp +Here is an example of an interactive session where the user is prompted for +units: +.Bd -literal -offset 2n +.Li You have : Ic meters +.Li You want : Ic feet + * 3.2808399 + / 0.3048 + +.Li You have : Ic cm^3 +.Li You want : Ic gallons + * 0.00026417205 + / 3785.4118 + +.Li You have : Ic meters/s +.Li You want : Ic furlongs/fortnight + * 6012.8848 + / 0.00016630952 + +.Li You have : Ic 1|2 inch +.Li You want : Ic cm + * 1.27 + / 0.78740157 + +.Li You have : Ic 85 degF +.Li You want : Ic degC + 29.444444 +.Ed +.It Sy Example 2 : No Difference between Do Ic \&| Dc No and Do Ic / Dc No division +.Pp +The following command shows how to convert half a meter to centimeters. +.Bd -literal -offset 2n +.Li $ Ic units '1|2 meter' cm + * 50 + / 0.02 +.Ed +.Pp +.Nm +prints the expected result because the division operator for numbers +.Pq Dq Li \&| +was used. +.Pp +Using the division operator for units +.Pq Dq Li / +would result in an error: +.Bd -literal -offset 2n +.Li $ Ic units '1/2 meter' cm +conformability error + 0.5 / m + 0.01 m +.Ed +.Pp +It is because +.Nm +interprets +.Dq Ic 1/2 meter +as +.Dq Ic 0.5/meter , +which is not conformable to +.Dq Ic cm . +.It Sy Example 3 : No Simple units file Here is an example of a short units file that defines some basic -units. +units: .Pp -.Bl -column -offset indent -compact "minute" +.Bl -column -offset 2n -compact "minute" .It "m !a!" .It "sec !b!" .It "micro- 1e-6" .It "minute 60 sec" .It "hour 60 min" .It "inch 0.0254 m" .It "ft 12 inches" .It "mile 5280 ft" .El -.Sh FILES -.Bl -tag -width /usr/share/misc/definitions.units -compact -.It Pa /usr/share/misc/definitions.units -the standard units library +.It Sy Example 4 : No Viewing units and conversions of the default units file +The following shell one-liner allows the user to view the contents of the +default units file: +.Bd -literal -offset 2n +.Li $ Ic less \&"$(units -U)" +.Ed .El +.Sh DIAGNOSTICS +.Bl -diag +.It can't find units file '%s' +The default units file is not in its default location +.Pq see Sx FILES +and it is not present in any file tree starting with their roots at directories from +.Ev PATH +.Pq see Sx ENVIRONMENT . +.It cap_rights_limit\&() failed +See +.Xr capsicum 4 . +.It conformability error +It is not possible to reduce the given units to one common unit: +they are not conformable. +Instead of a conversion, +.Nm +will display the reduced form for each provided unit: +.Bd -literal -offset 2n +.Li You have : Ic ergs/hour +.Li You want : Ic fathoms kg^2 / day +conformability error + 2.7777778e-11 kg m^2 / sec^3 + 2.1166667e-05 kg^2 m / sec +.Ed +.It Could not initialize history +See +.Xr editline 3 . +.It dupstr +.Xr strdup 3 +failed. +.It memory for prefixes exceeded in line %d +Over 100 prefixes were defined. +.It memory for units exceeded in line %d +Over 1000 prefixes were defined. +.It memory overflow in unit reduction +The requested conversion involves too many units +.Pq see Sx BUGS . +.It redefinition of prefix '%s' on line %d ignored +.No "" +.It redefinition of unit '%s' on line %d ignored +.No "" +.It unexpected end of prefix on line %d +.No "" +.It unexpected end of unit on line %d +.No "" +.It Units data file not found +The default units file is missing. +.It unable to enter capability mode +See +.Xr capsicum 4 . +.It unable to open units file '%s' +One of the user-specified units files cannot be opened. +.It unit reduces to zero +.No "" +.It unknown unit '%s' +The provided unit cannot be found in the units file. +.It WARNING: conversion of non-proportional quantities. +.Nm +may fail to convert +.Ar from +to +.Ar to +because the units are not proportional. +The warning is printed when a quantity is a part of the +.Ar to +argument. +It can be illustrated on an example of conversion from Fahrenheit to Celsius: +.Bd -literal -offset 2n +.Li $ Ic units \&"degF" \&"degC" + (-> x*0.55555556g -17.777778g) + (<- y*1.8g 32g) +.Li $ Ic units \&"degF" \&"1 degC" +WARNING: conversion of non-proportional quantities. + (-> x*0.55555556g -17.777778g) + (<- y*1.8g 32g) +.Li $ Ic units \&"1 degF" \&"1 degC" +WARNING: conversion of non-proportional quantities. + -17.222222 +.Ed +.El +.Sh SEE ALSO +.Xr bc 1 +.Sh HISTORY +The +.Nm +first appeared in +.Nx +and was ported to +.Fx 2.2.0 . +.Pp +The manual page was significantly rewritten in +.Fx 13.0 +by +.An Mateusz Piotrowski Aq Mt 0mp@FreeBSD.org . .Sh AUTHORS .An Adrian Mariano Aq Mt adrian@cam.cornell.edu .Sh BUGS -The effect of including a '/' in a prefix is surprising. +The effect of including a +.Dq / +in a prefix is surprising. .Pp Exponents entered by the user can be only one digit. You can work around this by multiplying several terms. .Pp -The user must use | to indicate division of numbers and / to -indicate division of symbols. +The user must use +.Dq Ic \&| +to indicate division of numbers and +.Dq Ic / +to indicate division of symbols. This distinction should not be necessary. .Pp The program contains various arbitrary limits on the length of the units converted and on the length of the data file. .Pp The program should use a hash table to store units so that it does not take so long to load the units list and check for duplication. +.Pp +It is not possible to convert a negative value. +.Pp +The +.Nm +program +does not handle reductions of long lists of units very well: +.Bd -literal -offset 2n +.Li $ Ic units \&"$(yes m | head -n 154)" \&"$(yes cm | head -n 154)" + * 1e+308 + / 1e-308 +.Li $ Ic units \&"$(yes m | head -n 333)" \&"$(yes cm | head -n 333)" + * inf + / 0 +.Li $ Ic units \&"$(yes m | head -n 500)" \&"$(yes cm | head -n 500)" +units: memory overflow in unit reduction +conformability error + 1 m^500 + 1 centi cm^499 +.Li $ Ic units \&"$(yes m | head -n 501)" \&"$(yes cm | head -n 501)" +units: memory overflow in unit reduction +units: memory overflow in unit reduction +units: memory overflow in unit reduction +conformability error + 1 m^500 + 1 centi cm^499 +.Ed Index: head/usr.bin/units/units.c =================================================================== --- head/usr.bin/units/units.c (revision 357448) +++ head/usr.bin/units/units.c (revision 357449) @@ -1,894 +1,894 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * units.c Copyright (c) 1993 by Adrian Mariano (adrian@cam.cornell.edu) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * Disclaimer: This software is provided by the author "as is". The author * shall not be liable for any damages caused in any way by this software. * * I would appreciate (though I do not require) receiving a copy of any * improvements you might make to this program. */ #ifndef lint static const char rcsid[] = "$FreeBSD$"; #endif /* not lint */ #include #include #include #include #include #include #include #include #include #include #include #ifndef UNITSFILE #define UNITSFILE "/usr/share/misc/definitions.units" #endif #define MAXUNITS 1000 #define MAXPREFIXES 100 #define MAXSUBUNITS 500 #define PRIMITIVECHAR '!' static const char *powerstring = "^"; static const char *numfmt = "%.8g"; static struct { char *uname; char *uval; } unittable[MAXUNITS]; struct unittype { char *numerator[MAXSUBUNITS]; char *denominator[MAXSUBUNITS]; double factor; double offset; int quantity; }; static struct { char *prefixname; char *prefixval; } prefixtable[MAXPREFIXES]; static char NULLUNIT[] = ""; #define SEPARATOR ":" static int unitcount; static int prefixcount; static bool verbose = false; static bool terse = false; static const char * outputformat; static const char * havestr; static const char * wantstr; static int addsubunit(char *product[], char *toadd); static int addunit(struct unittype *theunit, const char *toadd, int flip, int quantity); static void cancelunit(struct unittype * theunit); static int compare(const void *item1, const void *item2); static int compareproducts(char **one, char **two); static int compareunits(struct unittype * first, struct unittype * second); static int completereduce(struct unittype * unit); static char *dupstr(const char *str); static void initializeunit(struct unittype * theunit); static char *lookupunit(const char *unit); static void readunits(const char *userfile); static int reduceproduct(struct unittype * theunit, int flip); static int reduceunit(struct unittype * theunit); static void showanswer(struct unittype * have, struct unittype * want); static void showunit(struct unittype * theunit); static void sortunit(struct unittype * theunit); static void usage(void); static void zeroerror(void); static const char* promptstr = ""; static const char * prompt(EditLine *e __unused) { return promptstr; } static char * dupstr(const char *str) { char *ret; ret = strdup(str); if (!ret) err(3, "dupstr"); return (ret); } static void readunits(const char *userfile) { FILE *unitfile; char line[512], *lineptr; int len, linenum, i; cap_rights_t unitfilerights; unitcount = 0; linenum = 0; if (userfile) { unitfile = fopen(userfile, "r"); if (!unitfile) errx(1, "unable to open units file '%s'", userfile); } else { unitfile = fopen(UNITSFILE, "r"); if (!unitfile) { char *direc, *env; char filename[1000]; env = getenv("PATH"); if (env) { direc = strtok(env, SEPARATOR); while (direc) { snprintf(filename, sizeof(filename), "%s/%s", direc, UNITSFILE); unitfile = fopen(filename, "rt"); if (unitfile) break; direc = strtok(NULL, SEPARATOR); } } if (!unitfile) errx(1, "can't find units file '%s'", UNITSFILE); } } cap_rights_init(&unitfilerights, CAP_READ, CAP_FSTAT); if (caph_rights_limit(fileno(unitfile), &unitfilerights) < 0) err(1, "cap_rights_limit() failed"); while (!feof(unitfile)) { if (!fgets(line, sizeof(line), unitfile)) break; linenum++; lineptr = line; if (*lineptr == '/' || *lineptr == '#') continue; lineptr += strspn(lineptr, " \n\t"); len = strcspn(lineptr, " \n\t"); lineptr[len] = 0; if (!strlen(lineptr)) continue; if (lineptr[strlen(lineptr) - 1] == '-') { /* it's a prefix */ if (prefixcount == MAXPREFIXES) { warnx("memory for prefixes exceeded in line %d", linenum); continue; } lineptr[strlen(lineptr) - 1] = 0; prefixtable[prefixcount].prefixname = dupstr(lineptr); for (i = 0; i < prefixcount; i++) if (!strcmp(prefixtable[i].prefixname, lineptr)) { warnx("redefinition of prefix '%s' on line %d ignored", lineptr, linenum); continue; } lineptr += len + 1; lineptr += strspn(lineptr, " \n\t"); len = strcspn(lineptr, "\n\t"); if (len == 0) { warnx("unexpected end of prefix on line %d", linenum); continue; } lineptr[len] = 0; prefixtable[prefixcount++].prefixval = dupstr(lineptr); } else { /* it's not a prefix */ if (unitcount == MAXUNITS) { warnx("memory for units exceeded in line %d", linenum); continue; } unittable[unitcount].uname = dupstr(lineptr); for (i = 0; i < unitcount; i++) if (!strcmp(unittable[i].uname, lineptr)) { warnx("redefinition of unit '%s' on line %d ignored", lineptr, linenum); continue; } lineptr += len + 1; lineptr += strspn(lineptr, " \n\t"); if (!strlen(lineptr)) { warnx("unexpected end of unit on line %d", linenum); continue; } len = strcspn(lineptr, "\n\t"); lineptr[len] = 0; unittable[unitcount++].uval = dupstr(lineptr); } } fclose(unitfile); } static void initializeunit(struct unittype * theunit) { theunit->numerator[0] = theunit->denominator[0] = NULL; theunit->factor = 1.0; theunit->offset = 0.0; theunit->quantity = 0; } static int addsubunit(char *product[], char *toadd) { char **ptr; for (ptr = product; *ptr && *ptr != NULLUNIT; ptr++); if (ptr >= product + MAXSUBUNITS) { warnx("memory overflow in unit reduction"); return 1; } if (!*ptr) *(ptr + 1) = NULL; *ptr = dupstr(toadd); return 0; } static void showunit(struct unittype * theunit) { char **ptr; int printedslash; int counter = 1; printf(numfmt, theunit->factor); if (theunit->offset) printf("&%.8g", theunit->offset); for (ptr = theunit->numerator; *ptr; ptr++) { if (ptr > theunit->numerator && **ptr && !strcmp(*ptr, *(ptr - 1))) counter++; else { if (counter > 1) printf("%s%d", powerstring, counter); if (**ptr) printf(" %s", *ptr); counter = 1; } } if (counter > 1) printf("%s%d", powerstring, counter); counter = 1; printedslash = 0; for (ptr = theunit->denominator; *ptr; ptr++) { if (ptr > theunit->denominator && **ptr && !strcmp(*ptr, *(ptr - 1))) counter++; else { if (counter > 1) printf("%s%d", powerstring, counter); if (**ptr) { if (!printedslash) printf(" /"); printedslash = 1; printf(" %s", *ptr); } counter = 1; } } if (counter > 1) printf("%s%d", powerstring, counter); printf("\n"); } void zeroerror(void) { warnx("unit reduces to zero"); } /* Adds the specified string to the unit. Flip is 0 for adding normally, 1 for adding reciprocal. Quantity is 1 if this is a quantity to be converted rather than a pure unit. Returns 0 for successful addition, nonzero on error. */ static int addunit(struct unittype * theunit, const char *toadd, int flip, int quantity) { char *scratch, *savescr; char *item; char *divider, *slash, *offset; int doingtop; if (!strlen(toadd)) return 1; savescr = scratch = dupstr(toadd); for (slash = scratch + 1; *slash; slash++) if (*slash == '-' && (tolower(*(slash - 1)) != 'e' || !strchr(".0123456789", *(slash + 1)))) *slash = ' '; slash = strchr(scratch, '/'); if (slash) *slash = 0; doingtop = 1; do { item = strtok(scratch, " *\t\n/"); while (item) { if (strchr("0123456789.", *item)) { /* item is a number */ double num, offsetnum; if (quantity) theunit->quantity = 1; offset = strchr(item, '&'); if (offset) { *offset = 0; offsetnum = atof(offset+1); } else offsetnum = 0.0; divider = strchr(item, '|'); if (divider) { *divider = 0; num = atof(item); if (!num) { zeroerror(); free(savescr); return 1; } if (doingtop ^ flip) { theunit->factor *= num; theunit->offset *= num; } else { theunit->factor /= num; theunit->offset /= num; } num = atof(divider + 1); if (!num) { zeroerror(); free(savescr); return 1; } if (doingtop ^ flip) { theunit->factor /= num; theunit->offset /= num; } else { theunit->factor *= num; theunit->offset *= num; } } else { num = atof(item); if (!num) { zeroerror(); free(savescr); return 1; } if (doingtop ^ flip) { theunit->factor *= num; theunit->offset *= num; } else { theunit->factor /= num; theunit->offset /= num; } } if (doingtop ^ flip) theunit->offset += offsetnum; } else { /* item is not a number */ int repeat = 1; if (strchr("23456789", item[strlen(item) - 1])) { repeat = item[strlen(item) - 1] - '0'; item[strlen(item) - 1] = 0; } for (; repeat; repeat--) { if (addsubunit(doingtop ^ flip ? theunit->numerator : theunit->denominator, item)) { free(savescr); return 1; } } } item = strtok(NULL, " *\t/\n"); } doingtop--; if (slash) { scratch = slash + 1; } else doingtop--; } while (doingtop >= 0); free(savescr); return 0; } static int compare(const void *item1, const void *item2) { return strcmp(*(const char * const *)item1, *(const char * const *)item2); } static void sortunit(struct unittype * theunit) { char **ptr; unsigned int count; for (count = 0, ptr = theunit->numerator; *ptr; ptr++, count++); qsort(theunit->numerator, count, sizeof(char *), compare); for (count = 0, ptr = theunit->denominator; *ptr; ptr++, count++); qsort(theunit->denominator, count, sizeof(char *), compare); } void cancelunit(struct unittype * theunit) { char **den, **num; int comp; den = theunit->denominator; num = theunit->numerator; while (*num && *den) { comp = strcmp(*den, *num); if (!comp) { /* if (*den!=NULLUNIT) free(*den); if (*num!=NULLUNIT) free(*num);*/ *den++ = NULLUNIT; *num++ = NULLUNIT; } else if (comp < 0) den++; else num++; } } /* Looks up the definition for the specified unit. Returns a pointer to the definition or a null pointer if the specified unit does not appear in the units table. */ static char buffer[100]; /* buffer for lookupunit answers with prefixes */ char * lookupunit(const char *unit) { int i; char *copy; for (i = 0; i < unitcount; i++) { if (!strcmp(unittable[i].uname, unit)) return unittable[i].uval; } if (unit[strlen(unit) - 1] == '^') { copy = dupstr(unit); copy[strlen(copy) - 1] = 0; for (i = 0; i < unitcount; i++) { if (!strcmp(unittable[i].uname, copy)) { strlcpy(buffer, copy, sizeof(buffer)); free(copy); return buffer; } } free(copy); } if (unit[strlen(unit) - 1] == 's') { copy = dupstr(unit); copy[strlen(copy) - 1] = 0; for (i = 0; i < unitcount; i++) { if (!strcmp(unittable[i].uname, copy)) { strlcpy(buffer, copy, sizeof(buffer)); free(copy); return buffer; } } if (copy[strlen(copy) - 1] == 'e') { copy[strlen(copy) - 1] = 0; for (i = 0; i < unitcount; i++) { if (!strcmp(unittable[i].uname, copy)) { strlcpy(buffer, copy, sizeof(buffer)); free(copy); return buffer; } } } free(copy); } for (i = 0; i < prefixcount; i++) { size_t len = strlen(prefixtable[i].prefixname); if (!strncmp(prefixtable[i].prefixname, unit, len)) { if (!strlen(unit + len) || lookupunit(unit + len)) { snprintf(buffer, sizeof(buffer), "%s %s", prefixtable[i].prefixval, unit + len); return buffer; } } } return 0; } /* reduces a product of symbolic units to primitive units. The three low bits are used to return flags: bit 0 (1) set on if reductions were performed without error. bit 1 (2) set on if no reductions are performed. bit 2 (4) set on if an unknown unit is discovered. */ #define ERROR 4 static int reduceproduct(struct unittype * theunit, int flip) { char *toadd; char **product; int didsomething = 2; if (flip) product = theunit->denominator; else product = theunit->numerator; for (; *product; product++) { for (;;) { if (!strlen(*product)) break; toadd = lookupunit(*product); if (!toadd) { printf("unknown unit '%s'\n", *product); return ERROR; } if (strchr(toadd, PRIMITIVECHAR)) break; didsomething = 1; if (*product != NULLUNIT) { free(*product); *product = NULLUNIT; } if (addunit(theunit, toadd, flip, 0)) return ERROR; } } return didsomething; } /* Reduces numerator and denominator of the specified unit. Returns 0 on success, or 1 on unknown unit error. */ static int reduceunit(struct unittype * theunit) { int ret; ret = 1; while (ret & 1) { ret = reduceproduct(theunit, 0) | reduceproduct(theunit, 1); if (ret & 4) return 1; } return 0; } static int compareproducts(char **one, char **two) { while (*one || *two) { if (!*one && *two != NULLUNIT) return 1; if (!*two && *one != NULLUNIT) return 1; if (*one == NULLUNIT) one++; else if (*two == NULLUNIT) two++; else if (strcmp(*one, *two)) return 1; else { one++; two++; } } return 0; } /* Return zero if units are compatible, nonzero otherwise */ static int compareunits(struct unittype * first, struct unittype * second) { return compareproducts(first->numerator, second->numerator) || compareproducts(first->denominator, second->denominator); } static int completereduce(struct unittype * unit) { if (reduceunit(unit)) return 1; sortunit(unit); cancelunit(unit); return 0; } static void showanswer(struct unittype * have, struct unittype * want) { double ans; char* oformat; if (compareunits(have, want)) { printf("conformability error\n"); if (verbose) printf("\t%s = ", havestr); else if (!terse) printf("\t"); showunit(have); if (!terse) { if (verbose) printf("\t%s = ", wantstr); else printf("\t"); showunit(want); } } else if (have->offset != want->offset) { if (want->quantity) printf("WARNING: conversion of non-proportional quantities.\n"); if (have->quantity) { asprintf(&oformat, "\t%s\n", outputformat); printf(oformat, (have->factor + have->offset-want->offset)/want->factor); free(oformat); } else { asprintf(&oformat, "\t (-> x*%sg %sg)\n\t (<- y*%sg %sg)\n", outputformat, outputformat, outputformat, outputformat); printf(oformat, have->factor / want->factor, (have->offset-want->offset)/want->factor, want->factor / have->factor, (want->offset - have->offset)/have->factor); } } else { ans = have->factor / want->factor; if (verbose) { printf("\t%s = ", havestr); printf(outputformat, ans); printf(" * %s", wantstr); printf("\n"); } else if (terse) { printf(outputformat, ans); printf("\n"); } else { printf("\t* "); printf(outputformat, ans); printf("\n"); } if (verbose) { printf("\t%s = (1 / ", havestr); printf(outputformat, 1/ans); printf(") * %s\n", wantstr); } else if (!terse) { printf("\t/ "); printf(outputformat, 1/ans); printf("\n"); } } } static void __dead2 usage(void) { fprintf(stderr, - "usage: units [-f unitsfile] [-H historyfile] [-UVq] [from-unit to-unit]\n"); + "usage: units [-ehqtUVv] [-f unitsfile] [-o format] [from to]\n"); exit(3); } static struct option longopts[] = { - {"help", no_argument, NULL, 'h'}, {"exponential", no_argument, NULL, 'e'}, {"file", required_argument, NULL, 'f'}, {"history", required_argument, NULL, 'H'}, + {"help", no_argument, NULL, 'h'}, {"output-format", required_argument, NULL, 'o'}, {"quiet", no_argument, NULL, 'q'}, {"terse", no_argument, NULL, 't'}, {"unitsfile", no_argument, NULL, 'U'}, - {"verbose", no_argument, NULL, 'v'}, {"version", no_argument, NULL, 'V'}, + {"verbose", no_argument, NULL, 'v'}, { 0, 0, 0, 0 } }; int main(int argc, char **argv) { struct unittype have, want; int optchar; bool quiet; bool readfile; bool quit; History *inhistory; EditLine *el; HistEvent ev; int inputsz; char const * history_file; quiet = false; readfile = false; history_file = NULL; outputformat = numfmt; quit = false; while ((optchar = getopt_long(argc, argv, "+ehf:o:qtvH:UV", longopts, NULL)) != -1) { switch (optchar) { case 'e': outputformat = "%6e"; break; case 'f': readfile = true; if (strlen(optarg) == 0) readunits(NULL); else readunits(optarg); break; case 'H': history_file = optarg; break; case 'q': quiet = true; break; case 't': terse = true; break; case 'o': outputformat = optarg; break; case 'v': verbose = true; break; case 'V': fprintf(stderr, "FreeBSD units\n"); /* FALLTHROUGH */ case 'U': if (access(UNITSFILE, F_OK) == 0) printf("%s\n", UNITSFILE); else printf("Units data file not found"); exit(0); case 'h': /* FALLTHROUGH */ default: usage(); } } if (!readfile) readunits(NULL); if (optind == argc - 2) { if (caph_enter() < 0) err(1, "unable to enter capability mode"); havestr = argv[optind]; wantstr = argv[optind + 1]; initializeunit(&have); addunit(&have, havestr, 0, 1); completereduce(&have); initializeunit(&want); addunit(&want, wantstr, 0, 1); completereduce(&want); showanswer(&have, &want); } else { inhistory = history_init(); el = el_init(argv[0], stdin, stdout, stderr); el_set(el, EL_PROMPT, &prompt); el_set(el, EL_EDITOR, "emacs"); el_set(el, EL_SIGNAL, 1); el_set(el, EL_HIST, history, inhistory); el_source(el, NULL); history(inhistory, &ev, H_SETSIZE, 800); if (inhistory == 0) err(1, "Could not initialize history"); if (caph_enter() < 0) err(1, "unable to enter capability mode"); if (!quiet) printf("%d units, %d prefixes\n", unitcount, prefixcount); while (!quit) { do { initializeunit(&have); if (!quiet) promptstr = "You have: "; havestr = el_gets(el, &inputsz); if (havestr == NULL) { quit = true; break; } if (inputsz > 0) history(inhistory, &ev, H_ENTER, havestr); } while (addunit(&have, havestr, 0, 1) || completereduce(&have)); if (quit) { break; } do { initializeunit(&want); if (!quiet) promptstr = "You want: "; wantstr = el_gets(el, &inputsz); if (wantstr == NULL) { quit = true; break; } if (inputsz > 0) history(inhistory, &ev, H_ENTER, wantstr); } while (addunit(&want, wantstr, 0, 1) || completereduce(&want)); if (quit) { break; } showanswer(&have, &want); } history_end(inhistory); el_end(el); } return (0); }