9 /* #include <off_cvt.h>
11 /* off_t off_cvt_string(string)
12 /* const char *string;
14 /* VSTRING *off_cvt_number(result, offset)
18 /* This module provides conversions between \fIoff_t\fR and string.
20 /* off_cvt_string() converts a string, containing a non-negative
21 /* offset, to numerical form. The result is -1 in case of problems.
23 /* off_cvt_number() converts a non-negative offset to string form.
27 /* String with non-negative number to be converted to off_t.
29 /* Buffer for storage of the result of conversion to string.
31 /* Non-negative off_t value to be converted to string.
33 /* Panic: negative offset
37 /* The Secure Mailer license must be distributed with this software.
40 /* IBM T.J. Watson Research
42 /* Yorktown Heights, NY 10598, USA
50 /* Utility library. */
59 /* Application-specific. */
61 #define STR vstring_str
62 #define END vstring_end
63 #define SWAP(type, a, b) { type temp; temp = a; a = b; b = temp; }
65 /* off_cvt_string - string to number */
67 off_t
off_cvt_string(const char *str
)
77 * Multiplication by numbers > 2 can overflow without producing a smaller
78 * result mod 2^N (where N is the number of bits in the result type).
79 * (Victor Duchovni, Morgan Stanley).
81 for (result
= 0; (ch
= *(unsigned char *) str
) != 0; str
++) {
84 if ((res2
= result
+ result
) < result
)
86 if ((res4
= res2
+ res2
) < res2
)
88 if ((res8
= res4
+ res4
) < res4
)
90 if ((res10
= res8
+ res2
) < res8
)
92 if ((result
= res10
+ ch
- '0') < res10
)
98 /* off_cvt_number - number to string */
100 VSTRING
*off_cvt_number(VSTRING
*buf
, off_t offset
)
102 static char digs
[] = "0123456789";
111 msg_panic("off_cvt_number: negative offset -%s",
112 STR(off_cvt_number(buf
, -offset
)));
115 * First accumulate the result, backwards.
118 while (offset
!= 0) {
119 VSTRING_ADDCH(buf
, digs
[offset
% 10]);
122 VSTRING_TERMINATE(buf
);
125 * Then, reverse the result.
129 for (i
= 0; i
< VSTRING_LEN(buf
) / 2; i
++)
130 SWAP(int, start
[i
], last
[-i
]);
137 * Proof-of-concept test program. Read a number from stdin, convert to
138 * off_t, back to string, and print the result.
141 #include <vstring_vstream.h>
143 int main(int unused_argc
, char **unused_argv
)
145 VSTRING
*buf
= vstring_alloc(100);
148 while (vstring_fgets_nonl(buf
, VSTREAM_IN
)) {
149 if ((offset
= off_cvt_string(STR(buf
))) < 0) {
150 msg_warn("bad input %s", STR(buf
));
152 vstream_printf("%s\n", STR(off_cvt_number(buf
, offset
)));
154 vstream_fflush(VSTREAM_OUT
);