home *** CD-ROM | disk | FTP | other *** search
- /*
- * escape.c -- interpret and expand character escapes
- *
- * This code brought to you as a public service by Eric S. Raymond, Feb 1988
- * and is copyrighted (c)1988 by the author. Use, distribute, and mangle
- * freely, but don't try to make money selling it unless you're going to send
- * me a cut. Send bug reports, love letters and death threats to eric@snark
- * aka ...!rutgers!vu-vlsi!snark!eric.
- */
- /*LINTLIBRARY*/
- #include <stdio.h>
- #include <ctype.h>
-
- int escape(cp, tp)
- /* interpret standard C-style octal and hex escapes plus \e for ESC */
- char *cp, *tp;
- {
- extern char *strchr();
- int ccount = 0;
-
- while (*cp)
- {
- int cval = 0;
-
- if (*cp == '\\' && strchr("0123456789xX", cp[1]))
- {
- char *dp, *hex = "00112233445566778899aAbBcCdDeEfF";
- int dcount = 0;
-
- if (*++cp == 'x' || *cp == 'X')
- for (++cp; (dp = strchr(hex, *cp)) && dcount++ < 2; cp++)
- cval = (cval * 16) + (dp - hex) / 2;
- else if (*cp == '0')
- while (strchr("01234567", *cp) && dcount++ < 3)
- cval = (cval * 8) + (*cp++ - '0');
- else
- while (strchr("0123456789", *cp) && dcount++ < 3)
- cval = (cval * 10) + (*cp++ - '0');
- }
- else if (*cp == '\\') /* C-style character escape */
- {
- switch (*++cp)
- {
- case '\\': cval = '\\'; break;
- case 'n': cval = '\n'; break;
- case 't': cval = '\t'; break;
- case 'b': cval = '\b'; break;
- case 'r': cval = '\r'; break;
- case 'e': cval = 0x1b; break;
- default: cval = *cp;
- }
- cp++;
- }
- else
- cval = *cp++;
- *tp++ = cval;
- ccount++;
- }
- *tp = '\0';
- return(ccount);
- }
-
- int expand(sp, tp)
- /* generate a restricted set of escapes for nonprintable chars in a string */
- char *sp;
- char *tp;
- {
- char *start;
-
- for (start = tp; *sp; sp++)
- {
- if (!isprint(*sp) || *sp == '\\')
- *tp++ = '\\';
-
- if (*sp == '\\')
- *tp++ = '\\';
- else if (*sp == '\b')
- *tp++ = '\b';
- else if (*sp == '\n')
- *tp++ = '\n';
- else if (*sp == '\t')
- *tp++ = '\t';
- else if (*sp == '\r')
- *tp++ = '\r';
- else if (isprint(*sp))
- *tp++ = *sp;
- else
- {
- (void) sprintf(tp, "\\%03.3o", toascii(*sp));
- tp += strlen(tp);
- }
- }
- *tp = '\0';
- return(tp - start);
- }
-
- /* escape.c ends here */
-