Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP
Posting-Version: version B 2.10.2 9/3/84; site panda.UUCP
Path: utzoo!watmath!clyde!cbosgd!ulysses!allegra!mit-eddie!genrad!panda!
sources-request
From: sources-requ...@panda.UUCP
Newsgroups: mod.sources
Subject: regexp(3)
Message-ID: <1316@panda.UUCP>
Date: Sun, 19-Jan-86 09:32:53 EST
Article-I.D.: panda.1316
Posted: Sun Jan 19 09:32:53 1986
Date-Received: Mon, 20-Jan-86 06:31:42 EST
Sender: j...@panda.UUCP
Lines: 2236
Approved: j...@panda.UUCP
Mod.sources: Volume 3, Issue 89
Submitted by: decvax!utzoo!henry
Below is an almost-public-domain re-implementation of the V8 regexp(3)
routines.
Henry Spencer @ U of Toronto Zoology
{allegra,ihnp4,linus,decvax}!utzoo!henry
--------------
echo README:
sed 's/^X//' >README <<'!'
XThis is a nearly-public-domain reimplementation of the V8 regexp(3) package.
XIt gives C programs the ability to use egrep-style regular expressions, and
Xdoes it in a much cleaner fashion than the analogous routines in SysV.
X
X Copyright (c) 1986 by University of Toronto.
X Written by Henry Spencer. Not derived from licensed software.
X
X Permission is granted to anyone to use this software for any
X purpose on any computer system, and to redistribute it freely,
X subject to the following restrictions:
X
X 1. The author is not responsible for the consequences of use of
X this software, no matter how awful, even if they arise
X from defects in it.
X
X 2. The origin of this software must not be misrepresented, either
X by explicit claim or by omission.
X
X 3. Altered versions must be plainly marked as such, and must not
X be misrepresented as being the original software.
X
XBarring a couple of small items in the BUGS list, this implementation is
Xbelieved 100% compatible with V8. It should even be binary-compatible,
Xsort of, since the only fields in a "struct regexp" that other people have
Xany business touching are declared in exactly the same way at the same
Xlocation in the struct (the beginning).
X
XThis implementation is *NOT* AT&T/Bell code, and is not derived from licensed
Xsoftware. Even though U of T is a V8 licensee. This software is based on
Xa V8 manual page sent to me by Dennis Ritchie (the manual page enclosed
Xhere is a complete rewrite and hence is not covered by AT&T copyright).
XThe software was nearly complete at the time of arrival of our V8 tape.
XI haven't even looked at V8 yet, although a friend elsewhere at U of T has
Xbeen kind enough to run a few test programs using the V8 regexp(3) to resolve
Xa few fine points. I admit to some familiarity with regular-expression
Ximplementations of the past, but the only one that this code traces any
Xancestry to is the one published in Kernighan & Plauger (from which this
Xone draws ideas but not code).
X
XSimplistically: put this stuff into a source directory, copy regexp.h into
X/usr/include, inspect Makefile for compilation options that need changing
Xto suit your local environment, and then do "make r". This compiles the
Xregexp(3) functions, compiles a test program, and runs a large set of
Xregression tests. If there are no complaints, then put regexp.o, regsub.o,
Xand regerror.o into your C library, and regexp.3 into your manual-pages
Xdirectory.
X
XNote that if you don't put regexp.h into /usr/include *before* compiling,
Xyou'll have to add "-I." to CFLAGS before compiling.
X
XThe files are:
X
XMakefile instructions to make everything
Xregexp.3 manual page
Xregexp.h header file, for /usr/include
Xregexp.c source for regcomp() and regexec()
Xregsub.c source for regsub()
Xregerror.c source for default regerror()
Xregmagic.h internal header file
Xtry.c source for test program
Xtimer.c source for timing program
Xtests test list for try and timer
X
XThis implementation uses nondeterministic automata rather than the
Xdeterministic ones found in some other implementations, which makes it
Xsimpler, smaller, and faster at compiling regular expressions, but slower
Xat executing them. In theory, anyway. This implementation does employ
Xsome special-case optimizations to make the simpler cases (which do make
Xup the bulk of regular expressions actually used) run quickly. In general,
Xif you want blazing speed you're in the wrong place. Replacing the insides
Xof egrep with this stuff is probably a mistake; if you want your own egrep
Xyou're going to have to do a lot more work. But if you want to use regular
Xexpressions a little bit in something else, you're in luck. Note that many
Xexisting text editors use nondeterministic regular-expression implementations,
Xso you're in good company.
X
XThis stuff should be pretty portable, given appropriate option settings.
XIf your chars have less than 8 bits, you're going to have to change the
Xinternal representation of the automaton, although knowledge of the details
Xof this is fairly localized. There are no "reserved" char values except for
XNUL, and no special significance is attached to the top bit of chars.
XThe string(3) functions are used a fair bit, on the grounds that they are
Xprobably faster than coding the operations in line. Some attempts at code
Xtuning have been made, but this is invariably a bit machine-specific.
!
echo Makefile:
sed 's/^X//' >Makefile <<'!'
X# Things you might want to put in ENV and LENV:
X# -Dvoid=int compilers that don't do void
X# -DCHARBITS=0377 compilers that don't do unsigned char
X# -DSTATIC=extern compilers that don't like "static foo();" as forward decl
X# -DSTRCSPN library does not have strcspn()
X# -Dstrchr=index library does not have strchr()
X# -DERRAVAIL have utzoo-compatible error() function and friends
XENV=-Dvoid=int -DCHARBITS=0377 -DSTATIC=extern
XLENV=-Dvoid=int -DCHARBITS=0377
X
X# Things you might want to put in TEST:
X# -DDEBUG debugging hooks
X# -I. regexp.h from current directory, not /usr/include
XTEST=
X
X# Things you might want to put in PROF:
X# -Dstatic='/* */' make everything global so profiler can see it.
X# -p profiler
XPROF=
X
XCFLAGS=-O $(ENV) $(TEST) $(PROF)
XLINTFLAGS=$(LENV) $(TEST) -ha
XLDFLAGS=-i
X
XOBJ=regexp.o regsub.o
XLSRC=regexp.c regsub.c regerror.c
XDTR=README dMakefile regexp.3 regexp.h regexp.c regsub.c regerror.c \
X regmagic.h try.c timer.c tests
X
Xtry: try.o $(OBJ)
X cc $(LDFLAGS) try.o $(OBJ) -o try
X
X# Making timer will probably require putting stuff in $(PROF) and then
X# recompiling everything; the following is just the final stage.
Xtimer: timer.o $(OBJ)
X cc $(LDFLAGS) $(PROF) timer.o $(OBJ) -o timer
X
Xtimer.o: timer.c timer.t.h
X
Xtimer.t.h: tests
X sed 's/ /","/g;s/\\/&&/g;s/.*/{"&"},/' tests >timer.t.h
X
X# Regression test.
Xr: try tests
X @echo 'No news is good news...'
X try <tests
X
Xlint: timer.t.h
X @echo 'Complaints about multiply-declared regerror() are legit.'
X lint $(LINTFLAGS) $(LSRC) try.c
X lint $(LINTFLAGS) $(LSRC) timer.c
X
Xregexp.o: regexp.c regexp.h regmagic.h
Xregsub.o: regsub.c regexp.h regmagic.h
X
Xclean:
X rm -f *.o core mon.out timer.t.h dMakefile dtr try timer
X
Xdtr: r makedtr $(DTR)
X makedtr $(DTR) >dtr
X
XdMakefile: Makefile
X sed '/^L*ENV=/s/ *-DERRAVAIL//' Makefile >dMakefile
!
echo regexp.3:
sed 's/^X//' >regexp.3 <<'!'
X.TH REGEXP 3 local
X.DA 30 Nov 1985
X.SH NAME
Xregcomp, regexec, regsub, regerror \- regular expression handler
X.SH SYNOPSIS
X.ft B
X.nf
X#include <regexp.h>
X
Xregexp *regcomp(exp)
Xchar *exp;
X
Xint regexec(prog, string)
Xregexp *prog;
Xchar *string;
X
Xregsub(prog, source, dest)
Xregexp *prog;
Xchar *source;
Xchar *dest;
X
Xregerror(msg)
Xchar *msg;
X.SH DESCRIPTION
XThese functions implement
X.IR egrep (1)-style
Xregular expressions and supporting facilities.
X.PP
X.I Regcomp
Xcompiles a regular expression into a structure of type
X.IR regexp ,
Xand returns a pointer to it.
XThe space has been allocated using
X.IR malloc (3)
Xand may be released by
X.IR free .
X.PP
X.I Regexec
Xmatches a NUL-terminated \fIstring\fR against the compiled regular expression
Xin \fIprog\fR.
XIt returns 1 for success and 0 for failure, and adjusts the contents of
X\fIprog\fR's \fIstartp\fR and \fIendp\fR (see below) accordingly.
X.PP
XThe members of a
X.I regexp
Xstructure include at least the following (not necessarily in order):
X.PP
X.RS
Xchar *startp[NSUBEXP];
X.br
Xchar *endp[NSUBEXP];
X.RE
X.PP
Xwhere
X.I NSUBEXP
Xis defined (as 10) in the header file.
XOnce a successful \fIregexec\fR has been done using the \fIregexp\fR,
Xeach \fIstartp\fR-\fIendp\fR pair describes one substring
Xwithin the \fIstring\fR,
Xwith the \fIstartp\fR pointing to the first character of the substring and
Xthe \fIendp\fR pointing to the first character following the substring.
XThe 0th substring is the substring of \fIstring\fR that matched the whole
Xregular expression.
XThe others are those substrings that matched parenthesized expressions
Xwithin the regular expression, with parenthesized expressions numbered
Xin left-to-right order of their opening parentheses.
X.PP
X.I Regsub
Xcopies \fIsource\fR to \fIdest\fR, making substitutions according to the
Xmost recent \fIregexec\fR performed using \fIprog\fR.
XEach instance of `&' in \fIsource\fR is replaced by the substring
Xindicated by \fIstartp\fR[\fI0\fR] and
X\fIendp\fR[\fI0\fR].
XEach instance of `\e\fIn\fR', where \fIn\fR is a digit, is replaced by
Xthe substring indicated by
X\fIstartp\fR[\fIn\fR] and
X\fIendp\fR[\fIn\fR].
X.PP
X.I Regerror
Xis called whenever an error is detected in \fIregcomp\fR, \fIregexec\fR,
Xor \fIregsub\fR.
XThe default \fIregerror\fR writes the string \fImsg\fR,
Xwith a suitable indicator of origin,
Xon the standard
Xerror output
Xand invokes \fIexit\fR(2).
X.I Regerror
Xcan be replaced by the user if other actions are desirable.
X.SH "REGULAR EXPRESSION SYNTAX"
XA regular expression is zero or more \fIbranches\fR, separated by `|'.
XIt matches anything that matches one of the branches.
X.PP
XA branch is zero or more \fIpieces\fR, concatenated.
XIt matches a match for the first, followed by a match for the second, etc.
X.PP
XA piece is an \fIatom\fR possibly followed by `*', `+', or `?'.
XAn atom followed by `*' matches a sequence of 0 or more matches of the atom.
XAn atom followed by `+' matches a sequence of 1 or more matches of the atom.
XAn atom followed by `?' matches a match of the atom, or the null string.
X.PP
XAn atom is a regular expression in parentheses (matching a match for the
Xregular expression), a \fIrange\fR (see below), `.'
X(matching any single character), `^' (matching the null string at the
Xbeginning of the input string), `$' (matching the null string at the
Xend of the input string), a `\e' followed by a single character (matching
Xthat character), or a single character with no other significance
X(matching that character).
X.PP
XA \fIrange\fR is a sequence of characters enclosed in `[]'.
XIt normally matches any single character from the sequence.
XIf the sequence begins with `^',
Xit matches any single character \fInot\fR from the rest of the sequence.
XIf two characters in the sequence are separated by `\-', this is shorthand
Xfor the full list of ASCII characters between them
X(e.g. `[0-9]' matches any decimal digit).
XTo include a literal `]' in the sequence, make it the first character
X(following a possible `^').
XTo include a literal `\-', make it the first or last character.
X.SH AMBIGUITY
XIf a regular expression could match two different parts of the input string,
Xit will match the one which begins earliest.
XIf both begin in the same place but match different lengths, or match
Xthe same length in different ways, life gets messier, as follows.
X.PP
XIn general, the possibilities in a list of branches are considered in
Xleft-to-right order, the possibilities for `*', `+', and `?' are
Xconsidered longest-first, nested constructs are considered from the
Xoutermost in, and concatenated constructs are considered leftmost-first.
XThe match that will be chosen is the one that uses the earliest
Xpossibility in the first choice that has to be made.
XIf there is more than one choice, the next will be made in the same manner
X(earliest possibility) subject to the decision on the first choice.
XAnd so forth.
X.PP
XFor example, `(ab|a)b*c' could match `abc' in one of two ways.
XThe first choice is between `ab' and `a'; since `ab' is earlier, and does
Xlead to a successful overall match, it is chosen.
XSince the `b' is already spoken for,
Xthe `b*' must match its last possibility\(emthe empty string\(emsince
Xit must respect the earlier choice.
X.PP
XIn the particular case where no `|'s are present and there is only one
X`*', `+', or `?', the net effect is that the longest possible
Xmatch will be chosen.
XSo `ab*', presented with `xabbbby', will match `abbbb'.
XNote that if `ab*' is tried against `xabyabbbz', it
Xwill match `ab' just after `x', due to the begins-earliest rule.
X(In effect, the decision on where to start the match is the first choice
Xto be made, hence subsequent choices must respect it even if this leads them
Xto less-preferred alternatives.)
X.SH SEE ALSO
Xegrep(1), expr(1)
X.SH DIAGNOSTICS
X\fIRegcomp\fR returns NULL for a failure
X(\fIregerror\fR permitting),
Xwhere failures are syntax errors, exceeding implementation limits,
Xor applying `+' or `*' to a possibly-null operand.
X.SH HISTORY
XBoth code and manual page were
Xwritten at U of T.
XThey are intended to be compatible with the Bell V8 \fIregexp\fR(3),
Xbut are not derived from Bell code.
X.SH BUGS
XEmpty branches and empty regular expressions are not portable to V8.
X.PP
XThe restriction against
Xapplying `*' or `+' to a possibly-null operand is an artifact of the
Xsimplistic implementation.
X.PP
XDoes not support \fIegrep\fR's newline-separated branches;
Xneither does the V8 \fIregexp\fR(3), though.
X.PP
XDue to emphasis on
Xcompactness and simplicity,
Xit's not strikingly fast.
XIt does give special attention to handling simple cases quickly.
!
echo regexp.h:
sed 's/^X//' >regexp.h <<'!'
X/*
X * Definitions etc. for regexp(3) routines.
X *
X * Caveat: this is V8 regexp(3) [actually, a reimplementation thereof],
X * not the System V one.
X */
X#define NSUBEXP 10
Xtypedef struct regexp {
X char *startp[NSUBEXP];
X char *endp[NSUBEXP];
X char regstart; /* Internal use only. */
X char reganch; /* Internal use only. */
X char *regmust; /* Internal use only. */
X int regmlen; /* Internal use only. */
X char program[1]; /* Unwarranted chumminess with compiler. */
X} regexp;
X
Xextern regexp *regcomp();
Xextern int regexec();
Xextern void regsub();
Xextern void regerror();
!
echo regexp.c:
sed 's/^X//' >regexp.c <<'!'
X/*
X * regcomp and regexec -- regsub and regerror are elsewhere
X *
X * Copyright (c) 1986 by University of Toronto.
X * Written by Henry Spencer. Not derived from licensed software.
X *
X * Permission is granted to anyone to use this software for any
X * purpose on any computer system, and to redistribute it freely,
X * subject to the following restrictions:
X *
X * 1. The author is not responsible for the consequences of use of
X * this software, no matter how awful, even if they arise
X * from defects in it.
X *
X * 2. The origin of this software must not be misrepresented, either
X * by explicit claim or by omission.
X *
X * 3. Altered versions must be plainly marked as such, and must not
X * be misrepresented as being the original software.
X *
X * Beware that some of this code is subtly aware of the way operator
X * precedence is structured in regular expressions. Serious changes in
X * regular-expression syntax might require a total rethink.
X */
X#include <stdio.h>
X#include <regexp.h>
X#include "regmagic.h"
X
X/*
X * The "internal use only" fields in regexp.h are present to pass info from
X * compile to execute that permits the execute phase to run lots faster on
X * simple cases. They are:
X *
X * regstart char that must begin a match; '\0' if none obvious
X * reganch is the match anchored (at beginning-of-line only)?
X * regmust string (pointer into program) that match must include, or NULL
X * regmlen length of regmust string
X *
X * Regstart and reganch permit very fast decisions on suitable starting points
X * for a match, cutting down the work a lot. Regmust permits fast rejection
X * of lines that cannot possibly match. The regmust tests are costly enough
X * that regcomp() supplies a regmust only if the r.e. contains something
X * potentially expensive (at present, the only such thing detected is * or +
X * at the start of the r.e., which can involve a lot of backup). Regmlen is
X * supplied because the test in regexec() needs it and regcomp() is computing
X * it anyway.
X */
X
X/*
X * Structure for regexp "program". This is essentially a linear encoding
X * of a nondeterministic finite-state machine (aka syntax charts or
X * "railroad normal form" in parsing technology). Each node is an opcode
X * plus a "next" pointer, possibly plus an operand. "Next" pointers of
X * all nodes except BRANCH implement concatenation; a "next" pointer with
X * a BRANCH on both ends of it is connecting two alternatives. (Here we
X * have one of the subtle syntax dependencies: an individual BRANCH (as
X * opposed to a collection of them) is never concatenated with anything
X * because of operator precedence.) The operand of some types of node is
X * a literal string; for others, it is a node leading into a sub-FSM. In
X * particular, the operand of a BRANCH node is the first node of the branch.
X * (NB this is *not* a tree structure: the tail of the branch connects
X * to the thing following the set of BRANCHes.) The opcodes are:
X */
X
X/* definition number opnd? meaning */
X#define END 0 /* no End of program. */
X#define BOL 1 /* no Match "" at beginning of line. */
X#define EOL 2 /* no Match "" at end of line. */
X#define ANY 3 /* no Match any one character. */
X#define ANYOF 4 /* str Match any character in this string. */
X#define ANYBUT 5 /* str Match any character not in this string. */
X#define BRANCH 6 /* node Match this alternative, or the next... */
X#define BACK 7 /* no Match "", "next" ptr points backward. */
X#define EXACTLY 8 /* str Match this string. */
X#define NOTHING 9 /* no Match empty string. */
X#define STAR 10 /* node Match this (simple) thing 0 or more times. */
X#define PLUS 11 /* node Match this (simple) thing 1 or more times. */
X#define OPEN 20 /* no Mark this point in input as start of #n. */
X /* OPEN+1 is number 1, etc. */
X#define CLOSE 30 /* no Analogous to OPEN. */
X
X/*
X * Opcode notes:
X *
X * BRANCH The set of branches constituting a single choice are hooked
X * together with their "next" pointers, since precedence prevents
X * anything being concatenated to any individual branch. The
X * "next" pointer of the last BRANCH in a choice points to the
X * thing following the whole choice. This is also where the
X * final "next" pointer of each individual branch points; each
X * branch starts with the operand node of a BRANCH node.
X *
X * BACK Normal "next" pointers all implicitly point forward; BACK
X * exists to make loop structures possible.
X *
X * STAR,PLUS '?', and complex '*' and '+', are implemented as circular
X * BRANCH structures using BACK. Simple cases (one character
X * per match) are implemented with STAR and PLUS for speed
X * and to minimize recursive plunges.
X *
X * OPEN,CLOSE ...are numbered at compile time.
X */
X
X/*
X * A node is one char of opcode followed by two chars of "next" pointer.
X * "Next" pointers are stored as two 8-bit pieces, high order first. The
X * value is a positive offset from the opcode of the node containing it.
X * An operand, if any, simply follows the node. (Note that much of the
X * code generation knows about this implicit relationship.)
X *
X * Using two bytes for the "next" pointer is vast overkill for most things,
X * but allows patterns to get big without disasters.
X */
X#define OP(p) (*(p))
X#define NEXT(p) (((*((p)+1)&0377)<<8) + *((p)+2)&0377)
X#define OPERAND(p) ((p) + 3)
X
X/*
X * See regmagic.h for one further detail of program structure.
X */
X
X
X/*
X * Utility definitions.
X */
X#ifndef CHARBITS
X#define UCHARAT(p) ((int)*(unsigned char *)(p))
X#else
X#define UCHARAT(p) ((int)*(p)&CHARBITS)
X#endif
X
X#define FAIL(m) { regerror(m); return(NULL); }
X#define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?')
X#define META "^$.[()|?+*\\"
X
X/*
X * Flags to be passed up and down.
X */
X#define HASWIDTH 01 /* Known never to match null string. */
X#define SIMPLE 02 /* Simple enough to be STAR/PLUS operand. */
X#define SPSTART 04 /* Starts with * or +. */
X#define WORST 0 /* Worst case. */
X
X/*
X * Global work variables for regcomp().
X */
Xstatic char *regparse; /* Input-scan pointer. */
Xstatic int regnpar; /* () count. */
Xstatic char regdummy;
Xstatic char *regcode; /* Code-emit pointer; ®dummy = don't. */
Xstatic long regsize; /* Code size. */
X
X/*
X * Forward declarations for regcomp()'s friends.
X */
X#ifndef STATIC
X#define STATIC static
X#endif
XSTATIC char *reg();
XSTATIC char *regbranch();
XSTATIC char *regpiece();
XSTATIC char *regatom();
XSTATIC char *regnode();
XSTATIC char *regnext();
XSTATIC void regc();
XSTATIC void reginsert();
XSTATIC void regtail();
XSTATIC void regoptail();
X#ifdef STRCSPN
XSTATIC int strcspn();
X#endif
X
X/*
X - regcomp - compile a regular expression into internal code
X *
X * We can't allocate space until we know how big the compiled form will be,
X * but we can't compile it (and thus know how big it is) until we've got a
X * place to put the code. So we cheat: we compile it twice, once with code
X * generation turned off and size counting turned on, and once "for real".
X * This also means that we don't allocate space until we are sure that the
X * thing really will compile successfully, and we never have to move the
X * code and thus invalidate pointers into it. (Note that it has to be in
X * one piece because free() must be able to free it all.)
X *
X * Beware that the optimization-preparation code in here knows about some
X * of the structure of the compiled regexp.
X */
Xregexp *
Xregcomp(exp)
Xchar *exp;
X{
X register regexp *r;
X register char *scan;
X register char *longest;
X register int len;
X int flags;
X extern char *malloc();
X
X if (exp == NULL)
X FAIL("NULL argument");
X
X /* First pass: determine size, legality. */
X regparse = exp;
X regnpar = 1;
X regsize = 0L;
X regcode = ®dummy;
X regc(MAGIC);
X if (reg(0, &flags) == NULL)
X return(NULL);
X
X /* Small enough for pointer-storage convention? */
X if (regsize >= 32767L) /* Probably could be 65535L. */
X FAIL("regexp too big");
X
X /* Allocate space. */
X r = (regexp *)malloc(sizeof(regexp) + (unsigned)regsize);
X if (r == NULL)
X FAIL("out of space");
X
X /* Second pass: emit code. */
X regparse = exp;
X regnpar = 1;
X regcode = r->program;
X regc(MAGIC);
X if (reg(0, &flags) == NULL)
X return(NULL);
X
X /* Dig out information for optimizations. */
X r->regstart = '\0'; /* Worst-case defaults. */
X r->reganch = 0;
X r->regmust = NULL;
X r->regmlen = 0;
X scan = r->program+1; /* First BRANCH. */
X if (OP(regnext(scan)) == END) { /* Only one top-level choice. */
X scan = OPERAND(scan);
X
X /* Starting-point info. */
X if (OP(scan) == EXACTLY)
X r->regstart = *OPERAND(scan);
X else if (OP(scan) == BOL)
X r->reganch++;
X
X /*
X * If there's something expensive in the r.e., find the
X * longest literal string that must appear and make it the
X * regmust. Resolve ties in favor of later strings, since
X * the regstart check works with the beginning of the r.e.
X * and avoiding duplication strengthens checking. Not a
X * strong reason, but sufficient in the absence of others.
X */
X if (flags&SPSTART) {
X longest = NULL;
X len = 0;
X for (; scan != NULL; scan = regnext(scan))
X if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
X longest = OPERAND(scan);
X len = strlen(OPERAND(scan));
X }
X r->regmust = longest;
X r->regmlen = len;
X }
X }
X
X return(r);
X}
X
X/*
X - reg - regular expression, i.e. main body or parenthesized thing
X *
X * Caller must absorb opening parenthesis.
X *
X * Combining parenthesis handling with the base level of regular expression
X * is a trifle forced, but the need to tie the tails of the branches to what
X * follows makes it hard to avoid.
X */
Xstatic char *
Xreg(paren, flagp)
Xint paren; /* Parenthesized? */
Xint *flagp;
X{
X register char *ret;
X register char *br;
X register char *ender;
X register int parno;
X int flags;
X
X *flagp = HASWIDTH; /* Tentatively. */
X
X /* Make an OPEN node, if parenthesized. */
X if (paren) {
X if (regnpar >= NSUBEXP)
X FAIL("too many ()");
X parno = regnpar;
X regnpar++;
X ret = regnode(OPEN+parno);
X } else
X ret = NULL;
X
X /* Pick up the branches, linking them together. */
X br = regbranch(&flags);
X if (br == NULL)
X return(NULL);
X if (ret != NULL)
X regtail(ret, br); /* OPEN -> first. */
X else
X ret = br;
X if (!(flags&HASWIDTH))
X *flagp &= ~HASWIDTH;
X *flagp |= flags&SPSTART;
X while (*regparse == '|') {
X regparse++;
X br = regbranch(&flags);
X if (br == NULL)
X return(NULL);
X regtail(ret, br); /* BRANCH -> BRANCH. */
X if (!(flags&HASWIDTH))
X *flagp &= ~HASWIDTH;
X *flagp |= flags&SPSTART;
X }
X
X /* Make a closing node, and hook it on the end. */
X ender = regnode((paren) ? CLOSE+parno : END);
X regtail(ret, ender);
X
X /* Hook the tails of the branches to the closing node. */
X for (br = ret; br != NULL; br = regnext(br))
X regoptail(br, ender);
X
X /* Check for proper termination. */
X if (paren && *regparse++ != ')') {
X FAIL("unmatched ()");
X } else if (!paren && *regparse != '\0') {
X if (*regparse == ')') {
X FAIL("unmatched ()");
X } else
X FAIL("junk on end"); /* "Can't happen". */
X /* NOTREACHED */
X }
X
X return(ret);
X}
X
X/*
X - regbranch - one alternative of an | operator
X *
X * Implements the concatenation operator.
X */
Xstatic char *
Xregbranch(flagp)
Xint *flagp;
X{
X register char *ret;
X register char *chain;
X register char *latest;
X int flags;
X
X *flagp = WORST; /* Tentatively. */
X
X ret = regnode(BRANCH);
X chain = NULL;
X while (*regparse != '\0' && *regparse != '|' && *regparse != ')') {
X latest = regpiece(&flags);
X if (latest == NULL)
X return(NULL);
X *flagp |= flags&HASWIDTH;
X if (chain == NULL) /* First piece. */
X *flagp |= flags&SPSTART;
X else
X regtail(chain, latest);
X chain = latest;
X }
X if (chain == NULL) /* Loop ran zero times. */
X (void) regnode(NOTHING);
X
X return(ret);
X}
X
X/*
X - regpiece - something followed by possible [*+?]
X *
X * Note that the branching code sequences used for ? and the general cases
X * of * and + are somewhat optimized: they use the same NOTHING node as
X * both the endmarker for their branch list and the body of the last branch.
X * It might seem that this node could be dispensed with entirely, but the
X * endmarker role is not redundant.
X */
Xstatic char *
Xregpiece(flagp)
Xint *flagp;
X{
X register char *ret;
X register char op;
X register char *next;
X int flags;
X
X ret = regatom(&flags);
X if (ret == NULL)
X return(NULL);
X
X op = *regparse;
X if (!ISMULT(op)) {
X *flagp = flags;
X return(ret);
X }
X
X if (!(flags&HASWIDTH) && op != '?')
X FAIL("*+ operand could be empty");
X *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
X
X if (op == '*' && (flags&SIMPLE))
X reginsert(STAR, ret);
X else if (op == '*') {
X /* Emit x* as (x&|), where & means "self". */
X reginsert(BRANCH, ret); /* Either x */
X regoptail(ret, regnode(BACK)); /* and loop */
X regoptail(ret, ret); /* back */
X regtail(ret, regnode(BRANCH)); /* or */
X regtail(ret, regnode(NOTHING)); /* null. */
X } else if (op == '+' && (flags&SIMPLE))
X reginsert(PLUS, ret);
X else if (op == '+') {
X /* Emit x+ as x(&|), where & means "self". */
X next = regnode(BRANCH); /* Either */
X regtail(ret, next);
X regtail(regnode(BACK), ret); /* loop back */
X regtail(next, regnode(BRANCH)); /* or */
X regtail(ret, regnode(NOTHING)); /* null. */
X } else if (op == '?') {
X /* Emit x? as (x|) */
X reginsert(BRANCH, ret); /* Either x */
X regtail(ret, regnode(BRANCH)); /* or */
X next = regnode(NOTHING); /* null. */
X regtail(ret, next);
X regoptail(ret, next);
X }
X regparse++;
X if (ISMULT(*regparse))
X FAIL("nested *?+");
X
X return(ret);
X}
X
X/*
X - regatom - the lowest level
X *
X * Optimization: gobbles an entire sequence of ordinary characters so that
X * it can turn them into a single node, which is smaller to store and
X * faster to run. Backslashed characters are exceptions, each becoming a
X * separate node; the code is simpler that way and it's not worth fixing.
X */
Xstatic char *
Xregatom(flagp)
Xint *flagp;
X{
X register char *ret;
X int flags;
X
X *flagp = WORST; /* Tentatively. */
X
X switch (*regparse++) {
X case '^':
X ret = regnode(BOL);
X break;
X case '$':
X ret = regnode(EOL);
X break;
X case '.':
X ret = regnode(ANY);
X *flagp |= HASWIDTH|SIMPLE;
X break;
X case '[': {
X register int class;
X register int classend;
X
X if (*regparse == '^') { /* Complement of range. */
X ret = regnode(ANYBUT);
X regparse++;
X } else
X ret = regnode(ANYOF);
X if (*regparse == ']' || *regparse == '-')
X regc(*regparse++);
X while (*regparse != '\0' && *regparse != ']') {
X if (*regparse == '-') {
X regparse++;
X if (*regparse == ']' || *regparse == '\0')
X regc('-');
X else {
X class = UCHARAT(regparse-2)+1;
X classend = UCHARAT(regparse);
X if (class > classend+1)
X FAIL("invalid [] range");
X for (; class <= classend; class++)
X regc(class);
X regparse++;
X }
X } else
X regc(*regparse++);
X }
X regc('\0');
X if (*regparse != ']')
X FAIL("unmatched []");
X regparse++;
X *flagp |= HASWIDTH|SIMPLE;
X }
X break;
X case '(':
X ret = reg(1, &flags);
X if (ret == NULL)
X return(NULL);
X *flagp |= flags&(HASWIDTH|SPSTART);
X break;
X case '\0':
X case '|':
X case ')':
X FAIL("internal urp"); /* Supposed to be caught earlier. */
X break;
X case '?':
X case '+':
X case '*':
X FAIL("?+* follows nothing");
X break;
X case '\\':
X if (*regparse == '\0')
X FAIL("trailing \\");
X ret = regnode(EXACTLY);
X regc(*regparse++);
X regc('\0');
X *flagp |= HASWIDTH|SIMPLE;
X break;
X default: {
X register int len;
X register char ender;
X
X regparse--;
X len = strcspn(regparse, META);
X if (len <= 0)
X FAIL("internal disaster");
X ender = *(regparse+len);
X if (len > 1 && ISMULT(ender))
X len--; /* Back off clear of ?+* operand. */
X *flagp |= HASWIDTH;
X if (len == 1)
X *flagp |= SIMPLE;
X ret = regnode(EXACTLY);
X while (len > 0) {
X regc(*regparse++);
X len--;
X }
X regc('\0');
X }
X break;
X }
X
X return(ret);
X}
X
X/*
X - regnode - emit a node
X */
Xstatic char * /* Location. */
Xregnode(op)
Xchar op;
X{
X register char *ret;
X register char *ptr;
X
X ret = regcode;
X if (ret == ®dummy) {
X regsize += 3;
X return(ret);
X }
X
X ptr = ret;
X *ptr++ = op;
X *ptr++ = '\0'; /* Null "next" pointer. */
X *ptr++ = '\0';
X regcode = ptr;
X
X return(ret);
X}
X
X/*
X - regc - emit (if appropriate) a byte of code
X */
Xstatic void
Xregc(b)
Xchar b;
X{
X if (regcode != ®dummy)
X *regcode++ = b;
X else
X regsize++;
X}
X
X/*
X - reginsert - insert an operator in front of already-emitted operand
X *
X * Means relocating the operand.
X */
Xstatic void
Xreginsert(op, opnd)
Xchar op;
Xchar *opnd;
X{
X register char *src;
X register char *dst;
X register char *place;
X
X if (regcode == ®dummy) {
X regsize += 3;
X return;
X }
X
X src = regcode;
X regcode += 3;
X dst = regcode;
X while (src > opnd)
X *--dst = *--src;
X
X place = opnd; /* Op node, where operand used to be. */
X *place++ = op;
X *place++ = '\0';
X *place++ = '\0';
X}
X
X/*
X - regtail - set the next-pointer at the end of a node chain
X */
Xstatic void
Xregtail(p, val)
Xchar *p;
Xchar *val;
X{
X register char *scan;
X register char *temp;
X register int offset;
X
X if (p == ®dummy)
X return;
X
X /* Find last node. */
X scan = p;
X for (;;) {
X temp = regnext(scan);
X if (temp == NULL)
X break;
X scan = temp;
X }
X
X if (OP(scan) == BACK)
X offset = scan - val;
X else
X offset = val - scan;
X *(scan+1) = (offset>>8)&0377;
X *(scan+2) = offset&0377;
X}
X
X/*
X - regoptail - regtail on operand of first argument; nop if operandless
X */
Xstatic void
Xregoptail(p, val)
Xchar *p;
Xchar *val;
X{
X /* "Operandless" and "op != BRANCH" are synonymous in practice. */
X if (p == NULL || p == ®dummy || OP(p) != BRANCH)
X return;
X regtail(OPERAND(p), val);
X}
X
X/*
X * regexec and friends
X */
X
X/*
X * Global work variables for regexec().
X */
Xstatic char *reginput; /* String-input pointer. */
Xstatic char *regbol; /* Beginning of input, for ^ check. */
Xstatic char **regstartp; /* Pointer to startp array. */
Xstatic char **regendp; /* Ditto for endp. */
X
X/*
X * Forwards.
X */
XSTATIC int regtry();
XSTATIC int regmatch();
XSTATIC int regrepeat();
X
X#ifdef DEBUG
Xint regnarrate = 0;
Xvoid regdump();
XSTATIC char *regprop();
X#endif
X
X/*
X - regexec - match a regexp against a string
X */
Xint
Xregexec(prog, string)
Xregister regexp *prog;
Xregister char *string;
X{
X register char *s;
X extern char *strchr();
X
X /* Be paranoid... */
X if (prog == NULL || string == NULL) {
X regerror("NULL parameter");
X return(0);
X }
X
X /* Check validity of program. */
X if (UCHARAT(prog->program) != MAGIC) {
X regerror("corrupted program");
X return(0);
X }
X
X /* If there is a "must appear" string, look for it. */
X if (prog->regmust != NULL) {
X s = string;
X while ((s = strchr(s, prog->regmust[0])) != NULL) {
X if (strncmp(s, prog->regmust, prog->regmlen) == 0)
X break; /* Found it. */
X s++;
X }
X if (s == NULL) /* Not present. */
X return(0);
X }
X
X /* Mark beginning of line for ^ . */
X regbol = string;
X
X /* Simplest case: anchored match need be tried only once. */
X if (prog->reganch)
X return(regtry(prog, string));
X
X /* Messy cases: unanchored match. */
X s = string;
X if (prog->regstart != '\0')
X /* We know what char it must start with. */
X while ((s = strchr(s, prog->regstart)) != NULL) {
X if (regtry(prog, s))
X return(1);
X s++;
X }
X else
X /* We don't -- general case. */
X do {
X if (regtry(prog, s))
X return(1);
X } while (*s++ != '\0');
X
X /* Failure. */
X return(0);
X}
X
X/*
X - regtry - try match at specific point
X */
Xstatic int /* 0 failure, 1 success */
Xregtry(prog, string)
Xregexp *prog;
Xchar *string;
X{
X register int i;
X register char **sp;
X register char **ep;
X
X reginput = string;
X regstartp = prog->startp;
X regendp = prog->endp;
X
X sp = prog->startp;
X ep = prog->endp;
X for (i = NSUBEXP; i > 0; i--) {
X *sp++ = NULL;
X *ep++ = NULL;
X }
X if (regmatch(prog->program + 1)) {
X prog->startp[0] = string;
X prog->endp[0] = reginput;
X return(1);
X } else
X return(0);
X}
X
X/*
X - regmatch - main matching routine
X *
X * Conceptually the strategy is simple: check to see whether the current
X * node matches, call self recursively to see whether the rest matches,
X * and then act accordingly. In practice we make some effort to avoid
X * recursion, in particular by going through "ordinary" nodes (that don't
X * need to know whether the rest of the match failed) by a loop instead of
X * by recursion.
X */
Xstatic int /* 0 failure, 1 success */
Xregmatch(prog)
Xchar *prog;
X{
X register char *scan; /* Current node. */
X char *next; /* Next node. */
X extern char *strchr();
X
X scan = prog;
X#ifdef DEBUG
X if (scan != NULL && regnarrate)
X fprintf(stderr, "%s(\n", regprop(scan));
X#endif
X while (scan != NULL) {
X#ifdef DEBUG
X if (regnarrate)
X fprintf(stderr, "%s...\n", regprop(scan));
X#endif
X next = regnext(scan);
X
X switch (OP(scan)) {
X case BOL:
X if (reginput != regbol)
X return(0);
X break;
X case EOL:
X if (*reginput != '\0')
X return(0);
X break;
X case ANY:
X if (*reginput == '\0')
X return(0);
X reginput++;
X break;
X case EXACTLY: {
X register int len;
X register char *opnd;
X
X opnd = OPERAND(scan);
X /* Inline the first character, for speed. */
X if (*opnd != *reginput)
X return(0);
X len = strlen(opnd);
X if (len > 1 && strncmp(opnd, reginput, len) != 0)
X return(0);
X reginput += len;
X }
X break;
X case ANYOF:
X if (strchr(OPERAND(scan), *reginput) == NULL)
X return(0);
X reginput++;
X break;
X case ANYBUT:
X if (strchr(OPERAND(scan), *reginput) != NULL)
X return(0);
X reginput++;
X break;
X case NOTHING:
X break;
X case BACK:
X break;
X case OPEN+1:
X case OPEN+2:
X case OPEN+3:
X case OPEN+4:
X case OPEN+5:
X case OPEN+6:
X case OPEN+7:
X case OPEN+8:
X case OPEN+9: {
X register int no;
X register char *save;
X
X no = OP(scan) - OPEN;
X save = reginput;
X
X if (regmatch(next)) {
X /*
X * Don't set startp if some later
X * invocation of the same parentheses
X * already has.
X */
X if (regstartp[no] == NULL)
X regstartp[no] = save;
X return(1);
X } else
X return(0);
X }
X break;
X case CLOSE+1:
X case CLOSE+2:
X case CLOSE+3:
X case CLOSE+4:
X case CLOSE+5:
X case CLOSE+6:
X case CLOSE+7:
X case CLOSE+8:
X case CLOSE+9: {
X register int no;
X register char *save;
X
X no = OP(scan) - CLOSE;
X save = reginput;
X
X if (regmatch(next)) {
X /*
X * Don't set endp if some later
X * invocation of the same parentheses
X * already has.
X */
X if (regendp[no] == NULL)
X regendp[no] = save;
X return(1);
X } else
X return(0);
X }
X break;
X case BRANCH: {
X register char *save;
X
X if (OP(next) != BRANCH) /* No choice. */
X next = OPERAND(scan); /* Avoid recursion. */
X else {
X do {
X save = reginput;
X if (regmatch(OPERAND(scan)))
X return(1);
X reginput = save;
X scan = regnext(scan);
X } while (scan != NULL && OP(scan) == BRANCH);
X return(0);
X /* NOTREACHED */
X }
X }
X break;
X case STAR:
X case PLUS: {
X register char nextch;
X register int no;
X register char *save;
X register int min;
X
X /*
X * Lookahead to avoid useless match attempts
X * when we know what character comes next.
X */
X nextch = '\0';
X if (OP(next) == EXACTLY)
X nextch = *OPERAND(next);
X min = (OP(scan) == STAR) ? 0 : 1;
X save = reginput;
X no = regrepeat(OPERAND(scan));
X while (no >= min) {
X /* If it could work, try it. */
X if (nextch == '\0' || *reginput == nextch)
X if (regmatch(next))
X return(1);
X /* Couldn't or didn't -- back up. */
X no--;
X reginput = save + no;
X }
X return(0);
X }
X break;
X case END:
X return(1); /* Success! */
X break;
X default:
X regerror("memory corruption");
X return(0);
X break;
X }
X
X scan = next;
X }
X
X /*
X * We get here only if there's trouble -- normally "case END" is
X * the terminating point.
X */
X regerror("corrupted pointers");
X return(0);
X}
X
X/*
X - regrepeat - repeatedly match something simple, report how many
X */
Xstatic int
Xregrepeat(p)
Xchar *p;
X{
X register int count = 0;
X register char *scan;
X register char *opnd;
X
X scan = reginput;
X opnd = OPERAND(p);
X switch (OP(p)) {
X case ANY:
X count = strlen(scan);
X scan += count;
X break;
X case EXACTLY:
X while (*opnd == *scan) {
X count++;
X scan++;
X }
X break;
X case ANYOF:
X while (*scan != '\0' && strchr(opnd, *scan) != NULL) {
X count++;
X scan++;
X }
X break;
X case ANYBUT:
X while (*scan != '\0' && strchr(opnd, *scan) == NULL) {
X count++;
X scan++;
X }
X break;
X default: /* Oh dear. Called inappropriately. */
X regerror("internal foulup");
X count = 0; /* Best compromise. */
X break;
X }
X reginput = scan;
X
X return(count);
X}
X
X/*
X - regnext - dig the "next" pointer out of a node
X */
Xstatic char *
Xregnext(p)
Xregister char *p;
X{
X register int offset;
X
X if (p == ®dummy)
X return(NULL);
X
X offset = NEXT(p);
X if (offset == 0)
X return(NULL);
X
X if (OP(p) == BACK)
X return(p-offset);
X else
X return(p+offset);
X}
X
X#ifdef DEBUG
X
XSTATIC char *regprop();
X
X/*
X - regdump - dump a regexp onto stdout in vaguely comprehensible form
X */
Xvoid
Xregdump(r)
Xregexp *r;
X{
X register char *s;
X register char op = EXACTLY; /* Arbitrary non-END op. */
X register char *next;
X extern char *strchr();
X
X
X s = r->program + 1;
X while (op != END) { /* While that wasn't END last time... */
X op = OP(s);
X printf("%2d%s", s-r->program, regprop(s)); /* Where, what. */
X next = regnext(s);
X if (next == NULL) /* Next ptr. */
X printf("(0)");
X else
X printf("(%d)", (s-r->program)+(next-s));
X s += 3;
X if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
X /* Literal string, where present. */
X while (*s != '\0') {
X putchar(*s);
X s++;
X }
X s++;
X }
X putchar('\n');
X }
X
X /* Header fields of interest. */
X if (r->regstart != '\0')
X printf("start `%c' ", r->regstart);
X if (r->reganch)
X printf("anchored ");
X if (r->regmust != NULL)
X printf("must have \"%s\"", r->regmust);
X printf("\n");
X}
X
X/*
X - regprop - printable representation of opcode
X */
Xstatic char *
Xregprop(op)
Xchar *op;
X{
X register char *p;
X static char buf[50];
X
X (void) strcpy(buf, ":");
X
X switch (OP(op)) {
X case BOL:
X p = "BOL";
X break;
X case EOL:
X p = "EOL";
X break;
X case ANY:
X p = "ANY";
X break;
X case ANYOF:
X p = "ANYOF";
X break;
X case ANYBUT:
X p = "ANYBUT";
X break;
X case BRANCH:
X p = "BRANCH";
X break;
X case EXACTLY:
X p = "EXACTLY";
X break;
X case NOTHING:
X p = "NOTHING";
X break;
X case BACK:
X p = "BACK";
X break;
X case END:
X p = "END";
X break;
X case OPEN+1:
X case OPEN+2:
X case OPEN+3:
X case OPEN+4:
X case OPEN+5:
X case OPEN+6:
X case OPEN+7:
X case OPEN+8:
X case OPEN+9:
X sprintf(buf+strlen(buf), "OPEN%d", OP(op)-OPEN);
X p = NULL;
X break;
X case CLOSE+1:
X case CLOSE+2:
X case CLOSE+3:
X case CLOSE+4:
X case CLOSE+5:
X case CLOSE+6:
X case CLOSE+7:
X case CLOSE+8:
X case CLOSE+9:
X sprintf(buf+strlen(buf), "CLOSE%d", OP(op)-CLOSE);
X p = NULL;
X break;
X case STAR:
X p = "STAR";
X break;
X case PLUS:
X p = "PLUS";
X break;
X default:
X regerror("corrupted opcode");
X break;
X }
X if (p != NULL)
X (void) strcat(buf, p);
X return(buf);
X}
X#endif
X
X/*
X * The following is provided for those people who do not have strcspn() in
X * their C libraries. They should get off their butts and do something
X * about it; at least one public-domain implementation of those (highly
X * useful) string routines has been published on Usenet.
X */
X#ifdef STRCSPN
X/*
X * strcspn - find length of initial segment of s1 consisting entirely
X * of characters not from s2
X */
X
Xstatic int
Xstrcspn(s1, s2)
Xchar *s1;
Xchar *s2;
X{
X register char *scan1;
X register char *scan2;
X register int count;
X
X count = 0;
X for (scan1 = s1; *scan1 != '\0'; scan1++) {
X for (scan2 = s2; *scan2 != '\0';) /* ++ moved down. */
X if (*scan1 == *scan2++)
X return(count);
X count++;
X }
X return(count);
X}
X#endif
!
echo regsub.c:
sed 's/^X//' >regsub.c <<'!'
X/*
X * regsub
X *
X * Copyright (c) 1986 by University of Toronto.
X * Written by Henry Spencer. Not derived from licensed software.
X *
X * Permission is granted to anyone to use this software for any
X * purpose on any computer system, and to redistribute it freely,
X * subject to the following restrictions:
X *
X * 1. The author is not responsible for the consequences of use of
X * this software, no matter how awful, even if they arise
X * from defects in it.
X *
X * 2. The origin of this software must not be misrepresented, either
X * by explicit claim or by omission.
X *
X * 3. Altered versions must be plainly marked as such, and must not
X * be misrepresented as being the original software.
X */
X#include <stdio.h>
X#include <regexp.h>
X#include "regmagic.h"
X
X#ifndef CHARBITS
X#define UCHARAT(p) ((int)*(unsigned char *)(p))
X#else
X#define UCHARAT(p) ((int)*(p)&CHARBITS)
X#endif
X
X/*
X - regsub - perform substitutions after a regexp match
X */
Xvoid
Xregsub(prog, source, dest)
Xregexp *prog;
Xchar *source;
Xchar *dest;
X{
X register char *src;
X register char *dst;
X register char c;
X register int no;
X register int len;
X extern char *strncpy();
X
X if (prog == NULL || source == NULL || dest == NULL) {
X regerror("NULL parm to regsub");
X return;
X }
X if (UCHARAT(prog->program) != MAGIC) {
X regerror("damaged regexp fed to regsub");
X return;
X }
X
X src = source;
X dst = dest;
X while ((c = *src++) != '\0') {
X if (c == '&')
X no = 0;
X else if (c == '\\' && '0' <= *src && *src <= '9')
X no = *src++ - '0';
X else
X no = -1;
X
X if (no < 0) /* Ordinary character. */
X *dst++ = c;
X else if (prog->startp[no] != NULL && prog->endp[no] != NULL) {
X len = prog->endp[no] - prog->startp[no];
X (void) strncpy(dst, prog->startp[no], len);
X dst += len;
X if (*(dst-1) == '\0') { /* strncpy hit NUL. */
X regerror("damaged match string");
X return;
X }
X }
X }
X *dst++ = '\0';
X}
!
echo regerror.c:
sed 's/^X//' >regerror.c <<'!'
X#include <stdio.h>
X
Xvoid
Xregerror(s)
Xchar *s;
X{
X#ifdef ERRAVAIL
X error("regexp: %s", s);
X#else
X fprintf(stderr, "regexp(3): %s", s);
X exit(1);
X#endif
X /* NOTREACHED */
X}
!
echo regmagic.h:
sed 's/^X//' >regmagic.h <<'!'
X/*
X * The first byte of the regexp internal "program" is actually this magic
X * number; the start node begins in the second byte.
X */
X#define MAGIC 0234
!
echo try.c:
sed 's/^X//' >try.c <<'!'
X/*
X * Simple test program for regexp(3) stuff. Knows about debugging hooks.
X *
X * Copyright (c) 1986 by University of Toronto.
X * Written by Henry Spencer. Not derived from licensed software.
X *
X * Permission is granted to anyone to use this software for any
X * purpose on any computer system, and to redistribute it freely,
X * subject to the following restrictions:
X *
X * 1. The author is not responsible for the consequences of use of
X * this software, no matter how awful, even if they arise
X * from defects in it.
X *
X * 2. The origin of this software must not be misrepresented, either
X * by explicit claim or by omission.
X *
X * 3. Altered versions must be plainly marked as such, and must not
X * be misrepresented as being the original software.
X *
X * Usage: try re [string [output [-]]]
X * The re is compiled and dumped, regexeced against the string, the result
X * is applied to output using regsub(). The - triggers a running narrative
X * from regexec(). Dumping and narrative don't happen unless DEBUG.
X *
X * If there are no arguments, stdin is assumed to be a stream of lines with
X * five fields: a r.e., a string to match it against, a result code, a
X * source string for regsub, and the proper result. Result codes are 'c'
X * for compile failure, 'y' for match success, 'n' for match failure.
X * Field separator is tab.
X */
X#include <stdio.h>
X#include <regexp.h>
X
X#ifdef ERRAVAIL
Xchar *progname;
Xextern char *mkprogname();
X#endif
X
X#ifdef DEBUG
Xextern int regnarrate;
X#endif
X
Xchar buf[BUFSIZ];
X
Xint errreport = 0; /* Report errors via errseen? */
Xchar *errseen = NULL; /* Error message. */
Xint status = 0; /* Exit status. */
X
X/* ARGSUSED */
Xmain(argc, argv)
Xint argc;
Xchar *argv[];
X{
X regexp *r;
X int i;
X
X#ifdef ERRAVAIL
X progname = mkprogname(argv[0]);
X#endif
X
X if (argc == 1) {
X multiple();
X exit(status);
X }
X
X r = regcomp(argv[1]);
X if (r == NULL)
X error("regcomp failure", "");
X#ifdef DEBUG
X regdump(r);
X if (argc > 4)
X regnarrate++;
X#endif
X if (argc > 2) {
X i = regexec(r, argv[2]);
X printf("%d", i);
X for (i = 1; i < NSUBEXP; i++)
X if (r->startp[i] != NULL && r->endp[i] != NULL)
X printf(" \\%d", i);
X printf("\n");
X }
X if (argc > 3) {
X regsub(r, argv[3], buf);
X printf("%s\n", buf);
X }
X exit(status);
X}
X
Xvoid
Xregerror(s)
Xchar *s;
X{
X if (errreport)
X errseen = s;
X else
X error(s, "");
X}
X
X#ifndef ERRAVAIL
Xerror(s1, s2)
Xchar *s1;
Xchar *s2;
X{
X fprintf(stderr, "regexp: ");
X fprintf(stderr, s1, s2);
X fprintf(stderr, "\n");
X exit(1);
X}
X#endif
X
Xint lineno;
X
Xregexp badregexp; /* Implicit init to 0. */
X
Xmultiple()
X{
X char rbuf[BUFSIZ];
X char *field[5];
X char *scan;
X int i;
X regexp *r;
X extern char *strchr();
X
X errreport = 1;
X lineno = 0;
X while (fgets(rbuf, sizeof(rbuf), stdin) != NULL) {
X rbuf[strlen(rbuf)-1] = '\0'; /* Dispense with \n. */
X lineno++;
X scan = rbuf;
X for (i = 0; i < 5; i++) {
X field[i] = scan;
X if (field[i] == NULL) {
X complain("bad testfile format", "");
X exit(1);
X }
X scan = strchr(scan, '\t');
X if (scan != NULL)
X *scan++ = '\0';
X }
X try(field);
X }
X
X /* And finish up with some internal testing... */
X lineno = 9990;
X errseen = NULL;
X if (regcomp((char *)NULL) != NULL || errseen == NULL)
X complain("regcomp(NULL) doesn't complain", "");
X lineno = 9991;
X errseen = NULL;
X if (regexec((regexp *)NULL, "foo") || errseen == NULL)
X complain("regexec(NULL, ...) doesn't complain", "");
X lineno = 9992;
X r = regcomp("foo");
X if (r == NULL) {
X complain("regcomp(\"foo\") fails", "");
X return;
X }
X lineno = 9993;
X errseen = NULL;
X if (regexec(r, (char *)NULL) || errseen == NULL)
X complain("regexec(..., NULL) doesn't complain", "");
X lineno = 9994;
X errseen = NULL;
X regsub((regexp *)NULL, "foo", rbuf);
X if (errseen == NULL)
X complain("regsub(NULL, ..., ...) doesn't complain", "");
X lineno = 9995;
X errseen = NULL;
X regsub(r, (char *)NULL, rbuf);
X if (errseen == NULL)
X complain("regsub(..., NULL, ...) doesn't complain", "");
X lineno = 9996;
X errseen = NULL;
X regsub(r, "foo", (char *)NULL);
X if (errseen == NULL)
X complain("regsub(..., ..., NULL) doesn't complain", "");
X lineno = 9997;
X errseen = NULL;
X if (regexec(&badregexp, "foo") || errseen == NULL)
X complain("regexec(nonsense, ...) doesn't complain", "");
X lineno = 9998;
X errseen = NULL;
X regsub(&badregexp, "foo", rbuf);
X if (errseen == NULL)
X complain("regsub(nonsense, ..., ...) doesn't complain", "");
X}
X
Xtry(fields)
Xchar **fields;
X{
X regexp *r;
X char dbuf[BUFSIZ];
X
X errseen = NULL;
X r = regcomp(fields[0]);
X if (r == NULL) {
X if (*fields[2] != 'c')
X complain("regcomp failure in `%s'", fields[0]);
X return;
X }
X if (*fields[2] == 'c') {
X complain("unexpected regcomp success in `%s'", fields[0]);
X free((char *)r);
X return;
X }
X if (!regexec(r, fields[1])) {
X if (*fields[2] != 'n')
X complain("regexec failure in `%s'", "");
X free((char *)r);
X return;
X }
X if (*fields[2] == 'n') {
X complain("unexpected regexec success", "");
X free((char *)r);
X return;
X }
X errseen = NULL;
X regsub(r, fields[3], dbuf);
X if (errseen != NULL) {
X complain("regsub complaint", "");
X free((char *)r);
X return;
X }
X if (strcmp(dbuf, fields[4]) != 0)
X complain("regsub result `%s' wrong", dbuf);
X free((char *)r);
X}
X
Xcomplain(s1, s2)
Xchar *s1;
Xchar *s2;
X{
X fprintf(stderr, "try: %d: ", lineno);
X fprintf(stderr, s1, s2);
X fprintf(stderr, " (%s)\n", (errseen != NULL) ? errseen : "");
X status = 1;
X}
!
echo timer.c:
sed 's/^X//' >timer.c <<'!'
X/*
X * Simple timing program for regcomp().
X *
X * Copyright (c) 1986 by University of Toronto.
X * Written by Henry Spencer. Not derived from licensed software.
X *
X * Permission is granted to anyone to use this software for any
X * purpose on any computer system, and to redistribute it freely,
X * subject to the following restrictions:
X *
X * 1. The author is not responsible for the consequences of use of
X * this software, no matter how awful, even if they arise
X * from defects in it.
X *
X * 2. The origin of this software must not be misrepresented, either
X * by explicit claim or by omission.
X *
X * 3. Altered versions must be plainly marked as such, and must not
X * be misrepresented as being the original software.
X *
X * Usage: timer ncomp nexec nsub
X * or
X * timer ncomp nexec nsub regexp string [ answer [ sub ] ]
X *
X * The second form is for timing repetitions of a single test case.
X * The first form's test data is a compiled-in copy of the "tests" file.
X * Ncomp, nexec, nsub are how many times to do each regcomp, regexec,
X * and regsub. The way to time an operation individually is to do something
X * like "timer 1 50 1".
X */
X#include <stdio.h>
X
Xstruct try {
X char *re, *str, *ans, *src, *dst;
X} tests[] = {
X#include "timer.t.h"
X{ NULL, NULL, NULL, NULL, NULL }
X};
X
X#include <regexp.h>
X
Xint errreport = 0; /* Report errors via errseen? */
Xchar *errseen = NULL; /* Error message. */
X
Xchar *progname;
X
X/* ARGSUSED */
Xmain(argc, argv)
Xint argc;
Xchar *argv[];
X{
X int ncomp, nexec, nsub;
X struct try one;
X char dummy[512];
X
X if (argc < 4) {
X ncomp = 1;
X nexec = 1;
X nsub = 1;
X } else {
X ncomp = atoi(argv[1]);
X nexec = atoi(argv[2]);
X nsub = atoi(argv[3]);
X }
X
X progname = argv[0];
X if (argc > 5) {
X one.re = argv[4];
X one.str = argv[5];
X if (argc > 6)
X one.ans = argv[6];
X else
X one.ans = "y";
X if (argc > 7) {
X one.src = argv[7];
X one.dst = "xxx";
X } else {
X one.src = "x";
X one.dst = "x";
X }
X errreport = 1;
X try(one, ncomp, nexec, nsub);
X } else
X multiple(ncomp, nexec, nsub);
X exit(0);
X}
X
Xvoid
Xregerror(s)
Xchar *s;
X{
X if (errreport)
X errseen = s;
X else
X error(s, "");
X}
X
X#ifndef ERRAVAIL
Xerror(s1, s2)
Xchar *s1;
Xchar *s2;
X{
X fprintf(stderr, "regexp: ");
X fprintf(stderr, s1, s2);
X fprintf(stderr, "\n");
X exit(1);
X}
X#endif
X
Xint lineno = 0;
X
Xmultiple(ncomp, nexec, nsub)
Xint ncomp, nexec, nsub;
X{
X register int i;
X extern char *strchr();
X
X errreport = 1;
X for (i = 0; tests[i].re != NULL; i++) {
X lineno++;
X try(tests[i], ncomp, nexec, nsub);
X }
X}
X
Xtry(fields, ncomp, nexec, nsub)
Xstruct try fields;
Xint ncomp, nexec, nsub;
X{
X regexp *r;
X char dbuf[BUFSIZ];
X register int i;
X
X errseen = NULL;
X r = regcomp(fields.re);
X if (r == NULL) {
X if (*fields.ans != 'c')
X complain("regcomp failure in `%s'", fields.re);
X return;
X }
X if (*fields.ans == 'c') {
X complain("unexpected regcomp success in `%s'", fields.re);
X free((char *)r);
X return;
X }
X for (i = ncomp-1; i > 0; i--) {
X free((char *)r);
X r = regcomp(fields.re);
X }
X if (!regexec(r, fields.str)) {
X if (*fields.ans != 'n')
X complain("regexec failure in `%s'", "");
X free((char *)r);
X return;
X }
X if (*fields.ans == 'n') {
X complain("unexpected regexec success", "");
X free((char *)r);
X return;
X }
X for (i = nexec-1; i > 0; i--)
X (void) regexec(r, fields.str);
X errseen = NULL;
X for (i = nsub; i > 0; i--)
X regsub(r, fields.src, dbuf);
X if (errseen != NULL) {
X complain("regsub complaint", "");
X free((char *)r);
X return;
X }
X if (strcmp(dbuf, fields.dst) != 0)
X complain("regsub result `%s' wrong", dbuf);
X free((char *)r);
X}
X
Xcomplain(s1, s2)
Xchar *s1;
Xchar *s2;
X{
X fprintf(stderr, "try: %d: ", lineno);
X fprintf(stderr, s1, s2);
X fprintf(stderr, " (%s)\n", (errseen != NULL) ? errseen : "");
X}
!
echo tests:
sed 's/^X//' >tests <<'!'
Xabc abc y & abc
Xabc xbc n - -
Xabc axc n - -
Xabc abx n - -
Xabc xabcy y & abc
Xabc ababc y & abc
Xab*c abc y & abc
Xab*bc abc y & abc
Xab*bc abbc y & abbc
Xab*bc abbbbc y & abbbbc
Xab+bc abbc y & abbc
Xab+bc abc n - -
Xab+bc abq n - -
Xab+bc abbbbc y & abbbbc
Xab?bc abbc y & abbc
Xab?bc abc y & abc
Xab?bc abbbbc n - -
Xab?c abc y & abc
X^abc$ abc y & abc
X^abc$ abcc n - -
X^abc abcc y & abc
X^abc$ aabc n - -
Xabc$ aabc y & abc
X^ abc y &
X$ abc y &
Xa.c abc y & abc
Xa.c axc y & axc
Xa.*c axyzc y & axyzc
Xa.*c axyzd n - -
Xa[bc]d abc n - -
Xa[bc]d abd y & abd
Xa[b-d]e abd n - -
Xa[b-d]e ace y & ace
Xa[b-d] aac y & ac
Xa[-b] a- y & a-
Xa[b-] a- y & a-
Xa[b-a] - c - -
Xa[]b - c - -
Xa[ - c - -
Xa] a] y & a]
Xa[]]b a]b y & a]b
Xa[^bc]d aed y & aed
Xa[^bc]d abd n - -
Xa[^-b]c adc y & adc
Xa[^-b]c a-c n - -
Xa[^]b]c a]c n - -
Xa[^]b]c adc y & adc
Xab|cd abc y & ab
Xab|cd abcd y & ab
X()ef def y &-\1 ef-
X()* - c - -
X*a - c - -
X^* - c - -
X$* - c - -
X(*)b - c - -
X$b b n - -
Xa\ - c - -
Xa\(b a(b y &-\1 a(b-
Xa\(*b ab y & ab
Xa\(*b a((b y & a((b
Xa\\b a\b y & a\b
Xabc) - c - -
X(abc - c - -
X((a)) abc y &-\1-\2 a-a-a
X(a)b(c) abc y &-\1-\2 abc-a-c
Xa+b+c aabbabc y & abc
Xa** - c - -
Xa*? - c - -
X(a*)* - c - -
X(a*)+ - c - -
X(a|)* - c - -
X(a*|b)* - c - -
X(a+|b)* ab y &-\1 ab-b
X(a+|b)+ ab y &-\1 ab-b
X(a+|b)? ab y &-\1 a-a
X[^ab]* cde y & cde
X(^)* - c - -
X(ab|)* - c - -
X)( - c - -
X abc y &
Xabc n - -
Xa* y &
X([abc])*d abbbcd y &-\1 abbbcd-c
X([abc])*bcd abcd y &-\1 abcd-a
Xa|b|c|d|e e y & e
X(a|b|c|d|e)f ef y &-\1 ef-e
X((a*|b))* - c - -
Xabcd*efg abcdefg y & abcdefg
Xab* xabyabbbz y & ab
Xab* xayabbbz y & a
X(ab|cd)e abcde y &-\1 cde-cd
X[abhgefdc]ij hij y & hij
X^(ab|cd)e abcde n x\1y xy
X(abc|)ef abcdef y &-\1 ef-
X(a|b)c*d abcd y &-\1 bcd-b
X(ab|ab*)bc abc y &-\1 abc-a
Xa([bc]*)c* abc y &-\1 abc-bc
Xa([bc]*)(c*d) abcd y &-\1-\2 abcd-bc-d
Xa([bc]+)(c*d) abcd y &-\1-\2 abcd-bc-d
Xa([bc]*)(c+d) abcd y &-\1-\2 abcd-b-cd
Xa[bcd]*dcdcde adcdcde y & adcdcde
Xa[bcd]+dcdcde adcdcde n - -
X(ab|a)b*c abc y &-\1 abc-ab
X((a)(b)c)(d) abcd y \1-\2-\3-\4 abc-a-b-d
X[a-zA-Z_][a-zA-Z0-9_]* alpha y & alpha
X^a(bc+|b[eh])g|.h$ abh y &-\1 bh-
X(bc+d$|ef*g.|h?i(j|k)) effgz y &-\1-\2 effgz-effgz-
X(bc+d$|ef*g.|h?i(j|k)) ij y &-\1-\2 ij-ij-j
X(bc+d$|ef*g.|h?i(j|k)) effg n - -
X(bc+d$|ef*g.|h?i(j|k)) bcdd n - -
X(bc+d$|ef*g.|h?i(j|k)) reffgz y &-\1-\2 effgz-effgz-
X((((((((((a)))))))))) - c - -
X(((((((((a))))))))) a y & a
Xmultiple words of text uh-uh n - -
Xmultiple words multiple words, yeah y & multiple words
X(.*)c(.*) abcde y &-\1-\2 abcde-ab-de
X\((.*), (.*)\) (a, b) y (\2, \1) (b, a)
!
echo done
exit 0
Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP
Path: utzoo!decvax!genrad!mit-eddie!mirror!sources-request
From: sources-requ...@mirror.UUCP
Newsgroups: mod.sources
Subject: v06i043: X3J11/SVID/4BSD/etc string library (stringlib)
Message-ID: <125@mirror.UUCP>
Date: Tue, 8-Jul-86 17:35:35 EDT
Article-I.D.: mirror.125
Posted: Tue Jul 8 17:35:35 1986
Date-Received: Tue, 8-Jul-86 23:50:10 EDT
Sender: r...@mirror.UUCP
Lines: 1515
Approved: r...@mirror.UUCP
Submitted by: ihnp4!utzoo!henry (Henry Spencer)
Mod.sources: Volume 6, Issue 43
Archive-name: stringlib
[ This is an update of the string library Henry posted to net.sources
some time ago. It is different from a recent library published in
volume 4 in these two respects:
1. It comes with a fairly exhaustive test program, which it passes.
2. It does not invent new functions; it implements the union of those
described in X3J11, the SVID, etc., and nothing else.
It would be nice if everyone -- vendors, users -- put the "missing"
functions into their C library, and we could all live in harmony,
but I suspect that's wishful thinking. (Yeah, yeah: efficiency, too.)
This is also excempted from my mandatory manpage requirement, for
reasons mentioned and alluded to in the second paragraph of the README
file. --r$ ]
------------------
echo README:
sed 's/^X//' >README <<'!'
XThis is a public-domain reimplementation of string(3) and friends, notably
Xmemory(3) and bstring(3) (except ffs). Not derived from licensed software.
XThis code may be used on any computer system for any purpose by anyone.
X
XRelative to my old net.sources posting, this one adds some functions and
Xfixes one or two obscure bugs. There has been another string library
Xposted in recent times, with many more functions; I haven't inspected it
Xand can't comment on its relationship to mine. Alas, the manual pages
Xfor this stuff are copyright by various people other than me, so I can't
Xinclude them. See your local Unix manuals.
X
XThis distribution implements precisely the union of the string functions
Xof the SVID, 4BSD, X3J11, and V7. Included is a large test program that
Xexercises everything quite thoroughly. (Note that some existing libraries,
Xincluding e.g. V7, flunk one or more of these tests.)
X
XIn the event of conflict between the definitions from various places, the
Xnewer or more portable one is chosen. That is, X3J11 overrules the SVID,
Xwhich in turn overrules older Unixes.
X
XThe code is written for maximal portability. Some efficiency has been
Xsacrificed in the cause of meticulously avoiding possible portability
Xproblems. For example, this code never assumes that a pointer can be
Xmoved past the end of an array and then backed up. Many of these functions
Xcan be implemented more efficiently if machine-dependent assumptions are
Xmade; memcpy is a particular glaring case.
X
XSimplistically: put this stuff into a source directory, inspect Makefile
Xfor compilation options that need changing to suit your local environment,
Xand then do "make r". This compiles the functions and the test program and
Xruns the tests. If there are no complaints, put string.h in /usr/include
X(you may also want to "make memory.h" and put it in /usr/include) and add
Xthe functions (*.o except for tester.o) to your C library. The internal
Xinterdependencies are:
X
X index needs strchr
X rindex needs strrchr
X bcopy needs memcpy
X bcmp needs memcmp
X bzero needs memset
X
XI haven't included an implementation of Berkeley's ffs function partly
Xbecause it's not trivial to do in a portable way, and partly because I
Xdon't really see it as a string function.
X
XA weakness in the tester program is that it uses quite short strings for
Xeverything, and pays no real attention to alignment issues. Optimized
Ximplementations of things like memcpy would need a more elaborate set of
Xtest cases to put them through their full paces.
X
X Henry Spencer @ U of Toronto Zoology
X {allegra,ihnp4,decvax,pyramid}!utzoo!henry
X Wed Jun 25 19:21:34 EDT 1986
!
echo Makefile:
sed 's/^X//' >Makefile <<'!'
X# String library.
X
X# Configuration settings: how should "size_t", "void *", "const" be written?
X# "size_t" is what's needed to hold the result of sizeof; beware of problems
X# with compatibility here, because X3J11 uses this for e.g. the third
X# argument of strncpy() as well. You may need to make it "int" even if
X# this is a lie. "void *" is the generic pointer type, "char *" in most
X# existing implementations. "const" is the keyword marking read-only
X# variables and parameters, unimplemented in most existing implementations.
X# These things need to be defined this way because they must be fitted into
X# both the .h files and the .c files; see the make instructions for string.h
X# farther down.
XSIZET = int
XVOIDSTAR = char *
XLVOIDSTAR = char* # Lint shell file has problems with * alone. Barf.
XCONST =
X
XCONF = -DSIZET=$(SIZET) -DVOIDSTAR='$(VOIDSTAR)' -DCONST='$(CONST)'
XLCONF = -DSIZET=$(SIZET) -DVOIDSTAR='$(LVOIDSTAR)' -DCONST='$(CONST)'
X
X# Things you might want to put in CFLAGS or LINTFLAGS.
X# -DCHARBITS=0377 Required if compiler lacks "unsigned char".
X# -Dvoid=int Required if compiler lacks "void".
X# -DUNIXERR Unix-like errno stuff, can test strerror().
X# -DBERKERR Like UNIXERR but for Berklix (4BSD).
X# -I. string.h from here, not /usr/include.
X
XCFLAGS = -O $(CONF) -DUNIXERR -I.
XLINTFLAGS = -hpan $(LCONF) -DUNIXERR -Dvoid=int -DCHARBITS=0377 -I.
XLDFLAGS = -i
X
X# Name lists.
XSTRING = index.o rindex.o strcat.o strchr.o strcmp.o strcpy.o strcspn.o \
X strlen.o strncat.o strncmp.o strncpy.o strpbrk.o strrchr.o strspn.o \
X strtok.o strstr.o memcpy.o memccpy.o memcmp.o memchr.o memset.o \
X bcopy.o bcmp.o bzero.o strerror.o
XCSTRING = index.c rindex.c strcat.c strchr.c strcmp.c strcpy.c strcspn.c \
X strlen.c strncat.c strncmp.c strncpy.c strpbrk.c strrchr.c strspn.c \
X strtok.c strstr.c memcpy.c memccpy.c memcmp.c memchr.c memset.c \
X bcopy.c bcmp.c bzero.c strerror.c
XDTR = README Makefile $(CSTRING) tester.c string.h.proto
X
X# Locations, for installation (somewhat system-dependent).
XDEST=..
X
Xtester.o: string.h
X
Xmv: $(STRING)
X mv $(STRING) $(DEST)
X
Xr: tester
X @echo 'No news is good news. Note: strerror() test is VERY system-dependent.'
X tester
X
Xtester: tester.o $(STRING)
X cc $(LDFLAGS) tester.o $(STRING) -o tester
X
Xstring.h: string.h.proto
X sed 's/SIZET/$(SIZET)/g;s/VOIDSTAR /$(VOIDSTAR)/g' string.h.proto >string.h
X
Xmemory.h: string.h
X egrep mem string.h >memory.h
X
Xlint: string.h
X lint $(LINTFLAGS) tester.c $(CSTRING)
X
Xclean:
X rm -f tester a.out *.o string.h memory.h dtr
X
Xdtr: $(DTR)
X makedtr $(DTR) >dtr
!
echo index.c:
sed 's/^X//' >index.c <<'!'
X/*
X * index - find first occurrence of a character in a string
X */
X
X#define NULL 0
X
Xchar * /* found char, or NULL if none */
Xindex(s, charwanted)
XCONST char *s;
Xchar charwanted;
X{
X extern char *strchr();
X
X return(strchr(s, charwanted));
X}
!
echo rindex.c:
sed 's/^X//' >rindex.c <<'!'
X/*
X * rindex - find last occurrence of a character in a string
X */
X
X#define NULL 0
X
Xchar * /* found char, or NULL if none */
Xrindex(s, charwanted)
XCONST char *s;
Xchar charwanted;
X{
X extern char *strrchr();
X
X return(strrchr(s, charwanted));
X}
!
echo strcat.c:
sed 's/^X//' >strcat.c <<'!'
X/*
X * strcat - append string src to dst
X */
Xchar * /* dst */
Xstrcat(dst, src)
Xchar *dst;
XCONST char *src;
X{
X register char *dscan;
X register CONST char *sscan;
X
X for (dscan = dst; *dscan != '\0'; dscan++)
X continue;
X sscan = src;
X while ((*dscan++ = *sscan++) != '\0')
X continue;
X return(dst);
X}
!
echo strchr.c:
sed 's/^X//' >strchr.c <<'!'
X/*
X * strchr - find first occurrence of a character in a string
X */
X
X#define NULL 0
X
Xchar * /* found char, or NULL if none */
Xstrchr(s, charwanted)
XCONST char *s;
Xregister char charwanted;
X{
X register CONST char *scan;
X
X /*
X * The odd placement of the two tests is so NUL is findable.
X */
X for (scan = s; *scan != charwanted;) /* ++ moved down for opt. */
X if (*scan++ == '\0')
X return(NULL);
X return(scan);
X}
!
echo strcmp.c:
sed 's/^X//' >strcmp.c <<'!'
X/*
X * strcmp - compare string s1 to s2
X */
X
Xint /* <0 for <, 0 for ==, >0 for > */
Xstrcmp(s1, s2)
XCONST char *s1;
XCONST char *s2;
X{
X register CONST char *scan1;
X register CONST char *scan2;
X
X scan1 = s1;
X scan2 = s2;
X while (*scan1 != '\0' && *scan1 == *scan2) {
X scan1++;
X scan2++;
X }
X
X /*
X * The following case analysis is necessary so that characters
X * which look negative collate low against normal characters but
X * high against the end-of-string NUL.
X */
X if (*scan1 == '\0' && *scan2 == '\0')
X return(0);
X else if (*scan1 == '\0')
X return(-1);
X else if (*scan2 == '\0')
X return(1);
X else
X return(*scan1 - *scan2);
X}
!
echo strcpy.c:
sed 's/^X//' >strcpy.c <<'!'
X/*
X * strcpy - copy string src to dst
X */
Xchar * /* dst */
Xstrcpy(dst, src)
Xchar *dst;
XCONST char *src;
X{
X register char *dscan;
X register CONST char *sscan;
X
X dscan = dst;
X sscan = src;
X while ((*dscan++ = *sscan++) != '\0')
X continue;
X return(dst);
X}
!
echo strcspn.c:
sed 's/^X//' >strcspn.c <<'!'
X/*
X * strcspn - find length of initial segment of s consisting entirely
X * of characters not from reject
X */
X
XSIZET
Xstrcspn(s, reject)
XCONST char *s;
XCONST char *reject;
X{
X register CONST char *scan;
X register CONST char *rscan;
X register SIZET count;
X
X count = 0;
X for (scan = s; *scan != '\0'; scan++) {
X for (rscan = reject; *rscan != '\0';) /* ++ moved down. */
X if (*scan == *rscan++)
X return(count);
X count++;
X }
X return(count);
X}
!
echo strlen.c:
sed 's/^X//' >strlen.c <<'!'
X/*
X * strlen - length of string (not including NUL)
X */
XSIZET
Xstrlen(s)
XCONST char *s;
X{
X register CONST char *scan;
X register SIZET count;
X
X count = 0;
X scan = s;
X while (*scan++ != '\0')
X count++;
X return(count);
X}
!
echo strncat.c:
sed 's/^X//' >strncat.c <<'!'
X/*
X * strncat - append at most n characters of string src to dst
X */
Xchar * /* dst */
Xstrncat(dst, src, n)
Xchar *dst;
XCONST char *src;
XSIZET n;
X{
X register char *dscan;
X register CONST char *sscan;
X register SIZET count;
X
X for (dscan = dst; *dscan != '\0'; dscan++)
X continue;
X sscan = src;
X count = n;
X while (*sscan != '\0' && --count >= 0)
X *dscan++ = *sscan++;
X *dscan++ = '\0';
X return(dst);
X}
!
echo strncmp.c:
sed 's/^X//' >strncmp.c <<'!'
X/*
X * strncmp - compare at most n characters of string s1 to s2
X */
X
Xint /* <0 for <, 0 for ==, >0 for > */
Xstrncmp(s1, s2, n)
XCONST char *s1;
XCONST char *s2;
XSIZET n;
X{
X register CONST char *scan1;
X register CONST char *scan2;
X register SIZET count;
X
X scan1 = s1;
X scan2 = s2;
X count = n;
X while (--count >= 0 && *scan1 != '\0' && *scan1 == *scan2) {
X scan1++;
X scan2++;
X }
X if (count < 0)
X return(0);
X
X /*
X * The following case analysis is necessary so that characters
X * which look negative collate low against normal characters but
X * high against the end-of-string NUL.
X */
X if (*scan1 == '\0' && *scan2 == '\0')
X return(0);
X else if (*scan1 == '\0')
X return(-1);
X else if (*scan2 == '\0')
X return(1);
X else
X return(*scan1 - *scan2);
X}
!
echo strncpy.c:
sed 's/^X//' >strncpy.c <<'!'
X/*
X * strncpy - copy at most n characters of string src to dst
X */
Xchar * /* dst */
Xstrncpy(dst, src, n)
Xchar *dst;
XCONST char *src;
XSIZET n;
X{
X register char *dscan;
X register CONST char *sscan;
X register SIZET count;
X
X dscan = dst;
X sscan = src;
X count = n;
X while (--count >= 0 && (*dscan++ = *sscan++) != '\0')
X continue;
X while (--count >= 0)
X *dscan++ = '\0';
X return(dst);
X}
!
echo strpbrk.c:
sed 's/^X//' >strpbrk.c <<'!'
X/*
X * strpbrk - find first occurrence of any char from breakat in s
X */
X
X#define NULL 0
X
Xchar * /* found char, or NULL if none */
Xstrpbrk(s, breakat)
XCONST char *s;
XCONST char *breakat;
X{
X register CONST char *sscan;
X register CONST char *bscan;
X
X for (sscan = s; *sscan != '\0'; sscan++) {
X for (bscan = breakat; *bscan != '\0';) /* ++ moved down. */
X if (*sscan == *bscan++)
X return(sscan);
X }
X return(NULL);
X}
!
echo strrchr.c:
sed 's/^X//' >strrchr.c <<'!'
X/*
X * strrchr - find last occurrence of a character in a string
X */
X
X#define NULL 0
X
Xchar * /* found char, or NULL if none */
Xstrrchr(s, charwanted)
XCONST char *s;
Xregister char charwanted;
X{
X register CONST char *scan;
X register CONST char *place;
X
X place = NULL;
X for (scan = s; *scan != '\0'; scan++)
X if (*scan == charwanted)
X place = scan;
X if (charwanted == '\0')
X return(scan);
X return(place);
X}
!
echo strspn.c:
sed 's/^X//' >strspn.c <<'!'
X/*
X * strspn - find length of initial segment of s consisting entirely
X * of characters from accept
X */
X
XSIZET
Xstrspn(s, accept)
XCONST char *s;
XCONST char *accept;
X{
X register CONST char *sscan;
X register CONST char *ascan;
X register SIZET count;
X
X count = 0;
X for (sscan = s; *sscan != '\0'; sscan++) {
X for (ascan = accept; *ascan != '\0'; ascan++)
X if (*sscan == *ascan)
X break;
X if (*ascan == '\0')
X return(count);
X count++;
X }
X return(count);
X}
!
echo strtok.c:
sed 's/^X//' >strtok.c <<'!'
X/*
X * Get next token from string s (NULL on 2nd, 3rd, etc. calls),
X * where tokens are nonempty strings separated by runs of
X * chars from delim. Writes NULs into s to end tokens. delim need not
X * remain constant from call to call.
X */
X
X#define NULL 0
X
Xstatic char *scanpoint = NULL;
X
Xchar * /* NULL if no token left */
Xstrtok(s, delim)
Xchar *s;
Xregister CONST char *delim;
X{
X register char *scan;
X char *tok;
X register CONST char *dscan;
X
X if (s == NULL && scanpoint == NULL)
X return(NULL);
X if (s != NULL)
X scan = s;
X else
X scan = scanpoint;
X
X /*
X * Scan leading delimiters.
X */
X for (; *scan != '\0'; scan++) {
X for (dscan = delim; *dscan != '\0'; dscan++)
X if (*scan == *dscan)
X break;
X if (*dscan == '\0')
X break;
X }
X if (*scan == '\0') {
X scanpoint = NULL;
X return(NULL);
X }
X
X tok = scan;
X
X /*
X * Scan token.
X */
X for (; *scan != '\0'; scan++) {
X for (dscan = delim; *dscan != '\0';) /* ++ moved down. */
X if (*scan == *dscan++) {
X scanpoint = scan+1;
X *scan = '\0';
X return(tok);
X }
X }
X
X /*
X * Reached end of string.
X */
X scanpoint = NULL;
X return(tok);
X}
!
echo strstr.c:
sed 's/^X//' >strstr.c <<'!'
X/*
X * strstr - find first occurrence of wanted in s
X */
X
X#define NULL 0
X
Xchar * /* found string, or NULL if none */
Xstrstr(s, wanted)
XCONST char *s;
XCONST char *wanted;
X{
X register CONST char *scan;
X register SIZET len;
X register char firstc;
X extern int strcmp();
X extern SIZET strlen();
X
X /*
X * The odd placement of the two tests is so "" is findable.
X * Also, we inline the first char for speed.
X * The ++ on scan has been moved down for optimization.
X */
X firstc = *wanted;
X len = strlen(wanted);
X for (scan = s; *scan != firstc || strncmp(scan, wanted, len) != 0; )
X if (*scan++ == '\0')
X return(NULL);
X return(scan);
X}
!
echo memcpy.c:
sed 's/^X//' >memcpy.c <<'!'
X/*
X * memcpy - copy bytes
X */
X
XVOIDSTAR
Xmemcpy(dst, src, size)
XVOIDSTAR dst;
XCONST VOIDSTAR src;
XSIZET size;
X{
X register char *d;
X register CONST char *s;
X register SIZET n;
X
X if (size <= 0)
X return(dst);
X
X s = src;
X d = dst;
X if (s <= d && s + (size-1) >= d) {
X /* Overlap, must copy right-to-left. */
X s += size-1;
X d += size-1;
X for (n = size; n > 0; n--)
X *d-- = *s--;
X } else
X for (n = size; n > 0; n--)
X *d++ = *s++;
X
X return(dst);
X}
!
echo memccpy.c:
sed 's/^X//' >memccpy.c <<'!'
X/*
X * memccpy - copy bytes up to a certain char
X *
X * CHARBITS should be defined only if the compiler lacks "unsigned char".
X * It should be a mask, e.g. 0377 for an 8-bit machine.
X */
X
X#define NULL 0
X
X#ifndef CHARBITS
X# define UNSCHAR(c) ((unsigned char)(c))
X#else
X# define UNSCHAR(c) ((c)&CHARBITS)
X#endif
X
XVOIDSTAR
Xmemccpy(dst, src, ucharstop, size)
XVOIDSTAR dst;
XCONST VOIDSTAR src;
XSIZET size;
X{
X register char *d;
X register CONST char *s;
X register SIZET n;
X register int uc;
X
X if (size <= 0)
X return(NULL);
X
X s = src;
X d = dst;
X uc = UNSCHAR(ucharstop);
X for (n = size; n > 0; n--)
X if (UNSCHAR(*d++ = *s++) == uc)
X return(d);
X
X return(NULL);
X}
!
echo memcmp.c:
sed 's/^X//' >memcmp.c <<'!'
X/*
X * memcmp - compare bytes
X */
X
Xint /* <0, == 0, >0 */
Xmemcmp(s1, s2, size)
XCONST VOIDSTAR s1;
XCONST VOIDSTAR s2;
XSIZET size;
X{
X register CONST char *scan1;
X register CONST char *scan2;
X register SIZET n;
X
X scan1 = s1;
X scan2 = s2;
X for (n = size; n > 0; n--)
X if (*scan1 == *scan2) {
X scan1++;
X scan2++;
X } else
X return(*scan1 - *scan2);
X
X return(0);
X}
!
echo memchr.c:
sed 's/^X//' >memchr.c <<'!'
X/*
X * memchr - search for a byte
X *
X * CHARBITS should be defined only if the compiler lacks "unsigned char".
X * It should be a mask, e.g. 0377 for an 8-bit machine.
X */
X
X#define NULL 0
X
X#ifndef CHARBITS
X# define UNSCHAR(c) ((unsigned char)(c))
X#else
X# define UNSCHAR(c) ((c)&CHARBITS)
X#endif
X
XVOIDSTAR
Xmemchr(s, ucharwanted, size)
XCONST VOIDSTAR s;
Xint ucharwanted;
XSIZET size;
X{
X register CONST char *scan;
X register SIZET n;
X register int uc;
X
X scan = s;
X uc = UNSCHAR(ucharwanted);
X for (n = size; n > 0; n--)
X if (UNSCHAR(*scan) == uc)
X return(scan);
X else
X scan++;
X
X return(NULL);
X}
!
echo memset.c:
sed 's/^X//' >memset.c <<'!'
X/*
X * memset - set bytes
X *
X * CHARBITS should be defined only if the compiler lacks "unsigned char".
X * It should be a mask, e.g. 0377 for an 8-bit machine.
X */
X
X#ifndef CHARBITS
X# define UNSCHAR(c) ((unsigned char)(c))
X#else
X# define UNSCHAR(c) ((c)&CHARBITS)
X#endif
X
XVOIDSTAR
Xmemset(s, ucharfill, size)
XCONST VOIDSTAR s;
Xregister int ucharfill;
XSIZET size;
X{
X register CONST char *scan;
X register SIZET n;
X register int uc;
X
X scan = s;
X uc = UNSCHAR(ucharfill);
X for (n = size; n > 0; n--)
X *scan++ = uc;
X
X return(s);
X}
!
echo bcopy.c:
sed 's/^X//' >bcopy.c <<'!'
X/*
X - bcopy - Berklix equivalent of memcpy
X */
X
Xbcopy(src, dst, length)
XCONST char *src;
Xchar *dst;
Xint length;
X{
X extern VOIDSTAR memcpy();
X
X (void) memcpy((VOIDSTAR)dst, (CONST VOIDSTAR)src, (SIZET)length);
X}
!
echo bcmp.c:
sed 's/^X//' >bcmp.c <<'!'
X/*
X - bcmp - Berklix equivalent of memcmp
X */
X
Xint /* == 0 or != 0 for equality and inequality */
Xbcmp(s1, s2, length)
XCONST char *s1;
XCONST char *s2;
Xint length;
X{
X return(memcmp((CONST VOIDSTAR)s1, (CONST VOIDSTAR)s2, (SIZET)length));
X}
!
echo bzero.c:
sed 's/^X//' >bzero.c <<'!'
X/*
X - bzero - Berklix subset of memset
X */
X
Xbzero(dst, length)
Xchar *dst;
Xint length;
X{
X extern VOIDSTAR memset();
X
X (void) memset((VOIDSTAR)dst, 0, (SIZET)length);
X}
!
echo strerror.c:
sed 's/^X//' >strerror.c <<'!'
X/*
X * strerror - map error number to descriptive string
X *
X * This version is obviously somewhat Unix-specific.
X */
Xchar *
Xstrerror(errnum)
Xint errnum;
X{
X extern int errno, sys_nerr;
X extern char *sys_errlist[];
X
X if (errnum > 0 && errnum < sys_nerr)
X return(sys_errlist[errnum]);
X else
X return("unknown error");
X}
!
echo tester.c:
sed 's/^X//' >tester.c <<'!'
X/*
X * Test program for string(3) routines.
X *
X * Note that at least one Bell Labs implementation of the string
X * routines flunks a couple of these tests -- the ones which test
X * behavior on "negative" characters.
X */
X
X#include <stdio.h>
X#include <string.h>
X
X#define STREQ(a, b) (strcmp((a), (b)) == 0)
X
Xchar *it = "<UNSET>"; /* Routine name for message routines. */
Xint waserror = 0; /* For exit status. */
X
Xchar uctest[] = "\004\203"; /* For testing signedness of chars. */
Xint charsigned; /* Result. */
X
X/*
X - check - complain if condition is not true
X */
Xvoid
Xcheck(thing, number)
Xint thing;
Xint number; /* Test number for error message. */
X{
X if (!thing) {
X printf("%s flunked test %d\n", it, number);
X waserror = 1;
X }
X}
X
X/*
X - equal - complain if first two args don't strcmp as equal
X */
Xvoid
Xequal(a, b, number)
Xchar *a;
Xchar *b;
Xint number; /* Test number for error message. */
X{
X check(a != NULL && b != NULL && STREQ(a, b), number);
X}
X
Xchar one[50];
Xchar two[50];
X
X#ifdef UNIXERR
X#define ERR 1
X#endif
X#ifdef BERKERR
X#define ERR 1
X#endif
X#ifdef ERR
Xint f;
Xextern char *sys_errlist[];
Xextern int sys_nerr;
Xextern int errno;
X#endif
X
X/* ARGSUSED */
Xmain(argc, argv)
Xint argc;
Xchar *argv[];
X{
X /*
X * First, establish whether chars are signed.
X */
X if (uctest[0] < uctest[1])
X charsigned = 0;
X else
X charsigned = 1;
X
X /*
X * Then, do the rest of the work. Split into two functions because
X * some compilers get unhappy about a single immense function.
X */
X first();
X second();
X
X exit((waserror) ? 1 : 0);
X}
X
Xfirst()
X{
X /*
X * Test strcmp first because we use it to test other things.
X */
X it = "strcmp";
X check(strcmp("", "") == 0, 1); /* Trivial case. */
X check(strcmp("a", "a") == 0, 2); /* Identity. */
X check(strcmp("abc", "abc") == 0, 3); /* Multicharacter. */
X check(strcmp("abc", "abcd") < 0, 4); /* Length mismatches. */
X check(strcmp("abcd", "abc") > 0, 5);
X check(strcmp("abcd", "abce") < 0, 6); /* Honest miscompares. */
X check(strcmp("abce", "abcd") > 0, 7);
X check(strcmp("a\203", "a") > 0, 8); /* Tricky if char signed. */
X if (charsigned) /* Sign-bit comparison. */
X check(strcmp("a\203", "a\003") < 0, 9);
X else
X check(strcmp("a\203", "a\003") > 0, 9);
X
X /*
X * Test strcpy next because we need it to set up other tests.
X */
X it = "strcpy";
X check(strcpy(one, "abcd") == one, 1); /* Returned value. */
X equal(one, "abcd", 2); /* Basic test. */
X
X (void) strcpy(one, "x");
X equal(one, "x", 3); /* Writeover. */
X equal(one+2, "cd", 4); /* Wrote too much? */
X
X (void) strcpy(two, "hi there");
X (void) strcpy(one, two);
X equal(one, "hi there", 5); /* Basic test encore. */
X equal(two, "hi there", 6); /* Stomped on source? */
X
X (void) strcpy(one, "");
X equal(one, "", 7); /* Boundary condition. */
X
X /*
X * strcat
X */
X it = "strcat";
X (void) strcpy(one, "ijk");
X check(strcat(one, "lmn") == one, 1); /* Returned value. */
X equal(one, "ijklmn", 2); /* Basic test. */
X
X (void) strcpy(one, "x");
X (void) strcat(one, "yz");
X equal(one, "xyz", 3); /* Writeover. */
X equal(one+4, "mn", 4); /* Wrote too much? */
X
X (void) strcpy(one, "gh");
X (void) strcpy(two, "ef");
X (void) strcat(one, two);
X equal(one, "ghef", 5); /* Basic test encore. */
X equal(two, "ef", 6); /* Stomped on source? */
X
X (void) strcpy(one, "");
X (void) strcat(one, "");
X equal(one, "", 7); /* Boundary conditions. */
X (void) strcpy(one, "ab");
X (void) strcat(one, "");
X equal(one, "ab", 8);
X (void) strcpy(one, "");
X (void) strcat(one, "cd");
X equal(one, "cd", 9);
X
X /*
X * strncat - first test it as strcat, with big counts, then
X * test the count mechanism.
X */
X it = "strncat";
X (void) strcpy(one, "ijk");
X check(strncat(one, "lmn", 99) == one, 1); /* Returned value. */
X equal(one, "ijklmn", 2); /* Basic test. */
X
X (void) strcpy(one, "x");
X (void) strncat(one, "yz", 99);
X equal(one, "xyz", 3); /* Writeover. */
X equal(one+4, "mn", 4); /* Wrote too much? */
X
X (void) strcpy(one, "gh");
X (void) strcpy(two, "ef");
X (void) strncat(one, two, 99);
X equal(one, "ghef", 5); /* Basic test encore. */
X equal(two, "ef", 6); /* Stomped on source? */
X
X (void) strcpy(one, "");
X (void) strncat(one, "", 99);
X equal(one, "", 7); /* Boundary conditions. */
X (void) strcpy(one, "ab");
X (void) strncat(one, "", 99);
X equal(one, "ab", 8);
X (void) strcpy(one, "");
X (void) strncat(one, "cd", 99);
X equal(one, "cd", 9);
X
X (void) strcpy(one, "ab");
X (void) strncat(one, "cdef", 2);
X equal(one, "abcd", 10); /* Count-limited. */
X
X (void) strncat(one, "gh", 0);
X equal(one, "abcd", 11); /* Zero count. */
X
X (void) strncat(one, "gh", 2);
X equal(one, "abcdgh", 12); /* Count and length equal. */
X
X /*
X * strncmp - first test as strcmp with big counts, then test
X * count code.
X */
X it = "strncmp";
X check(strncmp("", "", 99) == 0, 1); /* Trivial case. */
X check(strncmp("a", "a", 99) == 0, 2); /* Identity. */
X check(strncmp("abc", "abc", 99) == 0, 3); /* Multicharacter. */
X check(strncmp("abc", "abcd", 99) < 0, 4); /* Length unequal. */
X check(strncmp("abcd", "abc", 99) > 0, 5);
X check(strncmp("abcd", "abce", 99) < 0, 6); /* Honestly unequal. */
X check(strncmp("abce", "abcd", 99) > 0, 7);
X check(strncmp("a\203", "a", 2) > 0, 8); /* Tricky if '\203' < 0 */
X if (charsigned) /* Sign-bit comparison. */
X check(strncmp("a\203", "a\003", 2) < 0, 9);
X else
X check(strncmp("a\203", "a\003", 2) > 0, 9);
X check(strncmp("abce", "abcd", 3) == 0, 10); /* Count limited. */
X check(strncmp("abce", "abc", 3) == 0, 11); /* Count == length. */
X check(strncmp("abcd", "abce", 4) < 0, 12); /* Nudging limit. */
X check(strncmp("abc", "def", 0) == 0, 13); /* Zero count. */
X
X /*
X * strncpy - testing is a bit different because of odd semantics
X */
X it = "strncpy";
X check(strncpy(one, "abc", 4) == one, 1); /* Returned value. */
X equal(one, "abc", 2); /* Did the copy go right? */
X
X (void) strcpy(one, "abcdefgh");
X (void) strncpy(one, "xyz", 2);
X equal(one, "xycdefgh", 3); /* Copy cut by count. */
X
X (void) strcpy(one, "abcdefgh");
X (void) strncpy(one, "xyz", 3); /* Copy cut just before NUL. */
X equal(one, "xyzdefgh", 4);
X
X (void) strcpy(one, "abcdefgh");
X (void) strncpy(one, "xyz", 4); /* Copy just includes NUL. */
X equal(one, "xyz", 5);
X equal(one+4, "efgh", 6); /* Wrote too much? */
X
X (void) strcpy(one, "abcdefgh");
X (void) strncpy(one, "xyz", 5); /* Copy includes padding. */
X equal(one, "xyz", 7);
X equal(one+4, "", 8);
X equal(one+5, "fgh", 9);
X
X (void) strcpy(one, "abc");
X (void) strncpy(one, "xyz", 0); /* Zero-length copy. */
X equal(one, "abc", 10);
X
X (void) strncpy(one, "", 2); /* Zero-length source. */
X equal(one, "", 11);
X equal(one+1, "", 12);
X equal(one+2, "c", 13);
X
X (void) strcpy(one, "hi there");
X (void) strncpy(two, one, 9);
X equal(two, "hi there", 14); /* Just paranoia. */
X equal(one, "hi there", 15); /* Stomped on source? */
X
X /*
X * strlen
X */
X it = "strlen";
X check(strlen("") == 0, 1); /* Empty. */
X check(strlen("a") == 1, 2); /* Single char. */
X check(strlen("abcd") == 4, 3); /* Multiple chars. */
X
X /*
X * strchr
X */
X it = "strchr";
X check(strchr("abcd", 'z') == NULL, 1); /* Not found. */
X (void) strcpy(one, "abcd");
X check(strchr(one, 'c') == one+2, 2); /* Basic test. */
X check(strchr(one, 'd') == one+3, 3); /* End of string. */
X check(strchr(one, 'a') == one, 4); /* Beginning. */
X check(strchr(one, '\0') == one+4, 5); /* Finding NUL. */
X (void) strcpy(one, "ababa");
X check(strchr(one, 'b') == one+1, 6); /* Finding first. */
X (void) strcpy(one, "");
X check(strchr(one, 'b') == NULL, 7); /* Empty string. */
X check(strchr(one, '\0') == one, 8); /* NUL in empty string. */
X
X /*
X * index - just like strchr
X */
X it = "index";
X check(index("abcd", 'z') == NULL, 1); /* Not found. */
X (void) strcpy(one, "abcd");
X check(index(one, 'c') == one+2, 2); /* Basic test. */
X check(index(one, 'd') == one+3, 3); /* End of string. */
X check(index(one, 'a') == one, 4); /* Beginning. */
X check(index(one, '\0') == one+4, 5); /* Finding NUL. */
X (void) strcpy(one, "ababa");
X check(index(one, 'b') == one+1, 6); /* Finding first. */
X (void) strcpy(one, "");
X check(index(one, 'b') == NULL, 7); /* Empty string. */
X check(index(one, '\0') == one, 8); /* NUL in empty string. */
X
X /*
X * strrchr
X */
X it = "strrchr";
X check(strrchr("abcd", 'z') == NULL, 1); /* Not found. */
X (void) strcpy(one, "abcd");
X check(strrchr(one, 'c') == one+2, 2); /* Basic test. */
X check(strrchr(one, 'd') == one+3, 3); /* End of string. */
X check(strrchr(one, 'a') == one, 4); /* Beginning. */
X check(strrchr(one, '\0') == one+4, 5); /* Finding NUL. */
X (void) strcpy(one, "ababa");
X check(strrchr(one, 'b') == one+3, 6); /* Finding last. */
X (void) strcpy(one, "");
X check(strrchr(one, 'b') == NULL, 7); /* Empty string. */
X check(strrchr(one, '\0') == one, 8); /* NUL in empty string. */
X
X /*
X * rindex - just like strrchr
X */
X it = "rindex";
X check(rindex("abcd", 'z') == NULL, 1); /* Not found. */
X (void) strcpy(one, "abcd");
X check(rindex(one, 'c') == one+2, 2); /* Basic test. */
X check(rindex(one, 'd') == one+3, 3); /* End of string. */
X check(rindex(one, 'a') == one, 4); /* Beginning. */
X check(rindex(one, '\0') == one+4, 5); /* Finding NUL. */
X (void) strcpy(one, "ababa");
X check(rindex(one, 'b') == one+3, 6); /* Finding last. */
X (void) strcpy(one, "");
X check(rindex(one, 'b') == NULL, 7); /* Empty string. */
X check(rindex(one, '\0') == one, 8); /* NUL in empty string. */
X}
X
Xsecond()
X{
X /*
X * strpbrk - somewhat like strchr
X */
X it = "strpbrk";
X check(strpbrk("abcd", "z") == NULL, 1); /* Not found. */
X (void) strcpy(one, "abcd");
X check(strpbrk(one, "c") == one+2, 2); /* Basic test. */
X check(strpbrk(one, "d") == one+3, 3); /* End of string. */
X check(strpbrk(one, "a") == one, 4); /* Beginning. */
X check(strpbrk(one, "") == NULL, 5); /* Empty search list. */
X check(strpbrk(one, "cb") == one+1, 6); /* Multiple search. */
X (void) strcpy(one, "abcabdea");
X check(strpbrk(one, "b") == one+1, 7); /* Finding first. */
X check(strpbrk(one, "cb") == one+1, 8); /* With multiple search. */
X check(strpbrk(one, "db") == one+1, 9); /* Another variant. */
X (void) strcpy(one, "");
X check(strpbrk(one, "bc") == NULL, 10); /* Empty string. */
X check(strpbrk(one, "") == NULL, 11); /* Both strings empty. */
X
X /*
X * strstr - somewhat like strchr
X */
X it = "strstr";
X check(strstr("abcd", "z") == NULL, 1); /* Not found. */
X check(strstr("abcd", "abx") == NULL, 2); /* Dead end. */
X (void) strcpy(one, "abcd");
X check(strstr(one, "c") == one+2, 3); /* Basic test. */
X check(strstr(one, "bc") == one+1, 4); /* Multichar. */
X check(strstr(one, "d") == one+3, 5); /* End of string. */
X check(strstr(one, "cd") == one+2, 6); /* Tail of string. */
X check(strstr(one, "abc") == one, 7); /* Beginning. */
X check(strstr(one, "abcd") == one, 8); /* Exact match. */
X check(strstr(one, "abcde") == NULL, 9); /* Too long. */
X check(strstr(one, "de") == NULL, 10); /* Past end. */
X check(strstr(one, "") == one+4, 11); /* Finding empty. */
X (void) strcpy(one, "ababa");
X check(strstr(one, "ba") == one+1, 12); /* Finding first. */
X (void) strcpy(one, "");
X check(strstr(one, "b") == NULL, 13); /* Empty string. */
X check(strstr(one, "") == one, 14); /* Empty in empty string. */
X (void) strcpy(one, "bcbca");
X check(strstr(one, "bca") == one+2, 15); /* False start. */
X (void) strcpy(one, "bbbcabbca");
X check(strstr(one, "bbca") == one+1, 16); /* With overlap. */
X
X /*
X * strspn
X */
X it = "strspn";
X check(strspn("abcba", "abc") == 5, 1); /* Whole string. */
X check(strspn("abcba", "ab") == 2, 2); /* Partial. */
X check(strspn("abc", "qx") == 0, 3); /* None. */
X check(strspn("", "ab") == 0, 4); /* Null string. */
X check(strspn("abc", "") == 0, 5); /* Null search list. */
X
X /*
X * strcspn
X */
X it = "strcspn";
X check(strcspn("abcba", "qx") == 5, 1); /* Whole string. */
X check(strcspn("abcba", "cx") == 2, 2); /* Partial. */
X check(strcspn("abc", "abc") == 0, 3); /* None. */
X check(strcspn("", "ab") == 0, 4); /* Null string. */
X check(strcspn("abc", "") == 3, 5); /* Null search list. */
X
X /*
X * strtok - the hard one
X */
X it = "strtok";
X (void) strcpy(one, "first, second, third");
X equal(strtok(one, ", "), "first", 1); /* Basic test. */
X equal(one, "first", 2);
X equal(strtok((char *)NULL, ", "), "second", 3);
X equal(strtok((char *)NULL, ", "), "third", 4);
X check(strtok((char *)NULL, ", ") == NULL, 5);
X (void) strcpy(one, ", first, ");
X equal(strtok(one, ", "), "first", 6); /* Extra delims, 1 tok. */
X check(strtok((char *)NULL, ", ") == NULL, 7);
X (void) strcpy(one, "1a, 1b; 2a, 2b");
X equal(strtok(one, ", "), "1a", 8); /* Changing delim lists. */
X equal(strtok((char *)NULL, "; "), "1b", 9);
X equal(strtok((char *)NULL, ", "), "2a", 10);
X (void) strcpy(two, "x-y");
X equal(strtok(two, "-"), "x", 11); /* New string before done. */
X equal(strtok((char *)NULL, "-"), "y", 12);
X check(strtok((char *)NULL, "-") == NULL, 13);
X (void) strcpy(one, "a,b, c,, ,d");
X equal(strtok(one, ", "), "a", 14); /* Different separators. */
X equal(strtok((char *)NULL, ", "), "b", 15);
X equal(strtok((char *)NULL, " ,"), "c", 16); /* Permute list too. */
X equal(strtok((char *)NULL, " ,"), "d", 17);
X check(strtok((char *)NULL, ", ") == NULL, 18);
X check(strtok((char *)NULL, ", ") == NULL, 19); /* Persistence. */
X (void) strcpy(one, ", ");
X check(strtok(one, ", ") == NULL, 20); /* No tokens. */
X (void) strcpy(one, "");
X check(strtok(one, ", ") == NULL, 21); /* Empty string. */
X (void) strcpy(one, "abc");
X equal(strtok(one, ", "), "abc", 22); /* No delimiters. */
X check(strtok((char *)NULL, ", ") == NULL, 23);
X (void) strcpy(one, "abc");
X equal(strtok(one, ""), "abc", 24); /* Empty delimiter list. */
X check(strtok((char *)NULL, "") == NULL, 25);
X (void) strcpy(one, "abcdefgh");
X (void) strcpy(one, "a,b,c");
X equal(strtok(one, ","), "a", 26); /* Basics again... */
X equal(strtok((char *)NULL, ","), "b", 27);
X equal(strtok((char *)NULL, ","), "c", 28);
X check(strtok((char *)NULL, ",") == NULL, 29);
X equal(one+6, "gh", 30); /* Stomped past end? */
X equal(one, "a", 31); /* Stomped old tokens? */
X equal(one+2, "b", 32);
X equal(one+4, "c", 33);
X
X /*
X * memcmp
X */
X it = "memcmp";
X check(memcmp("a", "a", 1) == 0, 1); /* Identity. */
X check(memcmp("abc", "abc", 3) == 0, 2); /* Multicharacter. */
X check(memcmp("abcd", "abce", 4) < 0, 3); /* Honestly unequal. */
X check(memcmp("abce", "abcd", 4) > 0, 4);
X check(memcmp("alph", "beta", 4) < 0, 5);
X if (charsigned) /* Sign-bit comparison. */
X check(memcmp("a\203", "a\003", 2) < 0, 6);
X else
X check(memcmp("a\203", "a\003", 2) > 0, 6);
X check(memcmp("abce", "abcd", 3) == 0, 7); /* Count limited. */
X check(memcmp("abc", "def", 0) == 0, 8); /* Zero count. */
X
X /*
X * memchr
X */
X it = "memchr";
X check(memchr("abcd", 'z', 4) == NULL, 1); /* Not found. */
X (void) strcpy(one, "abcd");
X check(memchr(one, 'c', 4) == one+2, 2); /* Basic test. */
X check(memchr(one, 'd', 4) == one+3, 3); /* End of string. */
X check(memchr(one, 'a', 4) == one, 4); /* Beginning. */
X check(memchr(one, '\0', 5) == one+4, 5); /* Finding NUL. */
X (void) strcpy(one, "ababa");
X check(memchr(one, 'b', 5) == one+1, 6); /* Finding first. */
X check(memchr(one, 'b', 0) == NULL, 7); /* Zero count. */
X check(memchr(one, 'a', 1) == one, 8); /* Singleton case. */
X (void) strcpy(one, "a\203b");
X check(memchr(one, 0203, 3) == one+1, 9); /* Unsignedness. */
X
X /*
X * memcpy
X *
X * Note that X3J11 says memcpy must work regardless of overlap.
X * The SVID says it might fail.
X */
X it = "memcpy";
X check(memcpy(one, "abc", 4) == one, 1); /* Returned value. */
X equal(one, "abc", 2); /* Did the copy go right? */
X
X (void) strcpy(one, "abcdefgh");
X (void) memcpy(one+1, "xyz", 2);
X equal(one, "axydefgh", 3); /* Basic test. */
X
X (void) strcpy(one, "abc");
X (void) memcpy(one, "xyz", 0);
X equal(one, "abc", 4); /* Zero-length copy. */
X
X (void) strcpy(one, "hi there");
X (void) strcpy(two, "foo");
X (void) memcpy(two, one, 9);
X equal(two, "hi there", 5); /* Just paranoia. */
X equal(one, "hi there", 6); /* Stomped on source? */
X
X (void) strcpy(one, "abcdefgh");
X (void) memcpy(one+1, one, 9);
X equal(one, "aabcdefgh", 7); /* Overlap, right-to-left. */
X
X (void) strcpy(one, "abcdefgh");
X (void) memcpy(one+1, one+2, 7);
X equal(one, "acdefgh", 8); /* Overlap, left-to-right. */
X
X (void) strcpy(one, "abcdefgh");
X (void) memcpy(one, one, 9);
X equal(one, "abcdefgh", 9); /* 100% overlap. */
X
X /*
X * memccpy - first test like memcpy, then the search part
X *
X * The SVID, the only place where memccpy is mentioned, says
X * overlap might fail, so we don't try it. Besides, it's hard
X * to see the rationale for a non-left-to-right memccpy.
X */
X it = "memccpy";
X check(memccpy(one, "abc", 'q', 4) == NULL, 1); /* Returned value. */
X equal(one, "abc", 2); /* Did the copy go right? */
X
X (void) strcpy(one, "abcdefgh");
X (void) memccpy(one+1, "xyz", 'q', 2);
X equal(one, "axydefgh", 3); /* Basic test. */
X
X (void) strcpy(one, "abc");
X (void) memccpy(one, "xyz", 'q', 0);
X equal(one, "abc", 4); /* Zero-length copy. */
X
X (void) strcpy(one, "hi there");
X (void) strcpy(two, "foo");
X (void) memccpy(two, one, 'q', 9);
X equal(two, "hi there", 5); /* Just paranoia. */
X equal(one, "hi there", 6); /* Stomped on source? */
X
X (void) strcpy(one, "abcdefgh");
X (void) strcpy(two, "horsefeathers");
X check(memccpy(two, one, 'f', 9) == two+6, 7); /* Returned value. */
X equal(one, "abcdefgh", 8); /* Source intact? */
X equal(two, "abcdefeathers", 9); /* Copy correct? */
X
X (void) strcpy(one, "abcd");
X (void) strcpy(two, "bumblebee");
X check(memccpy(two, one, 'a', 4) == two+1, 10); /* First char. */
X equal(two, "aumblebee", 11);
X check(memccpy(two, one, 'd', 4) == two+4, 12); /* Last char. */
X equal(two, "abcdlebee", 13);
X (void) strcpy(one, "xyz");
X check(memccpy(two, one, 'x', 1) == two+1, 14); /* Singleton. */
X equal(two, "xbcdlebee", 15);
X
X /*
X * memset
X */
X it = "memset";
X (void) strcpy(one, "abcdefgh");
X check(memset(one+1, 'x', 3) == one+1, 1); /* Return value. */
X equal(one, "axxxefgh", 2); /* Basic test. */
X
X (void) memset(one+2, 'y', 0);
X equal(one, "axxxefgh", 3); /* Zero-length set. */
X
X (void) memset(one+5, 0, 1);
X equal(one, "axxxe", 4); /* Zero fill. */
X equal(one+6, "gh", 5); /* And the leftover. */
X
X (void) memset(one+2, 010045, 1);
X equal(one, "ax\045xe", 6); /* Unsigned char convert. */
X
X /*
X * bcopy - much like memcpy
X *
X * Berklix manual is silent about overlap, so don't test it.
X */
X it = "bcopy";
X (void) bcopy("abc", one, 4);
X equal(one, "abc", 1); /* Simple copy. */
X
X (void) strcpy(one, "abcdefgh");
X (void) bcopy("xyz", one+1, 2);
X equal(one, "axydefgh", 2); /* Basic test. */
X
X (void) strcpy(one, "abc");
X (void) bcopy("xyz", one, 0);
X equal(one, "abc", 3); /* Zero-length copy. */
X
X (void) strcpy(one, "hi there");
X (void) strcpy(two, "foo");
X (void) bcopy(one, two, 9);
X equal(two, "hi there", 4); /* Just paranoia. */
X equal(one, "hi there", 5); /* Stomped on source? */
X
X /*
X * bzero
X */
X it = "bzero";
X (void) strcpy(one, "abcdef");
X bzero(one+2, 2);
X equal(one, "ab", 1); /* Basic test. */
X equal(one+3, "", 2);
X equal(one+4, "ef", 3);
X
X (void) strcpy(one, "abcdef");
X bzero(one+2, 0);
X equal(one, "abcdef", 4); /* Zero-length copy. */
X
X /*
X * bcmp - somewhat like memcmp
X */
X it = "bcmp";
X check(bcmp("a", "a", 1) == 0, 1); /* Identity. */
X check(bcmp("abc", "abc", 3) == 0, 2); /* Multicharacter. */
X check(bcmp("abcd", "abce", 4) != 0, 3); /* Honestly unequal. */
X check(bcmp("abce", "abcd", 4) != 0, 4);
X check(bcmp("alph", "beta", 4) != 0, 5);
X check(bcmp("abce", "abcd", 3) == 0, 6); /* Count limited. */
X check(bcmp("abc", "def", 0) == 0, 8); /* Zero count. */
X
X#ifdef ERR
X /*
X * strerror - VERY system-dependent
X */
X it = "strerror";
X f = open("/", 1); /* Should always fail. */
X check(f < 0 && errno > 0 && errno < sys_nerr, 1);
X equal(strerror(errno), sys_errlist[errno], 2);
X#ifdef UNIXERR
X equal(strerror(errno), "Is a directory", 3);
X#endif
X#ifdef BERKERR
X equal(strerror(errno), "Permission denied", 3);
X#endif
X#endif
X}
!
echo string.h.proto:
sed 's/^X//' >string.h.proto <<'!'
X/*
X * String functions.
X */
X
XVOIDSTAR memcpy(/*VOIDSTAR dst, const VOIDSTAR src, SIZET size*/);
XVOIDSTAR memccpy(/*VOIDSTAR dst, const VOIDSTAR src, int ucharstop, SIZET size*/);
Xchar *strcpy(/*char *dst, const char *src*/);
Xchar *strncpy(/*char *dst, const char *src, SIZET size*/);
Xchar *strcat(/*char *dst, const char *src*/);
Xchar *strncat(/*char *dst, const char *src, SIZET size*/);
Xint memcmp(/*const VOIDSTAR s1, const VOIDSTAR s2, SIZET size*/);
Xint strcmp(/*const char *s1, const char *s2*/);
Xint strncmp(/*const char *s1, const char *s2, SIZET size*/);
XVOIDSTAR memchr(/*const VOIDSTAR s, int ucharwanted, SIZET size*/);
Xchar *strchr(/*const char *s, int charwanted*/);
XSIZET strcspn(/*const char *s, const char *reject*/);
Xchar *strpbrk(/*const char *s, const char *breakat*/);
Xchar *strrchr(/*const char *s, int charwanted*/);
XSIZET strspn(/*const char *s, const char *accept*/);
Xchar *strstr(/*const char *s, const char *wanted*/);
Xchar *strtok(/*char *s, const char *delim*/);
XVOIDSTAR memset(/*VOIDSTAR s, int ucharfill, SIZET size*/);
XSIZET strlen(/*const char *s*/);
X
X/*
X * V7 and Berklix compatibility.
X */
Xchar *index(/*const char *s, int charwanted*/);
Xchar *rindex(/*const char *s, int charwanted*/);
Xint bcopy(/*const char *src, char *dst, int length*/);
Xint bcmp(/*const char *s1, const char *s2, int length*/);
Xint bzero(/*char *dst, int length*/);
X
X/*
X * Putting this in here is really silly, but who am I to argue with X3J11?
X */
Xchar *strerror(/*int errnum*/);
!
echo done
------------------
|