source: trunk/src/helpers/stringh.c@ 68

Last change on this file since 68 was 56, checked in by umoeller, 24 years ago

misc changes

  • Property svn:eol-style set to CRLF
  • Property svn:keywords set to Author Date Id Revision
File size: 79.0 KB
Line 
1
2/*
3 *@@sourcefile stringh.c:
4 * contains string/text helper functions. These are good for
5 * parsing/splitting strings and other stuff used throughout
6 * XWorkplace.
7 *
8 * Note that these functions are really a bunch of very mixed
9 * up string helpers, which you may or may not find helpful.
10 * If you're looking for string functions with memory
11 * management, look at xstring.c instead.
12 *
13 * Usage: All OS/2 programs.
14 *
15 * Function prefixes (new with V0.81):
16 * -- strh* string helper functions.
17 *
18 * Note: Version numbering in this file relates to XWorkplace version
19 * numbering.
20 *
21 *@@header "helpers\stringh.h"
22 */
23
24/*
25 * Copyright (C) 1997-2000 Ulrich M”ller.
26 * Parts Copyright (C) 1991-1999 iMatix Corporation.
27 * This file is part of the "XWorkplace helpers" source package.
28 * This is free software; you can redistribute it and/or modify
29 * it under the terms of the GNU General Public License as published
30 * by the Free Software Foundation, in version 2 as it comes in the
31 * "COPYING" file of the XWorkplace main distribution.
32 * This program is distributed in the hope that it will be useful,
33 * but WITHOUT ANY WARRANTY; without even the implied warranty of
34 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
35 * GNU General Public License for more details.
36 */
37
38#define OS2EMX_PLAIN_CHAR
39 // this is needed for "os2emx.h"; if this is defined,
40 // emx will define PSZ as _signed_ char, otherwise
41 // as unsigned char
42
43#define INCL_WINSHELLDATA
44#include <os2.h>
45
46#include <stdlib.h>
47#include <stdio.h>
48#include <string.h>
49#include <ctype.h>
50#include <math.h>
51
52#include "setup.h" // code generation and debugging options
53
54#include "helpers\stringh.h"
55#include "helpers\xstring.h" // extended string helpers
56
57#pragma hdrstop
58
59/*
60 *@@category: Helpers\C helpers\String management
61 * See stringh.c and xstring.c.
62 */
63
64/*
65 *@@category: Helpers\C helpers\String management\C string helpers
66 * See stringh.c.
67 */
68
69/*
70 *@@ strhdup:
71 * like strdup, but this one
72 * doesn't crash if pszSource is NULL,
73 * but returns NULL also.
74 *
75 *@@added V0.9.0 [umoeller]
76 */
77
78PSZ strhdup(const char *pszSource)
79{
80 if (pszSource)
81 return (strdup(pszSource));
82 else
83 return (0);
84}
85
86/*
87 *@@ strhcmp:
88 * better strcmp. This doesn't crash if any of the
89 * string pointers are NULL, but returns a proper
90 * value then.
91 *
92 * Besides, this is guaranteed to only return -1, 0,
93 * or +1, while strcmp can return any positive or
94 * negative value. This is useful for tree comparison
95 * funcs.
96 *
97 *@@added V0.9.9 (2001-02-16) [umoeller]
98 */
99
100int strhcmp(const char *p1, const char *p2)
101{
102 if (p1 && p2)
103 {
104 int i = strcmp(p1, p2);
105 if (i < 0) return (-1);
106 if (i > 0) return (+1);
107 }
108 else if (p1)
109 // but p2 is NULL: p1 greater than p2 then
110 return (+1);
111 else if (p2)
112 // but p1 is NULL: p1 less than p2 then
113 return (-1);
114
115 // return 0 if strcmp returned 0 above or both strings are NULL
116 return (0);
117}
118
119/*
120 *@@ strhicmp:
121 * like strhcmp, but compares without respect
122 * to case.
123 *
124 *@@added V0.9.9 (2001-04-07) [umoeller]
125 */
126
127int strhicmp(const char *p1, const char *p2)
128{
129 if (p1 && p2)
130 {
131 int i = stricmp(p1, p2);
132 if (i < 0) return (-1);
133 if (i > 0) return (+1);
134 }
135 else if (p1)
136 // but p2 is NULL: p1 greater than p2 then
137 return (+1);
138 else if (p2)
139 // but p1 is NULL: p1 less than p2 then
140 return (-1);
141
142 // return 0 if strcmp returned 0 above or both strings are NULL
143 return (0);
144}
145
146/*
147 *@@ strhistr:
148 * like strstr, but case-insensitive.
149 *
150 *@@changed V0.9.0 [umoeller]: crashed if null pointers were passed, thanks Rdiger Ihle
151 */
152
153PSZ strhistr(const char *string1, const char *string2)
154{
155 PSZ prc = NULL;
156
157 if ((string1) && (string2))
158 {
159 PSZ pszSrchIn = strdup(string1);
160 PSZ pszSrchFor = strdup(string2);
161
162 if ((pszSrchIn) && (pszSrchFor))
163 {
164 strupr(pszSrchIn);
165 strupr(pszSrchFor);
166
167 prc = strstr(pszSrchIn, pszSrchFor);
168 if (prc)
169 {
170 // prc now has the first occurence of the string,
171 // but in pszSrchIn; we need to map this
172 // return value to the original string
173 prc = (prc-pszSrchIn) // offset in pszSrchIn
174 + (PSZ)string1;
175 }
176 }
177 if (pszSrchFor)
178 free(pszSrchFor);
179 if (pszSrchIn)
180 free(pszSrchIn);
181 }
182 return (prc);
183}
184
185/*
186 *@@ strhncpy0:
187 * like strncpy, but always appends a 0 character.
188 */
189
190ULONG strhncpy0(PSZ pszTarget,
191 const char *pszSource,
192 ULONG cbSource)
193{
194 ULONG ul = 0;
195 PSZ pTarget = pszTarget,
196 pSource = (PSZ)pszSource;
197
198 for (ul = 0; ul < cbSource; ul++)
199 if (*pSource)
200 *pTarget++ = *pSource++;
201 else
202 break;
203 *pTarget = 0;
204
205 return (ul);
206}
207
208/*
209 * strhCount:
210 * this counts the occurences of c in pszSearch.
211 */
212
213ULONG strhCount(const char *pszSearch,
214 CHAR c)
215{
216 PSZ p = (PSZ)pszSearch;
217 ULONG ulCount = 0;
218 while (TRUE)
219 {
220 p = strchr(p, c);
221 if (p)
222 {
223 ulCount++;
224 p++;
225 }
226 else
227 break;
228 }
229 return (ulCount);
230}
231
232/*
233 *@@ strhIsDecimal:
234 * returns TRUE if psz consists of decimal digits only.
235 */
236
237BOOL strhIsDecimal(PSZ psz)
238{
239 PSZ p = psz;
240 while (*p != 0)
241 {
242 if (isdigit(*p) == 0)
243 return (FALSE);
244 p++;
245 }
246
247 return (TRUE);
248}
249
250/*
251 *@@ strhSubstr:
252 * this creates a new PSZ containing the string
253 * from pBegin to pEnd, excluding the pEnd character.
254 * The new string is null-terminated. The caller
255 * must free() the new string after use.
256 *
257 * Example:
258 + "1234567890"
259 + ^ ^
260 + p1 p2
261 + strhSubstr(p1, p2)
262 * would return a new string containing "2345678".
263 *
264 *@@changed V0.9.9 (2001-04-04) [umoeller]: fixed crashes with invalid pointers
265 *@@changed V0.9.9 (2001-04-04) [umoeller]: now using memcpy for speed
266 */
267
268PSZ strhSubstr(const char *pBegin, // in: first char
269 const char *pEnd) // in: last char (not included)
270{
271 PSZ pszSubstr = NULL;
272
273 if (pEnd > pBegin) // V0.9.9 (2001-04-04) [umoeller]
274 {
275 ULONG cbSubstr = (pEnd - pBegin);
276 pszSubstr = (PSZ)malloc(cbSubstr + 1);
277 if (pszSubstr)
278 {
279 // strhncpy0(pszSubstr, pBegin, cbSubstr);
280 memcpy(pszSubstr, pBegin, cbSubstr); // V0.9.9 (2001-04-04) [umoeller]
281 *(pszSubstr + cbSubstr) = '\0';
282 }
283 }
284
285 return (pszSubstr);
286}
287
288/*
289 *@@ strhExtract:
290 * searches pszBuf for the cOpen character and returns
291 * the data in between cOpen and cClose, excluding
292 * those two characters, in a newly allocated buffer
293 * which you must free() afterwards.
294 *
295 * Spaces and newlines/linefeeds are skipped.
296 *
297 * If the search was successful, the new buffer
298 * is returned and, if (ppEnd != NULL), *ppEnd points
299 * to the first character after the cClose character
300 * found in the buffer.
301 *
302 * If the search was not successful, NULL is
303 * returned, and *ppEnd is unchanged.
304 *
305 * If another cOpen character is found before
306 * cClose, matching cClose characters will be skipped.
307 * You can therefore nest the cOpen and cClose
308 * characters.
309 *
310 * This function ignores cOpen and cClose characters
311 * in C-style comments and strings surrounded by
312 * double quotes.
313 *
314 * Example:
315 + PSZ pszBuf = "KEYWORD { --blah-- } next",
316 + pEnd;
317 + strhExtract(pszBuf,
318 + '{', '}',
319 + &pEnd)
320 * would return a new buffer containing " --blah-- ",
321 * and ppEnd would afterwards point to the space
322 * before "next" in the static buffer.
323 *
324 *@@added V0.9.0 [umoeller]
325 */
326
327PSZ strhExtract(PSZ pszBuf, // in: search buffer
328 CHAR cOpen, // in: opening char
329 CHAR cClose, // in: closing char
330 PSZ *ppEnd) // out: if != NULL, receives first character after closing char
331{
332 PSZ pszReturn = NULL;
333
334 if (pszBuf)
335 {
336 PSZ pOpen = strchr(pszBuf, cOpen);
337 if (pOpen)
338 {
339 // opening char found:
340 // now go thru the whole rest of the buffer
341 PSZ p = pOpen+1;
342 LONG lLevel = 1; // if this goes 0, we're done
343 while (*p)
344 {
345 if (*p == cOpen)
346 lLevel++;
347 else if (*p == cClose)
348 {
349 lLevel--;
350 if (lLevel <= 0)
351 {
352 // matching closing bracket found:
353 // extract string
354 pszReturn = strhSubstr(pOpen+1, // after cOpen
355 p); // excluding cClose
356 if (ppEnd)
357 *ppEnd = p+1;
358 break; // while (*p)
359 }
360 }
361 else if (*p == '\"')
362 {
363 // beginning of string:
364 PSZ p2 = p+1;
365 // find end of string
366 while ((*p2) && (*p2 != '\"'))
367 p2++;
368
369 if (*p2 == '\"')
370 // closing quote found:
371 // search on after that
372 p = p2; // raised below
373 else
374 break; // while (*p)
375 }
376
377 p++;
378 }
379 }
380 }
381
382 return (pszReturn);
383}
384
385/*
386 *@@ strhQuote:
387 * similar to strhExtract, except that
388 * opening and closing chars are the same,
389 * and therefore no nesting is possible.
390 * Useful for extracting stuff between
391 * quotes.
392 *
393 *@@added V0.9.0 [umoeller]
394 */
395
396PSZ strhQuote(PSZ pszBuf,
397 CHAR cQuote,
398 PSZ *ppEnd)
399{
400 PSZ pszReturn = NULL,
401 p1 = NULL;
402 if ((p1 = strchr(pszBuf, cQuote)))
403 {
404 PSZ p2 = strchr(p1+1, cQuote);
405 if (p2)
406 {
407 pszReturn = strhSubstr(p1+1, p2);
408 if (ppEnd)
409 // store closing char
410 *ppEnd = p2 + 1;
411 }
412 }
413
414 return (pszReturn);
415}
416
417/*
418 *@@ strhStrip:
419 * removes all double spaces.
420 * This copies within the "psz" buffer.
421 * If any double spaces are found, the
422 * string will be shorter than before,
423 * but the buffer is _not_ reallocated,
424 * so there will be unused bytes at the
425 * end.
426 *
427 * Returns the number of spaces removed.
428 *
429 *@@added V0.9.0 [umoeller]
430 */
431
432ULONG strhStrip(PSZ psz) // in/out: string
433{
434 PSZ p;
435 ULONG cb = strlen(psz),
436 ulrc = 0;
437
438 for (p = psz; p < psz+cb; p++)
439 {
440 if ((*p == ' ') && (*(p+1) == ' '))
441 {
442 PSZ p2 = p;
443 while (*p2)
444 {
445 *p2 = *(p2+1);
446 p2++;
447 }
448 cb--;
449 p--;
450 ulrc++;
451 }
452 }
453 return (ulrc);
454}
455
456/*
457 *@@ strhins:
458 * this inserts one string into another.
459 *
460 * pszInsert is inserted into pszBuffer at offset
461 * ulInsertOfs (which counts from 0).
462 *
463 * A newly allocated string is returned. pszBuffer is
464 * not changed. The new string should be free()'d after
465 * use.
466 *
467 * Upon errors, NULL is returned.
468 *
469 *@@changed V0.9.0 [umoeller]: completely rewritten.
470 */
471
472PSZ strhins(const char *pcszBuffer,
473 ULONG ulInsertOfs,
474 const char *pcszInsert)
475{
476 PSZ pszNew = NULL;
477
478 if ((pcszBuffer) && (pcszInsert))
479 {
480 do {
481 ULONG cbBuffer = strlen(pcszBuffer);
482 ULONG cbInsert = strlen(pcszInsert);
483
484 // check string length
485 if (ulInsertOfs > cbBuffer + 1)
486 break; // do
487
488 // OK, let's go.
489 pszNew = (PSZ)malloc(cbBuffer + cbInsert + 1); // additional null terminator
490
491 // copy stuff before pInsertPos
492 memcpy(pszNew,
493 pcszBuffer,
494 ulInsertOfs);
495 // copy string to be inserted
496 memcpy(pszNew + ulInsertOfs,
497 pcszInsert,
498 cbInsert);
499 // copy stuff after pInsertPos
500 strcpy(pszNew + ulInsertOfs + cbInsert,
501 pcszBuffer + ulInsertOfs);
502 } while (FALSE);
503 }
504
505 return (pszNew);
506}
507
508/*
509 *@@ strhFindReplace:
510 * wrapper around xstrFindReplace to work with C strings.
511 * Note that *ppszBuf can get reallocated and must
512 * be free()'able.
513 *
514 * Repetitive use of this wrapper is not recommended
515 * because it is considerably slower than xstrFindReplace.
516 *
517 *@@added V0.9.6 (2000-11-01) [umoeller]
518 *@@changed V0.9.7 (2001-01-15) [umoeller]: renamed from strhrpl
519 */
520
521ULONG strhFindReplace(PSZ *ppszBuf, // in/out: string
522 PULONG pulOfs, // in: where to begin search (0 = start);
523 // out: ofs of first char after replacement string
524 const char *pcszSearch, // in: search string; cannot be NULL
525 const char *pcszReplace) // in: replacement string; cannot be NULL
526{
527 ULONG ulrc = 0;
528 XSTRING xstrBuf,
529 xstrFind,
530 xstrReplace;
531 size_t ShiftTable[256];
532 BOOL fRepeat = FALSE;
533 xstrInitSet(&xstrBuf, *ppszBuf);
534 // reallocated and returned, so we're safe
535 xstrInitSet(&xstrFind, (PSZ)pcszSearch);
536 xstrInitSet(&xstrReplace, (PSZ)pcszReplace);
537 // these two are never freed, so we're safe too
538
539 if ((ulrc = xstrFindReplace(&xstrBuf,
540 pulOfs,
541 &xstrFind,
542 &xstrReplace,
543 ShiftTable,
544 &fRepeat)))
545 // replaced:
546 *ppszBuf = xstrBuf.psz;
547
548 return (ulrc);
549}
550
551/*
552 * strhWords:
553 * returns the no. of words in "psz".
554 * A string is considered a "word" if
555 * it is surrounded by spaces only.
556 *
557 *@@added V0.9.0 [umoeller]
558 */
559
560ULONG strhWords(PSZ psz)
561{
562 PSZ p;
563 ULONG cb = strlen(psz),
564 ulWords = 0;
565 if (cb > 1)
566 {
567 ulWords = 1;
568 for (p = psz; p < psz+cb; p++)
569 if (*p == ' ')
570 ulWords++;
571 }
572 return (ulWords);
573}
574
575/*
576 *@@ strhThousandsULong:
577 * converts a ULONG into a decimal string, while
578 * inserting thousands separators into it. Specify
579 * the separator character in cThousands.
580 *
581 * Returns pszTarget so you can use it directly
582 * with sprintf and the "%s" flag.
583 *
584 * For cThousands, you should use the data in
585 * OS2.INI ("PM_National" application), which is
586 * always set according to the "Country" object.
587 * You can use prfhQueryCountrySettings to
588 * retrieve this setting.
589 *
590 * Use strhThousandsDouble for "double" values.
591 */
592
593PSZ strhThousandsULong(PSZ pszTarget, // out: decimal as string
594 ULONG ul, // in: decimal to convert
595 CHAR cThousands) // in: separator char (e.g. '.')
596{
597 USHORT ust, uss, usc;
598 CHAR szTemp[40];
599 sprintf(szTemp, "%lu", ul);
600
601 ust = 0;
602 usc = strlen(szTemp);
603 for (uss = 0; uss < usc; uss++)
604 {
605 if (uss)
606 if (((usc - uss) % 3) == 0)
607 {
608 pszTarget[ust] = cThousands;
609 ust++;
610 }
611 pszTarget[ust] = szTemp[uss];
612 ust++;
613 }
614 pszTarget[ust] = '\0';
615
616 return (pszTarget);
617}
618
619/*
620 *@@ strhThousandsDouble:
621 * like strhThousandsULong, but for a "double"
622 * value. Note that after-comma values are truncated.
623 */
624
625PSZ strhThousandsDouble(PSZ pszTarget, double dbl, CHAR cThousands)
626{
627 USHORT ust, uss, usc;
628 CHAR szTemp[40];
629 sprintf(szTemp, "%.0f", floor(dbl));
630
631 ust = 0;
632 usc = strlen(szTemp);
633 for (uss = 0; uss < usc; uss++)
634 {
635 if (uss)
636 if (((usc - uss) % 3) == 0)
637 {
638 pszTarget[ust] = cThousands;
639 ust++;
640 }
641 pszTarget[ust] = szTemp[uss];
642 ust++;
643 }
644 pszTarget[ust] = '\0';
645
646 return (pszTarget);
647}
648
649/*
650 *@@ strhVariableDouble:
651 * like strhThousandsULong, but for a "double" value, and
652 * with a variable number of decimal places depending on the
653 * size of the quantity.
654 *
655 *@@added V0.9.6 (2000-11-12) [pr]
656 */
657
658PSZ strhVariableDouble(PSZ pszTarget,
659 double dbl,
660 PSZ pszUnits,
661 CHAR cThousands)
662{
663 if (dbl < 100.0)
664 sprintf(pszTarget, "%.2f%s", dbl, pszUnits);
665 else
666 if (dbl < 1000.0)
667 sprintf(pszTarget, "%.1f%s", dbl, pszUnits);
668 else
669 strcat(strhThousandsDouble(pszTarget, dbl, cThousands),
670 pszUnits);
671
672 return(pszTarget);
673}
674
675/*
676 *@@ strhFileDate:
677 * converts file date data to a string (to pszBuf).
678 * You can pass any FDATE structure to this function,
679 * which are returned in those FILEFINDBUF* or
680 * FILESTATUS* structs by the Dos* functions.
681 *
682 * ulDateFormat is the PM setting for the date format,
683 * as set in the "Country" object, and can be queried using
684 + PrfQueryProfileInt(HINI_USER, "PM_National", "iDate", 0);
685 *
686 * meaning:
687 * -- 0 mm.dd.yyyy (English)
688 * -- 1 dd.mm.yyyy (e.g. German)
689 * -- 2 yyyy.mm.dd (Japanese, ISO)
690 * -- 3 yyyy.dd.mm
691 *
692 * cDateSep is used as a date separator (e.g. '.').
693 * This can be queried using:
694 + prfhQueryProfileChar(HINI_USER, "PM_National", "sDate", '/');
695 *
696 * Alternatively, you can query all the country settings
697 * at once using prfhQueryCountrySettings (prfh.c).
698 *
699 *@@changed V0.9.0 (99-11-07) [umoeller]: now calling strhDateTime
700 */
701
702VOID strhFileDate(PSZ pszBuf, // out: string returned
703 FDATE *pfDate, // in: date information
704 ULONG ulDateFormat, // in: date format (0-3)
705 CHAR cDateSep) // in: date separator (e.g. '.')
706{
707 DATETIME dt;
708 dt.day = pfDate->day;
709 dt.month = pfDate->month;
710 dt.year = pfDate->year + 1980;
711
712 strhDateTime(pszBuf,
713 NULL, // no time
714 &dt,
715 ulDateFormat,
716 cDateSep,
717 0, 0); // no time
718}
719
720/*
721 *@@ strhFileTime:
722 * converts file time data to a string (to pszBuf).
723 * You can pass any FTIME structure to this function,
724 * which are returned in those FILEFINDBUF* or
725 * FILESTATUS* structs by the Dos* functions.
726 *
727 * ulTimeFormat is the PM setting for the time format,
728 * as set in the "Country" object, and can be queried using
729 + PrfQueryProfileInt(HINI_USER, "PM_National", "iTime", 0);
730 * meaning:
731 * -- 0 12-hour clock
732 * -- >0 24-hour clock
733 *
734 * cDateSep is used as a time separator (e.g. ':').
735 * This can be queried using:
736 + prfhQueryProfileChar(HINI_USER, "PM_National", "sTime", ':');
737 *
738 * Alternatively, you can query all the country settings
739 * at once using prfhQueryCountrySettings (prfh.c).
740 *
741 *@@changed V0.8.5 (99-03-15) [umoeller]: fixed 12-hour crash
742 *@@changed V0.9.0 (99-11-07) [umoeller]: now calling strhDateTime
743 */
744
745VOID strhFileTime(PSZ pszBuf, // out: string returned
746 FTIME *pfTime, // in: time information
747 ULONG ulTimeFormat, // in: 24-hour time format (0 or 1)
748 CHAR cTimeSep) // in: time separator (e.g. ':')
749{
750 DATETIME dt;
751 dt.hours = pfTime->hours;
752 dt.minutes = pfTime->minutes;
753 dt.seconds = pfTime->twosecs * 2;
754
755 strhDateTime(NULL, // no date
756 pszBuf,
757 &dt,
758 0, 0, // no date
759 ulTimeFormat,
760 cTimeSep);
761}
762
763/*
764 *@@ strhDateTime:
765 * converts Control Program DATETIME info
766 * into two strings. See strhFileDate and strhFileTime
767 * for more detailed parameter descriptions.
768 *
769 *@@added V0.9.0 (99-11-07) [umoeller]
770 */
771
772VOID strhDateTime(PSZ pszDate, // out: date string returned (can be NULL)
773 PSZ pszTime, // out: time string returned (can be NULL)
774 DATETIME *pDateTime, // in: date/time information
775 ULONG ulDateFormat, // in: date format (0-3); see strhFileDate
776 CHAR cDateSep, // in: date separator (e.g. '.')
777 ULONG ulTimeFormat, // in: 24-hour time format (0 or 1); see strhFileTime
778 CHAR cTimeSep) // in: time separator (e.g. ':')
779{
780 if (pszDate)
781 {
782 switch (ulDateFormat)
783 {
784 case 0: // mm.dd.yyyy (English)
785 sprintf(pszDate, "%02d%c%02d%c%04d",
786 pDateTime->month,
787 cDateSep,
788 pDateTime->day,
789 cDateSep,
790 pDateTime->year);
791 break;
792
793 case 1: // dd.mm.yyyy (e.g. German)
794 sprintf(pszDate, "%02d%c%02d%c%04d",
795 pDateTime->day,
796 cDateSep,
797 pDateTime->month,
798 cDateSep,
799 pDateTime->year);
800 break;
801
802 case 2: // yyyy.mm.dd (Japanese)
803 sprintf(pszDate, "%04d%c%02d%c%02d",
804 pDateTime->year,
805 cDateSep,
806 pDateTime->month,
807 cDateSep,
808 pDateTime->day);
809 break;
810
811 default: // yyyy.dd.mm
812 sprintf(pszDate, "%04d%c%02d%c%02d",
813 pDateTime->year,
814 cDateSep,
815 pDateTime->day,
816 cDateSep,
817 pDateTime->month);
818 break;
819 }
820 }
821
822 if (pszTime)
823 {
824 if (ulTimeFormat == 0)
825 {
826 // for 12-hour clock, we need additional INI data
827 CHAR szAMPM[10] = "err";
828
829 if (pDateTime->hours > 12)
830 {
831 // > 12h: PM.
832
833 // Note: 12:xx noon is 12 AM, not PM (even though
834 // AM stands for "ante meridiam", but English is just
835 // not logical), so that's handled below.
836
837 PrfQueryProfileString(HINI_USER,
838 "PM_National",
839 "s2359", // key
840 "PM", // default
841 szAMPM, sizeof(szAMPM)-1);
842 sprintf(pszTime, "%02d%c%02d%c%02d %s",
843 // leave 12 == 12 (not 0)
844 pDateTime->hours % 12,
845 cTimeSep,
846 pDateTime->minutes,
847 cTimeSep,
848 pDateTime->seconds,
849 szAMPM);
850 }
851 else
852 {
853 // <= 12h: AM
854 PrfQueryProfileString(HINI_USER,
855 "PM_National",
856 "s1159", // key
857 "AM", // default
858 szAMPM, sizeof(szAMPM)-1);
859 sprintf(pszTime, "%02d%c%02d%c%02d %s",
860 pDateTime->hours,
861 cTimeSep,
862 pDateTime->minutes,
863 cTimeSep,
864 pDateTime->seconds,
865 szAMPM);
866 }
867 }
868 else
869 // 24-hour clock
870 sprintf(pszTime, "%02d%c%02d%c%02d",
871 pDateTime->hours,
872 cTimeSep,
873 pDateTime->minutes,
874 cTimeSep,
875 pDateTime->seconds);
876 }
877}
878
879/*
880 *@@ strhGetWord:
881 * finds word boundaries.
882 *
883 * *ppszStart is used as the beginning of the
884 * search.
885 *
886 * If a word is found, *ppszStart is set to
887 * the first character of the word which was
888 * found and *ppszEnd receives the address
889 * of the first character _after_ the word,
890 * which is probably a space or a \n or \r char.
891 * We then return TRUE.
892 *
893 * The search is stopped if a null character
894 * is found or pLimit is reached. In that case,
895 * FALSE is returned.
896 *
897 *@@added V0.9.1 (2000-02-13) [umoeller]
898 */
899
900BOOL strhGetWord(PSZ *ppszStart, // in: start of search,
901 // out: start of word (if TRUE is returned)
902 const char *pLimit, // in: ptr to last char after *ppszStart to be
903 // searched; if the word does not end before
904 // or with this char, FALSE is returned
905 const char *pcszBeginChars, // stringh.h defines STRH_BEGIN_CHARS
906 const char *pcszEndChars, // stringh.h defines STRH_END_CHARS
907 PSZ *ppszEnd) // out: first char _after_ word
908 // (if TRUE is returned)
909{
910 // characters after which a word can be started
911 // const char *pcszBeginChars = "\x0d\x0a ";
912 // const char *pcszEndChars = "\x0d\x0a /-";
913
914 PSZ pStart = *ppszStart;
915
916 // find start of word
917 while ( (pStart < (PSZ)pLimit)
918 && (strchr(pcszBeginChars, *pStart))
919 )
920 // if char is a "before word" char: go for next
921 pStart++;
922
923 if (pStart < (PSZ)pLimit)
924 {
925 // found a valid "word start" character
926 // (which is not in pcszBeginChars):
927
928 // find end of word
929 PSZ pEndOfWord = pStart;
930 while ( (pEndOfWord <= (PSZ)pLimit)
931 && (strchr(pcszEndChars, *pEndOfWord) == 0)
932 )
933 // if char is not an "end word" char: go for next
934 pEndOfWord++;
935
936 if (pEndOfWord <= (PSZ)pLimit)
937 {
938 // whoa, got a word:
939 *ppszStart = pStart;
940 *ppszEnd = pEndOfWord;
941 return (TRUE);
942 }
943 }
944
945 return (FALSE);
946}
947
948/*
949 *@@ strhIsWord:
950 * returns TRUE if p points to a "word"
951 * in pcszBuf.
952 *
953 * p is considered a word if the character _before_
954 * it is in pcszBeginChars and the char _after_
955 * it (i.e. *(p+cbSearch)) is in pcszEndChars.
956 *
957 *@@added V0.9.6 (2000-11-12) [umoeller]
958 */
959
960BOOL strhIsWord(const char *pcszBuf,
961 const char *p, // in: start of word
962 ULONG cbSearch, // in: length of word
963 const char *pcszBeginChars, // suggestion: "\x0d\x0a ()/\\-,."
964 const char *pcszEndChars) // suggestion: "\x0d\x0a ()/\\-,.:;"
965{
966 BOOL fEndOK = FALSE;
967
968 // check previous char
969 if ( (p == pcszBuf)
970 || (strchr(pcszBeginChars, *(p-1)))
971 )
972 {
973 // OK, valid begin char:
974 // check end char
975 CHAR cNextChar = *(p + cbSearch);
976 if (cNextChar == 0)
977 fEndOK = TRUE;
978 else
979 {
980 char *pc = strchr(pcszEndChars, cNextChar);
981 if (pc)
982 // OK, is end char: avoid doubles of that char,
983 // but allow spaces
984 if ( (cNextChar+1 != *pc)
985 || (cNextChar+1 == ' ')
986 || (cNextChar+1 == 0)
987 )
988 fEndOK = TRUE;
989 }
990 }
991
992 return (fEndOK);
993}
994
995/*
996 *@@ strhFindWord:
997 * searches for pszSearch in pszBuf, which is
998 * returned if found (or NULL if not).
999 *
1000 * As opposed to strstr, this finds pszSearch
1001 * only if it is a "word". A search string is
1002 * considered a word if the character _before_
1003 * it is in pcszBeginChars and the char _after_
1004 * it is in pcszEndChars.
1005 *
1006 * Example:
1007 + strhFindWord("This is an example.", "is");
1008 + returns ...........^ this, but not the "is" in "This".
1009 *
1010 * The algorithm here uses strstr to find pszSearch in pszBuf
1011 * and performs additional "is-word" checks for each item found
1012 * (by calling strhIsWord).
1013 *
1014 * Note that this function is fairly slow compared to xstrFindWord.
1015 *
1016 *@@added V0.9.0 (99-11-08) [umoeller]
1017 *@@changed V0.9.0 (99-11-10) [umoeller]: tried second algorithm, reverted to original...
1018 */
1019
1020PSZ strhFindWord(const char *pszBuf,
1021 const char *pszSearch,
1022 const char *pcszBeginChars, // suggestion: "\x0d\x0a ()/\\-,."
1023 const char *pcszEndChars) // suggestion: "\x0d\x0a ()/\\-,.:;"
1024{
1025 PSZ pszReturn = 0;
1026 ULONG cbBuf = strlen(pszBuf),
1027 cbSearch = strlen(pszSearch);
1028
1029 if ((cbBuf) && (cbSearch))
1030 {
1031 const char *p = pszBuf;
1032
1033 do // while p
1034 {
1035 p = strstr(p, pszSearch);
1036 if (p)
1037 {
1038 // string found:
1039 // check if that's a word
1040
1041 if (strhIsWord(pszBuf,
1042 p,
1043 cbSearch,
1044 pcszBeginChars,
1045 pcszEndChars))
1046 {
1047 // valid end char:
1048 pszReturn = (PSZ)p;
1049 break;
1050 }
1051
1052 p += cbSearch;
1053 }
1054 } while (p);
1055
1056 }
1057 return (pszReturn);
1058}
1059
1060/*
1061 *@@ strhFindEOL:
1062 * returns a pointer to the next \r, \n or null character
1063 * following pszSearchIn. Stores the offset in *pulOffset.
1064 *
1065 * This should never return NULL because at some point,
1066 * there will be a null byte in your string.
1067 *
1068 *@@added V0.9.4 (2000-07-01) [umoeller]
1069 */
1070
1071PSZ strhFindEOL(const char *pcszSearchIn, // in: where to search
1072 PULONG pulOffset) // out: offset (ptr can be NULL)
1073{
1074 const char *p = pcszSearchIn,
1075 *prc = 0;
1076 while (TRUE)
1077 {
1078 if ( (*p == '\r') || (*p == '\n') || (*p == 0) )
1079 {
1080 prc = p;
1081 break;
1082 }
1083 p++;
1084 }
1085
1086 if ((pulOffset) && (prc))
1087 *pulOffset = prc - pcszSearchIn;
1088
1089 return ((PSZ)prc);
1090}
1091
1092/*
1093 *@@ strhFindNextLine:
1094 * like strhFindEOL, but this returns the character
1095 * _after_ \r or \n. Note that this might return
1096 * a pointer to terminating NULL character also.
1097 */
1098
1099PSZ strhFindNextLine(PSZ pszSearchIn, PULONG pulOffset)
1100{
1101 PSZ pEOL = strhFindEOL(pszSearchIn, NULL);
1102 // pEOL now points to the \r char or the terminating 0 byte;
1103 // if not null byte, advance pointer
1104 PSZ pNextLine = pEOL;
1105 if (*pNextLine == '\r')
1106 pNextLine++;
1107 if (*pNextLine == '\n')
1108 pNextLine++;
1109 if (pulOffset)
1110 *pulOffset = pNextLine - pszSearchIn;
1111 return (pNextLine);
1112}
1113
1114/*
1115 *@@ strhBeautifyTitle:
1116 * replaces all line breaks (0xd, 0xa) with spaces.
1117 */
1118
1119BOOL strhBeautifyTitle(PSZ psz)
1120{
1121 BOOL rc = FALSE;
1122 CHAR *p;
1123 while ((p = strchr(psz, 0xa)))
1124 {
1125 *p = ' ';
1126 rc = TRUE;
1127 }
1128 while ((p = strchr(psz, 0xd)))
1129 {
1130 *p = ' ';
1131 rc = TRUE;
1132 }
1133 return (rc);
1134}
1135
1136/*
1137 * strhFindAttribValue:
1138 * searches for pszAttrib in pszSearchIn; if found,
1139 * returns the first character after the "=" char.
1140 * If "=" is not found, a space, \r, and \n are
1141 * also accepted. This function searches without
1142 * respecting case.
1143 *
1144 * <B>Example:</B>
1145 + strhFindAttribValue("<PAGE BLAH="data">, "BLAH")
1146 +
1147 + returns ....................... ^ this address.
1148 *
1149 *@@added V0.9.0 [umoeller]
1150 *@@changed V0.9.3 (2000-05-19) [umoeller]: some speed optimizations
1151 */
1152
1153PSZ strhFindAttribValue(const char *pszSearchIn, const char *pszAttrib)
1154{
1155 PSZ prc = 0;
1156 PSZ pszSearchIn2 = (PSZ)pszSearchIn,
1157 p,
1158 p2;
1159 ULONG cbAttrib = strlen(pszAttrib);
1160
1161 // 1) find space char
1162 while ((p = strchr(pszSearchIn2, ' ')))
1163 {
1164 CHAR c;
1165 p++;
1166 if (strlen(p) >= cbAttrib) // V0.9.9 (2001-03-27) [umoeller]
1167 {
1168 c = *(p+cbAttrib); // V0.9.3 (2000-05-19) [umoeller]
1169 // now check whether the p+strlen(pszAttrib)
1170 // is a valid end-of-tag character
1171 if ( (memicmp(p, (PVOID)pszAttrib, cbAttrib) == 0)
1172 && ( (c == ' ')
1173 || (c == '>')
1174 || (c == '=')
1175 || (c == '\r')
1176 || (c == '\n')
1177 || (c == 0)
1178 )
1179 )
1180 {
1181 // yes:
1182 CHAR c2;
1183 p2 = p + cbAttrib;
1184 c2 = *p2;
1185 while ( ( (c2 == ' ')
1186 || (c2 == '=')
1187 || (c2 == '\n')
1188 || (c2 == '\r')
1189 )
1190 && (c2 != 0)
1191 )
1192 c2 = *++p2;
1193
1194 prc = p2;
1195 break; // first while
1196 }
1197 }
1198 else
1199 break;
1200
1201 pszSearchIn2++;
1202 }
1203 return (prc);
1204}
1205
1206/*
1207 * strhGetNumAttribValue:
1208 * stores the numerical parameter value of an HTML-style
1209 * tag in *pl.
1210 *
1211 * Returns the address of the tag parameter in the
1212 * search buffer, if found, or NULL.
1213 *
1214 * <B>Example:</B>
1215 + strhGetNumAttribValue("<PAGE BLAH=123>, "BLAH", &l);
1216 *
1217 * stores 123 in the "l" variable.
1218 *
1219 *@@added V0.9.0 [umoeller]
1220 *@@changed V0.9.9 (2001-04-04) [umoeller]: this failed on "123" strings in quotes, fixed
1221 */
1222
1223PSZ strhGetNumAttribValue(const char *pszSearchIn, // in: where to search
1224 const char *pszTag, // e.g. "INDEX"
1225 PLONG pl) // out: numerical value
1226{
1227 PSZ pParam;
1228 if ((pParam = strhFindAttribValue(pszSearchIn, pszTag)))
1229 {
1230 if ( (*pParam == '\"')
1231 || (*pParam == '\'')
1232 )
1233 pParam++; // V0.9.9 (2001-04-04) [umoeller]
1234
1235 sscanf(pParam, "%ld", pl);
1236 }
1237
1238 return (pParam);
1239}
1240
1241/*
1242 * strhGetTextAttr:
1243 * retrieves the attribute value of a textual HTML-style tag
1244 * in a newly allocated buffer, which is returned,
1245 * or NULL if attribute not found.
1246 * If an attribute value is to contain spaces, it
1247 * must be enclosed in quotes.
1248 *
1249 * The offset of the attribute data in pszSearchIn is
1250 * returned in *pulOffset so that you can do multiple
1251 * searches.
1252 *
1253 * This returns a new buffer, which should be free()'d after use.
1254 *
1255 * <B>Example:</B>
1256 + ULONG ulOfs = 0;
1257 + strhGetTextAttr("<PAGE BLAH="blublub">, "BLAH", &ulOfs)
1258 + ............^ ulOfs
1259 *
1260 * returns a new string with the value "blublub" (without
1261 * quotes) and sets ulOfs to 12.
1262 *
1263 *@@added V0.9.0 [umoeller]
1264 */
1265
1266PSZ strhGetTextAttr(const char *pszSearchIn,
1267 const char *pszTag,
1268 PULONG pulOffset) // out: offset where found
1269{
1270 PSZ pParam,
1271 pParam2,
1272 prc = NULL;
1273 ULONG ulCount = 0;
1274 LONG lNestingLevel = 0;
1275
1276 if ((pParam = strhFindAttribValue(pszSearchIn, pszTag)))
1277 {
1278 // determine end character to search for: a space
1279 CHAR cEnd = ' ';
1280 if (*pParam == '\"')
1281 {
1282 // or, if the data is enclosed in quotes, a quote
1283 cEnd = '\"';
1284 pParam++;
1285 }
1286
1287 if (pulOffset)
1288 // store the offset
1289 (*pulOffset) = pParam - (PSZ)pszSearchIn;
1290
1291 // now find end of attribute
1292 pParam2 = pParam;
1293 while (*pParam)
1294 {
1295 if (*pParam == cEnd)
1296 // end character found
1297 break;
1298 else if (*pParam == '<')
1299 // yet another opening tag found:
1300 // this is probably some "<" in the attributes
1301 lNestingLevel++;
1302 else if (*pParam == '>')
1303 {
1304 lNestingLevel--;
1305 if (lNestingLevel < 0)
1306 // end of tag found:
1307 break;
1308 }
1309 ulCount++;
1310 pParam++;
1311 }
1312
1313 // copy attribute to new buffer
1314 if (ulCount)
1315 {
1316 prc = (PSZ)malloc(ulCount+1);
1317 memcpy(prc, pParam2, ulCount);
1318 *(prc+ulCount) = 0;
1319 }
1320 }
1321 return (prc);
1322}
1323
1324/*
1325 * strhFindEndOfTag:
1326 * returns a pointer to the ">" char
1327 * which seems to terminate the tag beginning
1328 * after pszBeginOfTag.
1329 *
1330 * If additional "<" chars are found, we look
1331 * for additional ">" characters too.
1332 *
1333 * Note: You must pass the address of the opening
1334 * '<' character to this function.
1335 *
1336 * Example:
1337 + PSZ pszTest = "<BODY ATTR=\"<BODY>\">";
1338 + strhFindEndOfTag(pszTest)
1339 + returns.................................^ this.
1340 *
1341 *@@added V0.9.0 [umoeller]
1342 */
1343
1344PSZ strhFindEndOfTag(const char *pszBeginOfTag)
1345{
1346 PSZ p = (PSZ)pszBeginOfTag,
1347 prc = NULL;
1348 LONG lNestingLevel = 0;
1349
1350 while (*p)
1351 {
1352 if (*p == '<')
1353 // another opening tag found:
1354 lNestingLevel++;
1355 else if (*p == '>')
1356 {
1357 // closing tag found:
1358 lNestingLevel--;
1359 if (lNestingLevel < 1)
1360 {
1361 // corresponding: return this
1362 prc = p;
1363 break;
1364 }
1365 }
1366 p++;
1367 }
1368
1369 return (prc);
1370}
1371
1372/*
1373 * strhGetBlock:
1374 * this complex function searches the given string
1375 * for a pair of opening/closing HTML-style tags.
1376 *
1377 * If found, this routine returns TRUE and does
1378 * the following:
1379 *
1380 * 1) allocate a new buffer, copy the text
1381 * enclosed by the opening/closing tags
1382 * into it and set *ppszBlock to that
1383 * buffer;
1384 *
1385 * 2) if the opening tag has any attributes,
1386 * allocate another buffer, copy the
1387 * attributes into it and set *ppszAttrs
1388 * to that buffer; if no attributes are
1389 * found, *ppszAttrs will be NULL;
1390 *
1391 * 3) set *pulOffset to the offset from the
1392 * beginning of *ppszSearchIn where the
1393 * opening tag was found;
1394 *
1395 * 4) advance *ppszSearchIn to after the
1396 * closing tag, so that you can do
1397 * multiple searches without finding the
1398 * same tags twice.
1399 *
1400 * All buffers should be freed using free().
1401 *
1402 * This returns the following:
1403 * -- 0: no error
1404 * -- 1: tag not found at all (doesn't have to be an error)
1405 * -- 2: begin tag found, but no corresponding end tag found. This
1406 * is a real error.
1407 * -- 3: begin tag is not terminated by "&gt;" (e.g. "&lt;BEGINTAG whatever")
1408 *
1409 * <B>Example:</B>
1410 + PSZ pSearch = "&lt;PAGE INDEX=1&gt;This is page 1.&lt;/PAGE&gt;More text."
1411 + PSZ pszBlock, pszAttrs;
1412 + ULONG ulOfs;
1413 + strhGetBlock(&pSearch, "PAGE", &pszBlock, &pszAttrs, &ulOfs)
1414 *
1415 * would do the following:
1416 *
1417 * 1) set pszBlock to a new string containing "This is page 1."
1418 * without quotes;
1419 *
1420 * 2) set pszAttrs to a new string containing "&lt;PAGE INDEX=1&gt;";
1421 *
1422 * 3) set ulOfs to 0, because "&lt;PAGE" was found at the beginning;
1423 *
1424 * 4) pSearch would be advanced to point to the "More text"
1425 * string in the original buffer.
1426 *
1427 * Hey-hey. A one-shot function, fairly complicated, but indispensable
1428 * for HTML parsing.
1429 *
1430 *@@added V0.9.0 [umoeller]
1431 *@@changed V0.9.1 (2000-01-03) [umoeller]: fixed heap overwrites (thanks to string debugging)
1432 *@@changed V0.9.1 (2000-01-06) [umoeller]: changed prototype
1433 *@@changed V0.9.3 (2000-05-06) [umoeller]: NULL string check was missing
1434 */
1435
1436ULONG strhGetBlock(const char *pszSearchIn, // in: buffer to search
1437 PULONG pulSearchOffset, // in/out: offset where to start search (0 for beginning)
1438 PSZ pszTag,
1439 PSZ *ppszBlock, // out: block enclosed by the tags
1440 PSZ *ppszAttribs, // out: attributes of the opening tag
1441 PULONG pulOfsBeginTag, // out: offset from pszSearchIn where opening tag was found
1442 PULONG pulOfsBeginBlock) // out: offset from pszSearchIn where beginning of block was found
1443{
1444 ULONG ulrc = 1;
1445 PSZ pszBeginTag = (PSZ)pszSearchIn + *pulSearchOffset,
1446 pszSearch2 = pszBeginTag,
1447 pszClosingTag;
1448 ULONG cbTag = strlen(pszTag);
1449
1450 // go thru the block and check all tags if it's the
1451 // begin tag we're looking for
1452 while ((pszBeginTag = strchr(pszBeginTag, '<')))
1453 {
1454 if (memicmp(pszBeginTag+1, pszTag, strlen(pszTag)) == 0)
1455 // yes: stop
1456 break;
1457 else
1458 pszBeginTag++;
1459 }
1460
1461 if (pszBeginTag)
1462 {
1463 // we found <TAG>:
1464 ULONG ulNestingLevel = 0;
1465
1466 PSZ pszEndOfBeginTag = strhFindEndOfTag(pszBeginTag);
1467 // strchr(pszBeginTag, '>');
1468 if (pszEndOfBeginTag)
1469 {
1470 // does the caller want the attributes?
1471 if (ppszAttribs)
1472 {
1473 // yes: then copy them
1474 ULONG ulAttrLen = pszEndOfBeginTag - pszBeginTag;
1475 PSZ pszAttrs = (PSZ)malloc(ulAttrLen + 1);
1476 strncpy(pszAttrs, pszBeginTag, ulAttrLen);
1477 // add terminating 0
1478 *(pszAttrs + ulAttrLen) = 0;
1479
1480 *ppszAttribs = pszAttrs;
1481 }
1482
1483 // output offset of where we found the begin tag
1484 if (pulOfsBeginTag)
1485 *pulOfsBeginTag = pszBeginTag - (PSZ)pszSearchIn;
1486
1487 // now find corresponding closing tag (e.g. "</BODY>"
1488 pszBeginTag = pszEndOfBeginTag+1;
1489 // now we're behind the '>' char of the opening tag
1490 // increase offset of that too
1491 if (pulOfsBeginBlock)
1492 *pulOfsBeginBlock = pszBeginTag - (PSZ)pszSearchIn;
1493
1494 // find next closing tag;
1495 // for the first run, pszSearch2 points to right
1496 // after the '>' char of the opening tag
1497 pszSearch2 = pszBeginTag;
1498 while ( (pszSearch2) // fixed V0.9.3 (2000-05-06) [umoeller]
1499 && (pszClosingTag = strstr(pszSearch2, "<"))
1500 )
1501 {
1502 // if we have another opening tag before our closing
1503 // tag, we need to have several closing tags before
1504 // we're done
1505 if (memicmp(pszClosingTag+1, pszTag, cbTag) == 0)
1506 ulNestingLevel++;
1507 else
1508 {
1509 // is this ours?
1510 if ( (*(pszClosingTag+1) == '/')
1511 && (memicmp(pszClosingTag+2, pszTag, cbTag) == 0)
1512 )
1513 {
1514 // we've found a matching closing tag; is
1515 // it ours?
1516 if (ulNestingLevel == 0)
1517 {
1518 // our closing tag found:
1519 // allocate mem for a new buffer
1520 // and extract all the text between
1521 // open and closing tags to it
1522 ULONG ulLen = pszClosingTag - pszBeginTag;
1523 if (ppszBlock)
1524 {
1525 PSZ pNew = (PSZ)malloc(ulLen + 1);
1526 strhncpy0(pNew, pszBeginTag, ulLen);
1527 *ppszBlock = pNew;
1528 }
1529
1530 // raise search offset to after the closing tag
1531 *pulSearchOffset = (pszClosingTag + cbTag + 1) - (PSZ)pszSearchIn;
1532
1533 ulrc = 0;
1534
1535 break;
1536 } else
1537 // not our closing tag:
1538 ulNestingLevel--;
1539 }
1540 }
1541 // no matching closing tag: search on after that
1542 pszSearch2 = strhFindEndOfTag(pszClosingTag);
1543 } // end while (pszClosingTag = strstr(pszSearch2, "<"))
1544
1545 if (!pszClosingTag)
1546 // no matching closing tag found:
1547 // return 2 (closing tag not found)
1548 ulrc = 2;
1549 } // end if (pszBeginTag)
1550 else
1551 // no matching ">" for opening tag found:
1552 ulrc = 3;
1553 }
1554
1555 return (ulrc);
1556}
1557
1558/* ******************************************************************
1559 *
1560 * Miscellaneous
1561 *
1562 ********************************************************************/
1563
1564/*
1565 *@@ strhArrayAppend:
1566 * this appends a string to a "string array".
1567 *
1568 * A string array is considered a sequence of
1569 * zero-terminated strings in memory. That is,
1570 * after each string's null-byte, the next
1571 * string comes up.
1572 *
1573 * This is useful for composing a single block
1574 * of memory from, say, list box entries, which
1575 * can then be written to OS2.INI in one flush.
1576 *
1577 * To append strings to such an array, call this
1578 * function for each string you wish to append.
1579 * This will re-allocate *ppszRoot with each call,
1580 * and update *pcbRoot, which then contains the
1581 * total size of all strings (including all null
1582 * terminators).
1583 *
1584 * Pass *pcbRoot to PrfSaveProfileData to have the
1585 * block saved.
1586 *
1587 * Note: On the first call, *ppszRoot and *pcbRoot
1588 * _must_ be both NULL, or this crashes.
1589 */
1590
1591VOID strhArrayAppend(PSZ *ppszRoot, // in: root of array
1592 const char *pcszNew, // in: string to append
1593 PULONG pcbRoot) // in/out: size of array
1594{
1595 ULONG cbNew = strlen(pcszNew);
1596 PSZ pszTemp = (PSZ)malloc(*pcbRoot
1597 + cbNew
1598 + 1); // two null bytes
1599 if (*ppszRoot)
1600 {
1601 // not first loop: copy old stuff
1602 memcpy(pszTemp,
1603 *ppszRoot,
1604 *pcbRoot);
1605 free(*ppszRoot);
1606 }
1607 // append new string
1608 strcpy(pszTemp + *pcbRoot,
1609 pcszNew);
1610 // update root
1611 *ppszRoot = pszTemp;
1612 // update length
1613 *pcbRoot += cbNew + 1;
1614}
1615
1616/*
1617 *@@ strhCreateDump:
1618 * this dumps a memory block into a string
1619 * and returns that string in a new buffer.
1620 *
1621 * You must free() the returned PSZ after use.
1622 *
1623 * The output looks like the following:
1624 *
1625 + 0000: FE FF 0E 02 90 00 00 00 ........
1626 + 0008: FD 01 00 00 57 50 46 6F ....WPFo
1627 + 0010: 6C 64 65 72 00 78 01 34 lder.x.4
1628 *
1629 * Each line is terminated with a newline (\n)
1630 * character only.
1631 *
1632 *@@added V0.9.1 (2000-01-22) [umoeller]
1633 */
1634
1635PSZ strhCreateDump(PBYTE pb, // in: start address of buffer
1636 ULONG ulSize, // in: size of buffer
1637 ULONG ulIndent) // in: indentation of every line
1638{
1639 PSZ pszReturn = 0;
1640 XSTRING strReturn;
1641 CHAR szTemp[1000];
1642
1643 PBYTE pbCurrent = pb; // current byte
1644 ULONG ulCount = 0,
1645 ulCharsInLine = 0; // if this grows > 7, a new line is started
1646 CHAR szLine[400] = "",
1647 szAscii[30] = " "; // ASCII representation; filled for every line
1648 PSZ pszLine = szLine,
1649 pszAscii = szAscii;
1650
1651 xstrInit(&strReturn, (ulSize * 30) + ulIndent);
1652
1653 for (pbCurrent = pb;
1654 ulCount < ulSize;
1655 pbCurrent++, ulCount++)
1656 {
1657 if (ulCharsInLine == 0)
1658 {
1659 memset(szLine, ' ', ulIndent);
1660 pszLine += ulIndent;
1661 }
1662 pszLine += sprintf(pszLine, "%02lX ", (ULONG)*pbCurrent);
1663
1664 if ( (*pbCurrent > 31) && (*pbCurrent < 127) )
1665 // printable character:
1666 *pszAscii = *pbCurrent;
1667 else
1668 *pszAscii = '.';
1669 pszAscii++;
1670
1671 ulCharsInLine++;
1672 if ( (ulCharsInLine > 7) // 8 bytes added?
1673 || (ulCount == ulSize-1) // end of buffer reached?
1674 )
1675 {
1676 // if we haven't had eight bytes yet,
1677 // fill buffer up to eight bytes with spaces
1678 ULONG ul2;
1679 for (ul2 = ulCharsInLine;
1680 ul2 < 8;
1681 ul2++)
1682 pszLine += sprintf(pszLine, " ");
1683
1684 sprintf(szTemp, "%04lX: %s %s\n",
1685 (ulCount & 0xFFFFFFF8), // offset in hex
1686 szLine, // bytes string
1687 szAscii); // ASCII string
1688 xstrcat(&strReturn, szTemp, 0);
1689
1690 // restart line buffer
1691 pszLine = szLine;
1692
1693 // clear ASCII buffer
1694 strcpy(szAscii, " ");
1695 pszAscii = szAscii;
1696
1697 // reset line counter
1698 ulCharsInLine = 0;
1699 }
1700 }
1701
1702 if (strReturn.cbAllocated)
1703 pszReturn = strReturn.psz;
1704
1705 return (pszReturn);
1706}
1707
1708/* ******************************************************************
1709 *
1710 * Wildcard matching
1711 *
1712 ********************************************************************/
1713
1714/*
1715 * The following code has been taken from "fnmatch.zip".
1716 *
1717 * (c) 1994-1996 by Eberhard Mattes.
1718 */
1719
1720/* In OS/2 and DOS styles, both / and \ separate components of a path.
1721 * This macro returns true iff C is a separator. */
1722
1723#define IS_OS2_COMP_SEP(C) ((C) == '/' || (C) == '\\')
1724
1725
1726/* This macro returns true if C is at the end of a component of a
1727 * path. */
1728
1729#define IS_OS2_COMP_END(C) ((C) == 0 || IS_OS2_COMP_SEP (C))
1730
1731/*
1732 * skip_comp_os2:
1733 * Return a pointer to the next component of the path SRC, for OS/2
1734 * and DOS styles. When the end of the string is reached, a pointer
1735 * to the terminating null character is returned.
1736 *
1737 * (c) 1994-1996 by Eberhard Mattes.
1738 */
1739
1740static const unsigned char* skip_comp_os2(const unsigned char *src)
1741{
1742 /* Skip characters until hitting a separator or the end of the
1743 * string. */
1744
1745 while (!IS_OS2_COMP_END(*src))
1746 ++src;
1747
1748 /* Skip the separator if we hit a separator. */
1749
1750 if (*src != 0)
1751 ++src;
1752 return src;
1753}
1754
1755/*
1756 * has_colon:
1757 * returns true iff the path P contains a colon.
1758 *
1759 * (c) 1994-1996 by Eberhard Mattes.
1760 */
1761
1762static int has_colon(const unsigned char *p)
1763{
1764 while (*p != 0)
1765 if (*p == ':')
1766 return 1;
1767 else
1768 ++p;
1769 return 0;
1770}
1771
1772/*
1773 * match_comp_os2:
1774 * Compare a single component (directory name or file name) of the
1775 * paths, for OS/2 and DOS styles. MASK and NAME point into a
1776 * component of the wildcard and the name to be checked, respectively.
1777 * Comparing stops at the next separator. The FLAGS argument is the
1778 * same as that of fnmatch(). HAS_DOT is true if a dot is in the
1779 * current component of NAME. The number of dots is not restricted,
1780 * even in DOS style. Return FNM_MATCH iff MASK and NAME match.
1781 * Note that this function is recursive.
1782 *
1783 * (c) 1994-1996 by Eberhard Mattes.
1784 */
1785
1786static int match_comp_os2(const unsigned char *mask,
1787 const unsigned char *name,
1788 unsigned flags,
1789 int has_dot)
1790{
1791 int rc;
1792
1793 for (;;)
1794 switch (*mask)
1795 {
1796 case 0:
1797
1798 /* There must be no extra characters at the end of NAME when
1799 * reaching the end of MASK unless _FNM_PATHPREFIX is set:
1800 * in that case, NAME may point to a separator. */
1801
1802 if (*name == 0)
1803 return FNM_MATCH;
1804 if ((flags & _FNM_PATHPREFIX) && IS_OS2_COMP_SEP(*name))
1805 return FNM_MATCH;
1806 return FNM_NOMATCH;
1807
1808 case '/':
1809 case '\\':
1810
1811 /* Separators match separators. */
1812
1813 if (IS_OS2_COMP_SEP(*name))
1814 return FNM_MATCH;
1815
1816 /* If _FNM_PATHPREFIX is set, a trailing separator in MASK
1817 * is ignored at the end of NAME. */
1818
1819 if ((flags & _FNM_PATHPREFIX) && mask[1] == 0 && *name == 0)
1820 return FNM_MATCH;
1821
1822 /* Stop comparing at the separator. */
1823
1824 return FNM_NOMATCH;
1825
1826 case '?':
1827
1828 /* A question mark matches one character. It does not match
1829 * a dot. At the end of the component (and before a dot),
1830 * it also matches zero characters. */
1831
1832 if (*name != '.' && !IS_OS2_COMP_END(*name))
1833 ++name;
1834 ++mask;
1835 break;
1836
1837 case '*':
1838
1839 /* An asterisk matches zero or more characters. In DOS
1840 * mode, dots are not matched. */
1841
1842 do
1843 {
1844 ++mask;
1845 }
1846 while (*mask == '*');
1847 for (;;)
1848 {
1849 rc = match_comp_os2(mask, name, flags, has_dot);
1850 if (rc != FNM_NOMATCH)
1851 return rc;
1852 if (IS_OS2_COMP_END(*name))
1853 return FNM_NOMATCH;
1854 if (*name == '.' && (flags & _FNM_STYLE_MASK) == _FNM_DOS)
1855 return FNM_NOMATCH;
1856 ++name;
1857 }
1858
1859 case '.':
1860
1861 /* A dot matches a dot. It also matches the implicit dot at
1862 * the end of a dot-less NAME. */
1863
1864 ++mask;
1865 if (*name == '.')
1866 ++name;
1867 else if (has_dot || !IS_OS2_COMP_END(*name))
1868 return FNM_NOMATCH;
1869 break;
1870
1871 default:
1872
1873 /* All other characters match themselves. */
1874
1875 if (flags & _FNM_IGNORECASE)
1876 {
1877 if (tolower(*mask) != tolower(*name))
1878 return FNM_NOMATCH;
1879 }
1880 else
1881 {
1882 if (*mask != *name)
1883 return FNM_NOMATCH;
1884 }
1885 ++mask;
1886 ++name;
1887 break;
1888 }
1889}
1890
1891/*
1892 * match_comp:
1893 * compare a single component (directory name or file name) of the
1894 * paths, for all styles which need component-by-component matching.
1895 * MASK and NAME point to the start of a component of the wildcard and
1896 * the name to be checked, respectively. Comparing stops at the next
1897 * separator. The FLAGS argument is the same as that of fnmatch().
1898 * Return FNM_MATCH iff MASK and NAME match.
1899 *
1900 * (c) 1994-1996 by Eberhard Mattes.
1901 */
1902
1903static int match_comp(const unsigned char *mask,
1904 const unsigned char *name,
1905 unsigned flags)
1906{
1907 const unsigned char *s;
1908
1909 switch (flags & _FNM_STYLE_MASK)
1910 {
1911 case _FNM_OS2:
1912 case _FNM_DOS:
1913
1914 /* For OS/2 and DOS styles, we add an implicit dot at the end of
1915 * the component if the component doesn't include a dot. */
1916
1917 s = name;
1918 while (!IS_OS2_COMP_END(*s) && *s != '.')
1919 ++s;
1920 return match_comp_os2(mask, name, flags, *s == '.');
1921
1922 default:
1923 return FNM_ERR;
1924 }
1925}
1926
1927/* In Unix styles, / separates components of a path. This macro
1928 * returns true iff C is a separator. */
1929
1930#define IS_UNIX_COMP_SEP(C) ((C) == '/')
1931
1932
1933/* This macro returns true if C is at the end of a component of a
1934 * path. */
1935
1936#define IS_UNIX_COMP_END(C) ((C) == 0 || IS_UNIX_COMP_SEP (C))
1937
1938/*
1939 * match_unix:
1940 * match complete paths for Unix styles. The FLAGS argument is the
1941 * same as that of fnmatch(). COMP points to the start of the current
1942 * component in NAME. Return FNM_MATCH iff MASK and NAME match. The
1943 * backslash character is used for escaping ? and * unless
1944 * FNM_NOESCAPE is set.
1945 *
1946 * (c) 1994-1996 by Eberhard Mattes.
1947 */
1948
1949static int match_unix(const unsigned char *mask,
1950 const unsigned char *name,
1951 unsigned flags,
1952 const unsigned char *comp)
1953{
1954 unsigned char c1, c2;
1955 char invert, matched;
1956 const unsigned char *start;
1957 int rc;
1958
1959 for (;;)
1960 switch (*mask)
1961 {
1962 case 0:
1963
1964 /* There must be no extra characters at the end of NAME when
1965 * reaching the end of MASK unless _FNM_PATHPREFIX is set:
1966 * in that case, NAME may point to a separator. */
1967
1968 if (*name == 0)
1969 return FNM_MATCH;
1970 if ((flags & _FNM_PATHPREFIX) && IS_UNIX_COMP_SEP(*name))
1971 return FNM_MATCH;
1972 return FNM_NOMATCH;
1973
1974 case '?':
1975
1976 /* A question mark matches one character. It does not match
1977 * the component separator if FNM_PATHNAME is set. It does
1978 * not match a dot at the start of a component if FNM_PERIOD
1979 * is set. */
1980
1981 if (*name == 0)
1982 return FNM_NOMATCH;
1983 if ((flags & FNM_PATHNAME) && IS_UNIX_COMP_SEP(*name))
1984 return FNM_NOMATCH;
1985 if (*name == '.' && (flags & FNM_PERIOD) && name == comp)
1986 return FNM_NOMATCH;
1987 ++mask;
1988 ++name;
1989 break;
1990
1991 case '*':
1992
1993 /* An asterisk matches zero or more characters. It does not
1994 * match the component separator if FNM_PATHNAME is set. It
1995 * does not match a dot at the start of a component if
1996 * FNM_PERIOD is set. */
1997
1998 if (*name == '.' && (flags & FNM_PERIOD) && name == comp)
1999 return FNM_NOMATCH;
2000 do
2001 {
2002 ++mask;
2003 }
2004 while (*mask == '*');
2005 for (;;)
2006 {
2007 rc = match_unix(mask, name, flags, comp);
2008 if (rc != FNM_NOMATCH)
2009 return rc;
2010 if (*name == 0)
2011 return FNM_NOMATCH;
2012 if ((flags & FNM_PATHNAME) && IS_UNIX_COMP_SEP(*name))
2013 return FNM_NOMATCH;
2014 ++name;
2015 }
2016
2017 case '/':
2018
2019 /* Separators match only separators. If _FNM_PATHPREFIX is
2020 * set, a trailing separator in MASK is ignored at the end
2021 * of NAME. */
2022
2023 if (!(IS_UNIX_COMP_SEP(*name)
2024 || ((flags & _FNM_PATHPREFIX) && *name == 0
2025 && (mask[1] == 0
2026 || (!(flags & FNM_NOESCAPE) && mask[1] == '\\'
2027 && mask[2] == 0)))))
2028 return FNM_NOMATCH;
2029
2030 ++mask;
2031 if (*name != 0)
2032 ++name;
2033
2034 /* This is the beginning of a new component if FNM_PATHNAME
2035 * is set. */
2036
2037 if (flags & FNM_PATHNAME)
2038 comp = name;
2039 break;
2040
2041 case '[':
2042
2043 /* A set of characters. Always case-sensitive. */
2044
2045 if (*name == 0)
2046 return FNM_NOMATCH;
2047 if ((flags & FNM_PATHNAME) && IS_UNIX_COMP_SEP(*name))
2048 return FNM_NOMATCH;
2049 if (*name == '.' && (flags & FNM_PERIOD) && name == comp)
2050 return FNM_NOMATCH;
2051
2052 invert = 0;
2053 matched = 0;
2054 ++mask;
2055
2056 /* If the first character is a ! or ^, the set matches all
2057 * characters not listed in the set. */
2058
2059 if (*mask == '!' || *mask == '^')
2060 {
2061 ++mask;
2062 invert = 1;
2063 }
2064
2065 /* Loop over all the characters of the set. The loop ends
2066 * if the end of the string is reached or if a ] is
2067 * encountered unless it directly follows the initial [ or
2068 * [-. */
2069
2070 start = mask;
2071 while (!(*mask == 0 || (*mask == ']' && mask != start)))
2072 {
2073 /* Get the next character which is optionally preceded
2074 * by a backslash. */
2075
2076 c1 = *mask++;
2077 if (!(flags & FNM_NOESCAPE) && c1 == '\\')
2078 {
2079 if (*mask == 0)
2080 break;
2081 c1 = *mask++;
2082 }
2083
2084 /* Ranges of characters are written as a-z. Don't
2085 * forget to check for the end of the string and to
2086 * handle the backslash. If the character after - is a
2087 * ], it isn't a range. */
2088
2089 if (*mask == '-' && mask[1] != ']')
2090 {
2091 ++mask; /* Skip the - character */
2092 if (!(flags & FNM_NOESCAPE) && *mask == '\\')
2093 ++mask;
2094 if (*mask == 0)
2095 break;
2096 c2 = *mask++;
2097 }
2098 else
2099 c2 = c1;
2100
2101 /* Now check whether this character or range matches NAME. */
2102
2103 if (c1 <= *name && *name <= c2)
2104 matched = 1;
2105 }
2106
2107 /* If the end of the string is reached before a ] is found,
2108 * back up to the [ and compare it to NAME. */
2109
2110 if (*mask == 0)
2111 {
2112 if (*name != '[')
2113 return FNM_NOMATCH;
2114 ++name;
2115 mask = start;
2116 if (invert)
2117 --mask;
2118 }
2119 else
2120 {
2121 if (invert)
2122 matched = !matched;
2123 if (!matched)
2124 return FNM_NOMATCH;
2125 ++mask; /* Skip the ] character */
2126 if (*name != 0)
2127 ++name;
2128 }
2129 break;
2130
2131 case '\\':
2132 ++mask;
2133 if (flags & FNM_NOESCAPE)
2134 {
2135 if (*name != '\\')
2136 return FNM_NOMATCH;
2137 ++name;
2138 }
2139 else if (*mask == '*' || *mask == '?')
2140 {
2141 if (*mask != *name)
2142 return FNM_NOMATCH;
2143 ++mask;
2144 ++name;
2145 }
2146 break;
2147
2148 default:
2149
2150 /* All other characters match themselves. */
2151
2152 if (flags & _FNM_IGNORECASE)
2153 {
2154 if (tolower(*mask) != tolower(*name))
2155 return FNM_NOMATCH;
2156 }
2157 else
2158 {
2159 if (*mask != *name)
2160 return FNM_NOMATCH;
2161 }
2162 ++mask;
2163 ++name;
2164 break;
2165 }
2166}
2167
2168/*
2169 * _fnmatch_unsigned:
2170 * Check whether the path name NAME matches the wildcard MASK.
2171 *
2172 * Return:
2173 * -- 0 (FNM_MATCH) if it matches,
2174 * -- _FNM_NOMATCH if it doesn't,
2175 * -- FNM_ERR on error.
2176 *
2177 * The operation of this function is controlled by FLAGS.
2178 * This is an internal function, with unsigned arguments.
2179 *
2180 * (c) 1994-1996 by Eberhard Mattes.
2181 */
2182
2183static int _fnmatch_unsigned(const unsigned char *mask,
2184 const unsigned char *name,
2185 unsigned flags)
2186{
2187 int m_drive, n_drive,
2188 rc;
2189
2190 /* Match and skip the drive name if present. */
2191
2192 m_drive = ((isalpha(mask[0]) && mask[1] == ':') ? mask[0] : -1);
2193 n_drive = ((isalpha(name[0]) && name[1] == ':') ? name[0] : -1);
2194
2195 if (m_drive != n_drive)
2196 {
2197 if (m_drive == -1 || n_drive == -1)
2198 return FNM_NOMATCH;
2199 if (!(flags & _FNM_IGNORECASE))
2200 return FNM_NOMATCH;
2201 if (tolower(m_drive) != tolower(n_drive))
2202 return FNM_NOMATCH;
2203 }
2204
2205 if (m_drive != -1)
2206 mask += 2;
2207 if (n_drive != -1)
2208 name += 2;
2209
2210 /* Colons are not allowed in path names, except for the drive name,
2211 * which was skipped above. */
2212
2213 if (has_colon(mask) || has_colon(name))
2214 return FNM_ERR;
2215
2216 /* The name "\\server\path" should not be matched by mask
2217 * "\*\server\path". Ditto for /. */
2218
2219 switch (flags & _FNM_STYLE_MASK)
2220 {
2221 case _FNM_OS2:
2222 case _FNM_DOS:
2223
2224 if (IS_OS2_COMP_SEP(name[0]) && IS_OS2_COMP_SEP(name[1]))
2225 {
2226 if (!(IS_OS2_COMP_SEP(mask[0]) && IS_OS2_COMP_SEP(mask[1])))
2227 return FNM_NOMATCH;
2228 name += 2;
2229 mask += 2;
2230 }
2231 break;
2232
2233 case _FNM_POSIX:
2234
2235 if (name[0] == '/' && name[1] == '/')
2236 {
2237 int i;
2238
2239 name += 2;
2240 for (i = 0; i < 2; ++i)
2241 if (mask[0] == '/')
2242 ++mask;
2243 else if (mask[0] == '\\' && mask[1] == '/')
2244 mask += 2;
2245 else
2246 return FNM_NOMATCH;
2247 }
2248
2249 /* In Unix styles, treating ? and * w.r.t. components is simple.
2250 * No need to do matching component by component. */
2251
2252 return match_unix(mask, name, flags, name);
2253 }
2254
2255 /* Now compare all the components of the path name, one by one.
2256 * Note that the path separator must not be enclosed in brackets. */
2257
2258 while (*mask != 0 || *name != 0)
2259 {
2260
2261 /* If _FNM_PATHPREFIX is set, the names match if the end of MASK
2262 * is reached even if there are components left in NAME. */
2263
2264 if (*mask == 0 && (flags & _FNM_PATHPREFIX))
2265 return FNM_MATCH;
2266
2267 /* Compare a single component of the path name. */
2268
2269 rc = match_comp(mask, name, flags);
2270 if (rc != FNM_MATCH)
2271 return rc;
2272
2273 /* Skip to the next component or to the end of the path name. */
2274
2275 mask = skip_comp_os2(mask);
2276 name = skip_comp_os2(name);
2277 }
2278
2279 /* If we reached the ends of both strings, the names match. */
2280
2281 if (*mask == 0 && *name == 0)
2282 return FNM_MATCH;
2283
2284 /* The names do not match. */
2285
2286 return FNM_NOMATCH;
2287}
2288
2289/*
2290 *@@ strhMatchOS2:
2291 * this matches wildcards, similar to what DosEditName does.
2292 * However, this does not require a file to be present, but
2293 * works on strings only.
2294 */
2295
2296BOOL strhMatchOS2(const unsigned char* pcszMask, // in: mask (e.g. "*.txt")
2297 const unsigned char* pcszName) // in: string to check (e.g. "test.txt")
2298{
2299 return ((BOOL)(_fnmatch_unsigned(pcszMask,
2300 pcszName,
2301 _FNM_OS2 | _FNM_IGNORECASE)
2302 == FNM_MATCH)
2303 );
2304}
2305
2306/* ******************************************************************
2307 *
2308 * Fast string searches
2309 *
2310 ********************************************************************/
2311
2312#define ASSERT(a)
2313
2314/*
2315 * The following code has been taken from the "Standard
2316 * Function Library", file sflfind.c, and only slightly
2317 * modified to conform to the rest of this file.
2318 *
2319 * Written: 96/04/24 iMatix SFL project team <sfl@imatix.com>
2320 * Revised: 98/05/04
2321 *
2322 * Copyright: Copyright (c) 1991-99 iMatix Corporation.
2323 *
2324 * The SFL Licence allows incorporating SFL code into other
2325 * programs, as long as the copyright is reprinted and the
2326 * code is marked as modified, so this is what we do.
2327 */
2328
2329/*
2330 *@@ strhmemfind:
2331 * searches for a pattern in a block of memory using the
2332 * Boyer-Moore-Horspool-Sunday algorithm.
2333 *
2334 * The block and pattern may contain any values; you must
2335 * explicitly provide their lengths. If you search for strings,
2336 * use strlen() on the buffers.
2337 *
2338 * Returns a pointer to the pattern if found within the block,
2339 * or NULL if the pattern was not found.
2340 *
2341 * This algorithm needs a "shift table" to cache data for the
2342 * search pattern. This table can be reused when performing
2343 * several searches with the same pattern.
2344 *
2345 * "shift" must point to an array big enough to hold 256 (8**2)
2346 * "size_t" values.
2347 *
2348 * If (*repeat_find == FALSE), the shift table is initialized.
2349 * So on the first search with a given pattern, *repeat_find
2350 * should be FALSE. This function sets it to TRUE after the
2351 * shift table is initialised, allowing the initialisation
2352 * phase to be skipped on subsequent searches.
2353 *
2354 * This function is most effective when repeated searches are
2355 * made for the same pattern in one or more large buffers.
2356 *
2357 * Example:
2358 *
2359 + PSZ pszHaystack = "This is a sample string.",
2360 + pszNeedle = "string";
2361 + size_t shift[256];
2362 + BOOL fRepeat = FALSE;
2363 +
2364 + PSZ pFound = strhmemfind(pszHaystack,
2365 + strlen(pszHaystack), // block size
2366 + pszNeedle,
2367 + strlen(pszNeedle), // pattern size
2368 + shift,
2369 + &fRepeat);
2370 *
2371 * Taken from the "Standard Function Library", file sflfind.c.
2372 * Copyright: Copyright (c) 1991-99 iMatix Corporation.
2373 * Slightly modified by umoeller.
2374 *
2375 *@@added V0.9.3 (2000-05-08) [umoeller]
2376 */
2377
2378void* strhmemfind(const void *in_block, // in: block containing data
2379 size_t block_size, // in: size of block in bytes
2380 const void *in_pattern, // in: pattern to search for
2381 size_t pattern_size, // in: size of pattern block
2382 size_t *shift, // in/out: shift table (search buffer)
2383 BOOL *repeat_find) // in/out: if TRUE, *shift is already initialized
2384{
2385 size_t byte_nbr, // Distance through block
2386 match_size; // Size of matched part
2387 const unsigned char
2388 *match_base = NULL, // Base of match of pattern
2389 *match_ptr = NULL, // Point within current match
2390 *limit = NULL; // Last potiental match point
2391 const unsigned char
2392 *block = (unsigned char *) in_block, // Concrete pointer to block data
2393 *pattern = (unsigned char *) in_pattern; // Concrete pointer to search value
2394
2395 if ( (block == NULL)
2396 || (pattern == NULL)
2397 || (shift == NULL)
2398 )
2399 return (NULL);
2400
2401 // Pattern must be smaller or equal in size to string
2402 if (block_size < pattern_size)
2403 return (NULL); // Otherwise it's not found
2404
2405 if (pattern_size == 0) // Empty patterns match at start
2406 return ((void *)block);
2407
2408 // Build the shift table unless we're continuing a previous search
2409
2410 // The shift table determines how far to shift before trying to match
2411 // again, if a match at this point fails. If the byte after where the
2412 // end of our pattern falls is not in our pattern, then we start to
2413 // match again after that byte; otherwise we line up the last occurence
2414 // of that byte in our pattern under that byte, and try match again.
2415
2416 if (!repeat_find || !*repeat_find)
2417 {
2418 for (byte_nbr = 0;
2419 byte_nbr < 256;
2420 byte_nbr++)
2421 shift[byte_nbr] = pattern_size + 1;
2422 for (byte_nbr = 0;
2423 byte_nbr < pattern_size;
2424 byte_nbr++)
2425 shift[(unsigned char)pattern[byte_nbr]] = pattern_size - byte_nbr;
2426
2427 if (repeat_find)
2428 *repeat_find = TRUE;
2429 }
2430
2431 // Search for the block, each time jumping up by the amount
2432 // computed in the shift table
2433
2434 limit = block + (block_size - pattern_size + 1);
2435 ASSERT (limit > block);
2436
2437 for (match_base = block;
2438 match_base < limit;
2439 match_base += shift[*(match_base + pattern_size)])
2440 {
2441 match_ptr = match_base;
2442 match_size = 0;
2443
2444 // Compare pattern until it all matches, or we find a difference
2445 while (*match_ptr++ == pattern[match_size++])
2446 {
2447 ASSERT (match_size <= pattern_size &&
2448 match_ptr == (match_base + match_size));
2449
2450 // If we found a match, return the start address
2451 if (match_size >= pattern_size)
2452 return ((void*)(match_base));
2453
2454 }
2455 }
2456 return (NULL); // Found nothing
2457}
2458
2459/*
2460 *@@ strhtxtfind:
2461 * searches for a case-insensitive text pattern in a string
2462 * using the Boyer-Moore-Horspool-Sunday algorithm. The string and
2463 * pattern are null-terminated strings. Returns a pointer to the pattern
2464 * if found within the string, or NULL if the pattern was not found.
2465 * Will match strings irrespective of case. To match exact strings, use
2466 * strhfind(). Will not work on multibyte characters.
2467 *
2468 * Examples:
2469 + char *result;
2470 +
2471 + result = strhtxtfind ("AbracaDabra", "cad");
2472 + if (result)
2473 + puts (result);
2474 +
2475 * Taken from the "Standard Function Library", file sflfind.c.
2476 * Copyright: Copyright (c) 1991-99 iMatix Corporation.
2477 * Slightly modified.
2478 *
2479 *@@added V0.9.3 (2000-05-08) [umoeller]
2480 */
2481
2482char* strhtxtfind (const char *string, // String containing data
2483 const char *pattern) // Pattern to search for
2484{
2485 size_t
2486 shift [256]; // Shift distance for each value
2487 size_t
2488 string_size,
2489 pattern_size,
2490 byte_nbr, // Index into byte array
2491 match_size; // Size of matched part
2492 const char
2493 *match_base = NULL, // Base of match of pattern
2494 *match_ptr = NULL, // Point within current match
2495 *limit = NULL; // Last potiental match point
2496
2497 ASSERT (string); // Expect non-NULL pointers, but
2498 ASSERT (pattern); // fail gracefully if not debugging
2499 if (string == NULL || pattern == NULL)
2500 return (NULL);
2501
2502 string_size = strlen (string);
2503 pattern_size = strlen (pattern);
2504
2505 // Pattern must be smaller or equal in size to string
2506 if (string_size < pattern_size)
2507 return (NULL); // Otherwise it cannot be found
2508
2509 if (pattern_size == 0) // Empty string matches at start
2510 return (char *) string;
2511
2512 // Build the shift table
2513
2514 // The shift table determines how far to shift before trying to match
2515 // again, if a match at this point fails. If the byte after where the
2516 // end of our pattern falls is not in our pattern, then we start to
2517 // match again after that byte; otherwise we line up the last occurence
2518 // of that byte in our pattern under that byte, and try match again.
2519
2520 for (byte_nbr = 0; byte_nbr < 256; byte_nbr++)
2521 shift [byte_nbr] = pattern_size + 1;
2522
2523 for (byte_nbr = 0; byte_nbr < pattern_size; byte_nbr++)
2524 shift [(unsigned char) tolower (pattern [byte_nbr])] = pattern_size - byte_nbr;
2525
2526 // Search for the string. If we don't find a match, move up by the
2527 // amount we computed in the shift table above, to find location of
2528 // the next potiental match.
2529
2530 limit = string + (string_size - pattern_size + 1);
2531 ASSERT (limit > string);
2532
2533 for (match_base = string;
2534 match_base < limit;
2535 match_base += shift [(unsigned char) tolower (*(match_base + pattern_size))])
2536 {
2537 match_ptr = match_base;
2538 match_size = 0;
2539
2540 // Compare pattern until it all matches, or we find a difference
2541 while (tolower (*match_ptr++) == tolower (pattern [match_size++]))
2542 {
2543 ASSERT (match_size <= pattern_size &&
2544 match_ptr == (match_base + match_size));
2545
2546 // If we found a match, return the start address
2547 if (match_size >= pattern_size)
2548 return ((char *)(match_base));
2549 }
2550 }
2551 return (NULL); // Found nothing
2552}
2553
Note: See TracBrowser for help on using the repository browser.