xref: /netbsd-src/external/bsd/ntp/dist/libntp/mstolfp.c (revision deb6f0161a9109e7de9b519dc8dfb9478668dcdd)
1 /*	$NetBSD: mstolfp.c,v 1.7 2016/01/08 21:35:38 christos Exp $	*/
2 
3 /*
4  * mstolfp - convert an ascii string in milliseconds to an l_fp number
5  */
6 #include <config.h>
7 #include <stdio.h>
8 #include <ctype.h>
9 
10 #include "ntp_fp.h"
11 #include "ntp_stdlib.h"
12 
13 int
14 mstolfp(
15 	const char *str,
16 	l_fp *lfp
17 	)
18 {
19 	register const char *cp;
20 	register char *bp;
21 	register const char *cpdec;
22 	char buf[100];
23 
24 	/*
25 	 * We understand numbers of the form:
26 	 *
27 	 * [spaces][-][digits][.][digits][spaces|\n|\0]
28 	 *
29 	 * This is one enormous hack.  Since I didn't feel like
30 	 * rewriting the decoding routine for milliseconds, what
31 	 * is essentially done here is to make a copy of the string
32 	 * with the decimal moved over three places so the seconds
33 	 * decoding routine can be used.
34 	 */
35 	bp = buf;
36 	cp = str;
37 	while (isspace((unsigned char)*cp))
38 	    cp++;
39 
40 	if (*cp == '-') {
41 		*bp++ = '-';
42 		cp++;
43 	}
44 
45 	if (*cp != '.' && !isdigit((unsigned char)*cp))
46 	    return 0;
47 
48 
49 	/*
50 	 * Search forward for the decimal point or the end of the string.
51 	 */
52 	cpdec = cp;
53 	while (isdigit((unsigned char)*cpdec))
54 	    cpdec++;
55 
56 	/*
57 	 * Found something.  If we have more than three digits copy the
58 	 * excess over, else insert a leading 0.
59 	 */
60 	if ((cpdec - cp) > 3) {
61 		do {
62 			*bp++ = (char)*cp++;
63 		} while ((cpdec - cp) > 3);
64 	} else {
65 		*bp++ = '0';
66 	}
67 
68 	/*
69 	 * Stick the decimal in.  If we've got less than three digits in
70 	 * front of the millisecond decimal we insert the appropriate number
71 	 * of zeros.
72 	 */
73 	*bp++ = '.';
74 	if ((cpdec - cp) < 3) {
75 		size_t i = 3 - (cpdec - cp);
76 		do {
77 			*bp++ = '0';
78 		} while (--i > 0);
79 	}
80 
81 	/*
82 	 * Copy the remainder up to the millisecond decimal.  If cpdec
83 	 * is pointing at a decimal point, copy in the trailing number too.
84 	 */
85 	while (cp < cpdec)
86 	    *bp++ = (char)*cp++;
87 
88 	if (*cp == '.') {
89 		cp++;
90 		while (isdigit((unsigned char)*cp))
91 		    *bp++ = (char)*cp++;
92 	}
93 	*bp = '\0';
94 
95 	/*
96 	 * Check to make sure the string is properly terminated.  If
97 	 * so, give the buffer to the decoding routine.
98 	 */
99 	if (*cp != '\0' && !isspace((unsigned char)*cp))
100 	    return 0;
101 	return atolfp(buf, lfp);
102 }
103