]> granicus.if.org Git - fortune-mod/blob - fortune-mod/util/strfile.c
prepare for a release
[fortune-mod] / fortune-mod / util / strfile.c
1 /*      $NetBSD: strfile.c,v 1.3 1995/03/23 08:28:47 cgd Exp $  */
2
3 /*-
4  * Copyright (c) 1989, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Ken Arnold.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38
39 /*
40  * Changes, September 1995, to make the damn thing actually sort instead
41  * of just pretending.  Amy A. Lewis
42  *
43  * And lots more.
44  *
45  * Fixed the special cases of %^J% (an empty fortune), no 'separator' at
46  * the end of the file, and a trailing newline at the end of the file, all
47  * of which produced total ballsup at one point or another.
48  *
49  * This included adding a routine to go back and write over the last pointer
50  * written or stored, for the case of an empty fortune.
51  *
52  * unstr also had to be modified (well, for *lots* of reasons, but this was
53  * one) to be certain to put the delimiters in the right places.
54  */
55
56 #include "fortune-mod-common.h"
57
58 /*
59  *    This program takes a file composed of strings separated by
60  * lines containing only the delimiting character (the default
61  * character is '%') and creates another file which consists of a table
62  * describing the file (structure from "strfile.h"), a table of seek
63  * pointers to the start of the strings, and the strings, each terminated
64  * by a null byte.  Usage:
65  *
66  *      % strfile [-iorsx] [ -cC ] sourcefile [ datafile ]
67  *
68  *      c - Change delimiting character from '%' to 'C'
69  *      s - Silent.  Give no summary of data processed at the end of
70  *          the run.
71  *      o - order the strings in alphabetic order
72  *      i - if ordering, ignore case
73  *      r - randomize the order of the strings
74  *      x - set rotated bit
75  *
76  *              Ken Arnold      Sept. 7, 1978 --
77  *
78  *      Added ordering options.
79  *
80  * Made ordering options do more than set the bloody flag, September 95 A. Lewis
81  *
82  * Always make sure that your loop control variables aren't set to bloody
83  * *zero* before distributing the bloody code, all right?
84  *
85  */
86
87 #define CHUNKSIZE 512
88
89 #define ALLOC(ptr, sz)                                                         \
90     {                                                                          \
91         if (!ptr)                                                              \
92             ptr = malloc((unsigned int)(CHUNKSIZE * sizeof *ptr));             \
93         else if (((sz) + 1) % CHUNKSIZE == 0)                                  \
94             ptr = realloc((void *)ptr,                                         \
95                 ((unsigned int)((sz) + CHUNKSIZE) * sizeof *ptr));             \
96         if (!ptr)                                                              \
97         {                                                                      \
98             fprintf(stderr, "out of space\n");                                 \
99             exit(1);                                                           \
100         }                                                                      \
101     }
102
103 typedef struct
104 {
105     char first;
106     int32_t pos;
107 } STR;
108
109 static char delimiter_char = '%';
110
111 static bool Sflag = false; /* silent run flag */
112 static bool Oflag = false; /* ordering flag */
113 static bool Iflag = false; /* ignore case flag */
114 static bool Rflag = false; /* randomize order flag */
115 static bool Xflag = false; /* set rotated bit */
116 static long Num_pts = 0;   /* number of pointers/strings */
117
118 static bool storing_ptrs(void) { return (Oflag || Rflag); }
119
120 static int32_t *Seekpts;
121
122 static FILE *Sort_1, *Sort_2; /* pointers for sorting */
123
124 static STRFILE Tbl; /* statistics table */
125
126 static STR *Firstch; /* first chars of each string */
127
128 static void __attribute__((noreturn)) usage(void)
129 {
130     fprintf(stderr, "%s", "strfile [-iorsx] [-c char] sourcefile [datafile]\n");
131     exit(1);
132 }
133
134 #include "fortune-util-set-outfn.h"
135
136 /*
137  *    This routine evaluates arguments from the command line
138  */
139 static void getargs(int argc, char **argv)
140 {
141     int ch;
142
143     while ((ch = getopt(argc, argv, "c:iorsx")) != EOF)
144     {
145         switch (ch)
146         {
147         case 'c': /* new delimiting char */
148             delimiter_char = *optarg;
149             if (!isascii(delimiter_char))
150             {
151                 printf("bad delimiting character: '\\%o\n'",
152                     (unsigned int)delimiter_char);
153             }
154             break;
155         case 'i': /* ignore case in ordering */
156             Iflag = true;
157             break;
158         case 'o': /* order strings */
159             Oflag = true;
160             break;
161         case 'r': /* randomize pointers */
162             Rflag = true;
163             break;
164         case 's': /* silent */
165             Sflag = true;
166             break;
167         case 'x': /* set the rotated bit */
168             Xflag = true;
169             break;
170         case '?':
171         default:
172             usage();
173         }
174     }
175     argv += optind;
176
177     if (*argv)
178     {
179         input_filename = *argv;
180         set_output_filename(*++argv);
181     }
182     if (!input_filename)
183     {
184         puts("No input file name");
185         usage();
186     }
187     if (*output_filename == '\0')
188     {
189         if (strlen(input_filename) > MAXPATHLEN - 10)
190         {
191             puts("input file name too long!");
192             usage();
193         }
194         snprintf(
195             output_filename, COUNT(output_filename), "%s.dat", input_filename);
196     }
197 }
198
199 /*
200  * add_offset:
201  *      Add an offset to the list, or write it out, as appropriate.
202  */
203 static void add_offset(FILE *fp, int32_t off)
204 {
205     if (!storing_ptrs())
206     {
207         uint32_t net;
208         net = htonl((uint32_t)off);
209         fwrite(&net, 1, sizeof net, fp);
210     }
211     else
212     {
213         ALLOC(Seekpts, Num_pts + 1);
214         Seekpts[Num_pts] = off;
215     }
216     Num_pts++;
217 }
218
219 /*
220  * fix_last_offset:
221  *     Used when we have two separators in a row.
222  */
223 static void fix_last_offset(FILE *const fp, const int32_t off)
224 {
225     if (!storing_ptrs())
226     {
227         uint32_t net = htonl((uint32_t)off);
228         fseek(fp, -(long)(sizeof net), SEEK_CUR);
229         fwrite(&net, 1, sizeof net, fp);
230     }
231     else
232     {
233         Seekpts[Num_pts - 1] = off;
234     }
235 }
236
237 /*
238  * cmp_str:
239  *      Compare two strings in the file
240  */
241 static int cmp_str(const void *v1, const void *v2)
242 {
243 #define SET_N(nf, ch) (nf = (ch == '\n'))
244 #define IS_END(ch, nf) (ch == delimiter_char && nf)
245
246     const STR *p1 = (const STR *)v1;
247     const STR *p2 = (const STR *)v2;
248     int c1 = p1->first;
249     int c2 = p2->first;
250     if (c1 != c2)
251     {
252         return c1 - c2;
253     }
254
255     fseek(Sort_1, p1->pos, SEEK_SET);
256     fseek(Sort_2, p2->pos, SEEK_SET);
257
258     bool n1 = false;
259     bool n2 = false;
260     while (!isalnum(c1 = getc(Sort_1)) && c1 != '\0')
261     {
262         SET_N(n1, c1);
263     }
264     while (!isalnum(c2 = getc(Sort_2)) && c2 != '\0')
265     {
266         SET_N(n2, c2);
267     }
268
269     while (!IS_END(c1, n1) && !IS_END(c2, n2))
270     {
271         if (Iflag)
272         {
273             if (isupper(c1))
274             {
275                 c1 = tolower(c1);
276             }
277             if (isupper(c2))
278             {
279                 c2 = tolower(c2);
280             }
281         }
282         if (c1 != c2)
283         {
284             return c1 - c2;
285         }
286         SET_N(n1, c1);
287         SET_N(n2, c2);
288         c1 = getc(Sort_1);
289         c2 = getc(Sort_2);
290     }
291     if (IS_END(c1, n1))
292     {
293         c1 = 0;
294     }
295     if (IS_END(c2, n2))
296     {
297         c2 = 0;
298     }
299     return c1 - c2;
300 }
301
302 /*
303  * do_order:
304  *      Order the strings alphabetically (possibly ignoring case).
305  */
306 static void do_order(void)
307 {
308     Sort_1 = fopen(input_filename, "r");
309     Sort_2 = fopen(input_filename, "r");
310     qsort(
311         (char *)Firstch, (size_t)((int)Num_pts - 1), sizeof *Firstch, cmp_str);
312     /*      i = Tbl.str_numstr;
313      * Fucking brilliant.  Tbl.str_numstr was initialized to zero, and is still
314      * zero
315      */
316     long i = Num_pts - 1;
317     int32_t *lp = Seekpts;
318     STR *fp = Firstch;
319     while (i--)
320     {
321         *lp++ = fp++->pos;
322     }
323     fclose(Sort_1);
324     fclose(Sort_2);
325     Tbl.str_flags |= STR_ORDERED;
326 }
327
328 /*
329  * randomize:
330  *      Randomize the order of the string table.  We must be careful
331  *      not to randomize across delimiter boundaries.  All
332  *      randomization is done within each block.
333  */
334 static void randomize(void)
335 {
336     call_srandom();
337     Tbl.str_flags |= STR_RANDOM;
338     /*      cnt = Tbl.str_numstr;
339      * See comment above.  Isn't this stuff distributed worldwide?  How
340      * embarrassing!
341      */
342     int cnt = (int)Num_pts;
343
344     /*
345      * move things around randomly
346      */
347
348     int32_t *sp = Seekpts;
349     for (; cnt > 0; cnt--, sp++)
350     {
351         const int i = random() % cnt;
352         const int32_t tmp = sp[0];
353         sp[0] = sp[i];
354         sp[i] = tmp;
355     }
356 }
357
358 /*
359  * main:
360  *      Drive the sucker.  There are two main modes -- either we store
361  *      the seek pointers, if the table is to be sorted or randomized,
362  *      or we write the pointer directly to the file, if we are to stay
363  *      in file order.  If the former, we allocate and re-allocate in
364  *      CHUNKSIZE blocks; if the latter, we just write each pointer,
365  *      and then seek back to the beginning to write in the table.
366  */
367 int main(int argc, char **argv)
368 {
369     char *sp;
370     FILE *inf, *outf;
371     bool len_was_set = false;
372
373     getargs(argc, argv); /* evalute arguments */
374     if (!(inf = fopen(input_filename, "r")))
375     {
376         perror(input_filename);
377         exit(1);
378     }
379
380     if (!(outf = fopen(output_filename, "w")))
381     {
382         perror(output_filename);
383         exit(1);
384     }
385     if (!storing_ptrs())
386     {
387         (void)fseek(outf, sizeof Tbl, SEEK_SET);
388     }
389
390     /*
391      * Write the strings onto the file
392      */
393
394     Tbl.str_longlen = 0;
395     Tbl.str_shortlen = (unsigned int)0xffffffff;
396     Tbl.str_delim = (uint8_t)delimiter_char;
397     Tbl.str_version = STRFILE_VERSION;
398     bool first = Oflag;
399     add_offset(outf, (int32_t)ftell(inf));
400     int32_t last_off = 0;
401     do
402     {
403         char string[257];
404         sp = fgets(string, 256, inf);
405         if ((!sp) || STR_ENDSTRING(sp, Tbl))
406         {
407             const int32_t pos = (int32_t)ftell(inf);
408             const int32_t length =
409                 pos - last_off - (int32_t)(sp ? strlen(sp) : 0);
410             if (!length)
411             /* Here's where we go back and fix things, if the
412              * 'fortune' just read was the null string.
413              * We had to make the assignment of last_off slightly
414              * redundant to achieve this.
415              */
416             {
417                 if (pos - last_off == 2)
418                 {
419                     fix_last_offset(outf, pos);
420                 }
421                 last_off = pos;
422                 continue;
423             }
424             last_off = pos;
425             add_offset(outf, pos);
426             if (!len_was_set)
427             {
428                 Tbl.str_longlen = (uint32_t)length;
429                 Tbl.str_shortlen = (uint32_t)length;
430                 len_was_set = true;
431             }
432             else
433             {
434                 if ((int)Tbl.str_longlen < length)
435                 {
436                     Tbl.str_longlen = (uint32_t)length;
437                 }
438                 if (Tbl.str_shortlen > (uint32_t)length)
439                 {
440                     Tbl.str_shortlen = (uint32_t)length;
441                 }
442             }
443             first = Oflag;
444         }
445         else if (first)
446         {
447             char *nsp = sp;
448             for (; !isalnum(*nsp); ++nsp)
449             {
450             }
451             ALLOC(Firstch, Num_pts);
452             STR *const fp = &Firstch[Num_pts - 1];
453             fp->first =
454                 ((Iflag && isupper(*nsp)) ? ((char)tolower(*nsp)) : (*nsp));
455             fp->pos = Seekpts[Num_pts - 1];
456             first = false;
457         }
458     } while (sp);
459
460     /*
461      * write the tables in
462      */
463
464     fclose(inf);
465
466     if (Oflag)
467     {
468         do_order();
469     }
470     else if (Rflag)
471     {
472         randomize();
473     }
474
475     if (Xflag)
476     {
477         Tbl.str_flags |= STR_ROTATED;
478     }
479
480     if (!Sflag)
481     {
482         printf("\"%s\" created\n", output_filename);
483         if (Num_pts == 1)
484         {
485             puts("There was no string");
486         }
487         else
488         {
489             if (Num_pts == 2)
490             {
491                 puts("There was 1 string");
492             }
493             else
494             {
495                 printf("There were %ld strings\n", Num_pts - 1);
496             }
497             printf("Longest string: %lu byte%s\n",
498                 (unsigned long)(Tbl.str_longlen),
499                 Tbl.str_longlen == 1 ? "" : "s");
500             printf("Shortest string: %lu byte%s\n",
501                 (unsigned long)(Tbl.str_shortlen),
502                 Tbl.str_shortlen == 1 ? "" : "s");
503         }
504     }
505
506     fseek(outf, (off_t)0, SEEK_SET);
507     Tbl.str_version = htonl(Tbl.str_version);
508     Tbl.str_numstr = htonl((uint32_t)(Num_pts - 1));
509     /* Look, Ma!  After using the variable three times, let's store
510      * something in it!
511      */
512     Tbl.str_longlen = htonl(Tbl.str_longlen);
513     Tbl.str_shortlen = htonl(Tbl.str_shortlen);
514     Tbl.str_flags = htonl(Tbl.str_flags);
515     fwrite(&Tbl.str_version, sizeof Tbl.str_version, 1, outf);
516     fwrite(&Tbl.str_numstr, sizeof Tbl.str_numstr, 1, outf);
517     fwrite(&Tbl.str_longlen, sizeof Tbl.str_longlen, 1, outf);
518     fwrite(&Tbl.str_shortlen, sizeof Tbl.str_shortlen, 1, outf);
519     fwrite(&Tbl.str_flags, sizeof Tbl.str_flags, 1, outf);
520     fwrite(Tbl.stuff, sizeof Tbl.stuff, 1, outf);
521     if (storing_ptrs())
522     {
523         int cnt = (int)Num_pts;
524         for (int32_t *p = Seekpts; cnt--; ++p)
525         {
526             *p = (int32_t)htonl((uint32_t)*p);
527             fwrite(p, sizeof *p, 1, outf);
528         }
529     }
530     fclose(outf);
531     exit(0);
532 }