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

Last change on this file since 71 was 69, checked in by umoeller, 24 years ago

New folder sorting. Updated folder refresh. Misc other changes.

  • Property svn:eol-style set to CRLF
  • Property svn:keywords set to Author Date Id Revision
File size: 79.2 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 *@@changed V0.9.12 (2001-05-17) [pr]: multiple line break chars. end up as only 1 space
1119 */
1120
1121BOOL strhBeautifyTitle(PSZ psz)
1122{
1123 BOOL rc = FALSE;
1124 CHAR *p = psz;
1125
1126 while(*p)
1127 if ( (*p == '\r')
1128 || (*p == '\n')
1129 )
1130 {
1131 rc = TRUE;
1132 if ( (p != psz)
1133 && (p[-1] == ' ')
1134 )
1135 memmove(p, p + 1, strlen(p));
1136 else
1137 *p++ = ' ';
1138 }
1139 else
1140 p++;
1141
1142 return (rc);
1143}
1144
1145/*
1146 * strhFindAttribValue:
1147 * searches for pszAttrib in pszSearchIn; if found,
1148 * returns the first character after the "=" char.
1149 * If "=" is not found, a space, \r, and \n are
1150 * also accepted. This function searches without
1151 * respecting case.
1152 *
1153 * <B>Example:</B>
1154 + strhFindAttribValue("<PAGE BLAH="data">, "BLAH")
1155 +
1156 + returns ....................... ^ this address.
1157 *
1158 *@@added V0.9.0 [umoeller]
1159 *@@changed V0.9.3 (2000-05-19) [umoeller]: some speed optimizations
1160 */
1161
1162PSZ strhFindAttribValue(const char *pszSearchIn, const char *pszAttrib)
1163{
1164 PSZ prc = 0;
1165 PSZ pszSearchIn2 = (PSZ)pszSearchIn,
1166 p,
1167 p2;
1168 ULONG cbAttrib = strlen(pszAttrib);
1169
1170 // 1) find space char
1171 while ((p = strchr(pszSearchIn2, ' ')))
1172 {
1173 CHAR c;
1174 p++;
1175 if (strlen(p) >= cbAttrib) // V0.9.9 (2001-03-27) [umoeller]
1176 {
1177 c = *(p+cbAttrib); // V0.9.3 (2000-05-19) [umoeller]
1178 // now check whether the p+strlen(pszAttrib)
1179 // is a valid end-of-tag character
1180 if ( (memicmp(p, (PVOID)pszAttrib, cbAttrib) == 0)
1181 && ( (c == ' ')
1182 || (c == '>')
1183 || (c == '=')
1184 || (c == '\r')
1185 || (c == '\n')
1186 || (c == 0)
1187 )
1188 )
1189 {
1190 // yes:
1191 CHAR c2;
1192 p2 = p + cbAttrib;
1193 c2 = *p2;
1194 while ( ( (c2 == ' ')
1195 || (c2 == '=')
1196 || (c2 == '\n')
1197 || (c2 == '\r')
1198 )
1199 && (c2 != 0)
1200 )
1201 c2 = *++p2;
1202
1203 prc = p2;
1204 break; // first while
1205 }
1206 }
1207 else
1208 break;
1209
1210 pszSearchIn2++;
1211 }
1212 return (prc);
1213}
1214
1215/*
1216 * strhGetNumAttribValue:
1217 * stores the numerical parameter value of an HTML-style
1218 * tag in *pl.
1219 *
1220 * Returns the address of the tag parameter in the
1221 * search buffer, if found, or NULL.
1222 *
1223 * <B>Example:</B>
1224 + strhGetNumAttribValue("<PAGE BLAH=123>, "BLAH", &l);
1225 *
1226 * stores 123 in the "l" variable.
1227 *
1228 *@@added V0.9.0 [umoeller]
1229 *@@changed V0.9.9 (2001-04-04) [umoeller]: this failed on "123" strings in quotes, fixed
1230 */
1231
1232PSZ strhGetNumAttribValue(const char *pszSearchIn, // in: where to search
1233 const char *pszTag, // e.g. "INDEX"
1234 PLONG pl) // out: numerical value
1235{
1236 PSZ pParam;
1237 if ((pParam = strhFindAttribValue(pszSearchIn, pszTag)))
1238 {
1239 if ( (*pParam == '\"')
1240 || (*pParam == '\'')
1241 )
1242 pParam++; // V0.9.9 (2001-04-04) [umoeller]
1243
1244 sscanf(pParam, "%ld", pl);
1245 }
1246
1247 return (pParam);
1248}
1249
1250/*
1251 * strhGetTextAttr:
1252 * retrieves the attribute value of a textual HTML-style tag
1253 * in a newly allocated buffer, which is returned,
1254 * or NULL if attribute not found.
1255 * If an attribute value is to contain spaces, it
1256 * must be enclosed in quotes.
1257 *
1258 * The offset of the attribute data in pszSearchIn is
1259 * returned in *pulOffset so that you can do multiple
1260 * searches.
1261 *
1262 * This returns a new buffer, which should be free()'d after use.
1263 *
1264 * <B>Example:</B>
1265 + ULONG ulOfs = 0;
1266 + strhGetTextAttr("<PAGE BLAH="blublub">, "BLAH", &ulOfs)
1267 + ............^ ulOfs
1268 *
1269 * returns a new string with the value "blublub" (without
1270 * quotes) and sets ulOfs to 12.
1271 *
1272 *@@added V0.9.0 [umoeller]
1273 */
1274
1275PSZ strhGetTextAttr(const char *pszSearchIn,
1276 const char *pszTag,
1277 PULONG pulOffset) // out: offset where found
1278{
1279 PSZ pParam,
1280 pParam2,
1281 prc = NULL;
1282 ULONG ulCount = 0;
1283 LONG lNestingLevel = 0;
1284
1285 if ((pParam = strhFindAttribValue(pszSearchIn, pszTag)))
1286 {
1287 // determine end character to search for: a space
1288 CHAR cEnd = ' ';
1289 if (*pParam == '\"')
1290 {
1291 // or, if the data is enclosed in quotes, a quote
1292 cEnd = '\"';
1293 pParam++;
1294 }
1295
1296 if (pulOffset)
1297 // store the offset
1298 (*pulOffset) = pParam - (PSZ)pszSearchIn;
1299
1300 // now find end of attribute
1301 pParam2 = pParam;
1302 while (*pParam)
1303 {
1304 if (*pParam == cEnd)
1305 // end character found
1306 break;
1307 else if (*pParam == '<')
1308 // yet another opening tag found:
1309 // this is probably some "<" in the attributes
1310 lNestingLevel++;
1311 else if (*pParam == '>')
1312 {
1313 lNestingLevel--;
1314 if (lNestingLevel < 0)
1315 // end of tag found:
1316 break;
1317 }
1318 ulCount++;
1319 pParam++;
1320 }
1321
1322 // copy attribute to new buffer
1323 if (ulCount)
1324 {
1325 prc = (PSZ)malloc(ulCount+1);
1326 memcpy(prc, pParam2, ulCount);
1327 *(prc+ulCount) = 0;
1328 }
1329 }
1330 return (prc);
1331}
1332
1333/*
1334 * strhFindEndOfTag:
1335 * returns a pointer to the ">" char
1336 * which seems to terminate the tag beginning
1337 * after pszBeginOfTag.
1338 *
1339 * If additional "<" chars are found, we look
1340 * for additional ">" characters too.
1341 *
1342 * Note: You must pass the address of the opening
1343 * '<' character to this function.
1344 *
1345 * Example:
1346 + PSZ pszTest = "<BODY ATTR=\"<BODY>\">";
1347 + strhFindEndOfTag(pszTest)
1348 + returns.................................^ this.
1349 *
1350 *@@added V0.9.0 [umoeller]
1351 */
1352
1353PSZ strhFindEndOfTag(const char *pszBeginOfTag)
1354{
1355 PSZ p = (PSZ)pszBeginOfTag,
1356 prc = NULL;
1357 LONG lNestingLevel = 0;
1358
1359 while (*p)
1360 {
1361 if (*p == '<')
1362 // another opening tag found:
1363 lNestingLevel++;
1364 else if (*p == '>')
1365 {
1366 // closing tag found:
1367 lNestingLevel--;
1368 if (lNestingLevel < 1)
1369 {
1370 // corresponding: return this
1371 prc = p;
1372 break;
1373 }
1374 }
1375 p++;
1376 }
1377
1378 return (prc);
1379}
1380
1381/*
1382 * strhGetBlock:
1383 * this complex function searches the given string
1384 * for a pair of opening/closing HTML-style tags.
1385 *
1386 * If found, this routine returns TRUE and does
1387 * the following:
1388 *
1389 * 1) allocate a new buffer, copy the text
1390 * enclosed by the opening/closing tags
1391 * into it and set *ppszBlock to that
1392 * buffer;
1393 *
1394 * 2) if the opening tag has any attributes,
1395 * allocate another buffer, copy the
1396 * attributes into it and set *ppszAttrs
1397 * to that buffer; if no attributes are
1398 * found, *ppszAttrs will be NULL;
1399 *
1400 * 3) set *pulOffset to the offset from the
1401 * beginning of *ppszSearchIn where the
1402 * opening tag was found;
1403 *
1404 * 4) advance *ppszSearchIn to after the
1405 * closing tag, so that you can do
1406 * multiple searches without finding the
1407 * same tags twice.
1408 *
1409 * All buffers should be freed using free().
1410 *
1411 * This returns the following:
1412 * -- 0: no error
1413 * -- 1: tag not found at all (doesn't have to be an error)
1414 * -- 2: begin tag found, but no corresponding end tag found. This
1415 * is a real error.
1416 * -- 3: begin tag is not terminated by "&gt;" (e.g. "&lt;BEGINTAG whatever")
1417 *
1418 * <B>Example:</B>
1419 + PSZ pSearch = "&lt;PAGE INDEX=1&gt;This is page 1.&lt;/PAGE&gt;More text."
1420 + PSZ pszBlock, pszAttrs;
1421 + ULONG ulOfs;
1422 + strhGetBlock(&pSearch, "PAGE", &pszBlock, &pszAttrs, &ulOfs)
1423 *
1424 * would do the following:
1425 *
1426 * 1) set pszBlock to a new string containing "This is page 1."
1427 * without quotes;
1428 *
1429 * 2) set pszAttrs to a new string containing "&lt;PAGE INDEX=1&gt;";
1430 *
1431 * 3) set ulOfs to 0, because "&lt;PAGE" was found at the beginning;
1432 *
1433 * 4) pSearch would be advanced to point to the "More text"
1434 * string in the original buffer.
1435 *
1436 * Hey-hey. A one-shot function, fairly complicated, but indispensable
1437 * for HTML parsing.
1438 *
1439 *@@added V0.9.0 [umoeller]
1440 *@@changed V0.9.1 (2000-01-03) [umoeller]: fixed heap overwrites (thanks to string debugging)
1441 *@@changed V0.9.1 (2000-01-06) [umoeller]: changed prototype
1442 *@@changed V0.9.3 (2000-05-06) [umoeller]: NULL string check was missing
1443 */
1444
1445ULONG strhGetBlock(const char *pszSearchIn, // in: buffer to search
1446 PULONG pulSearchOffset, // in/out: offset where to start search (0 for beginning)
1447 PSZ pszTag,
1448 PSZ *ppszBlock, // out: block enclosed by the tags
1449 PSZ *ppszAttribs, // out: attributes of the opening tag
1450 PULONG pulOfsBeginTag, // out: offset from pszSearchIn where opening tag was found
1451 PULONG pulOfsBeginBlock) // out: offset from pszSearchIn where beginning of block was found
1452{
1453 ULONG ulrc = 1;
1454 PSZ pszBeginTag = (PSZ)pszSearchIn + *pulSearchOffset,
1455 pszSearch2 = pszBeginTag,
1456 pszClosingTag;
1457 ULONG cbTag = strlen(pszTag);
1458
1459 // go thru the block and check all tags if it's the
1460 // begin tag we're looking for
1461 while ((pszBeginTag = strchr(pszBeginTag, '<')))
1462 {
1463 if (memicmp(pszBeginTag+1, pszTag, strlen(pszTag)) == 0)
1464 // yes: stop
1465 break;
1466 else
1467 pszBeginTag++;
1468 }
1469
1470 if (pszBeginTag)
1471 {
1472 // we found <TAG>:
1473 ULONG ulNestingLevel = 0;
1474
1475 PSZ pszEndOfBeginTag = strhFindEndOfTag(pszBeginTag);
1476 // strchr(pszBeginTag, '>');
1477 if (pszEndOfBeginTag)
1478 {
1479 // does the caller want the attributes?
1480 if (ppszAttribs)
1481 {
1482 // yes: then copy them
1483 ULONG ulAttrLen = pszEndOfBeginTag - pszBeginTag;
1484 PSZ pszAttrs = (PSZ)malloc(ulAttrLen + 1);
1485 strncpy(pszAttrs, pszBeginTag, ulAttrLen);
1486 // add terminating 0
1487 *(pszAttrs + ulAttrLen) = 0;
1488
1489 *ppszAttribs = pszAttrs;
1490 }
1491
1492 // output offset of where we found the begin tag
1493 if (pulOfsBeginTag)
1494 *pulOfsBeginTag = pszBeginTag - (PSZ)pszSearchIn;
1495
1496 // now find corresponding closing tag (e.g. "</BODY>"
1497 pszBeginTag = pszEndOfBeginTag+1;
1498 // now we're behind the '>' char of the opening tag
1499 // increase offset of that too
1500 if (pulOfsBeginBlock)
1501 *pulOfsBeginBlock = pszBeginTag - (PSZ)pszSearchIn;
1502
1503 // find next closing tag;
1504 // for the first run, pszSearch2 points to right
1505 // after the '>' char of the opening tag
1506 pszSearch2 = pszBeginTag;
1507 while ( (pszSearch2) // fixed V0.9.3 (2000-05-06) [umoeller]
1508 && (pszClosingTag = strstr(pszSearch2, "<"))
1509 )
1510 {
1511 // if we have another opening tag before our closing
1512 // tag, we need to have several closing tags before
1513 // we're done
1514 if (memicmp(pszClosingTag+1, pszTag, cbTag) == 0)
1515 ulNestingLevel++;
1516 else
1517 {
1518 // is this ours?
1519 if ( (*(pszClosingTag+1) == '/')
1520 && (memicmp(pszClosingTag+2, pszTag, cbTag) == 0)
1521 )
1522 {
1523 // we've found a matching closing tag; is
1524 // it ours?
1525 if (ulNestingLevel == 0)
1526 {
1527 // our closing tag found:
1528 // allocate mem for a new buffer
1529 // and extract all the text between
1530 // open and closing tags to it
1531 ULONG ulLen = pszClosingTag - pszBeginTag;
1532 if (ppszBlock)
1533 {
1534 PSZ pNew = (PSZ)malloc(ulLen + 1);
1535 strhncpy0(pNew, pszBeginTag, ulLen);
1536 *ppszBlock = pNew;
1537 }
1538
1539 // raise search offset to after the closing tag
1540 *pulSearchOffset = (pszClosingTag + cbTag + 1) - (PSZ)pszSearchIn;
1541
1542 ulrc = 0;
1543
1544 break;
1545 } else
1546 // not our closing tag:
1547 ulNestingLevel--;
1548 }
1549 }
1550 // no matching closing tag: search on after that
1551 pszSearch2 = strhFindEndOfTag(pszClosingTag);
1552 } // end while (pszClosingTag = strstr(pszSearch2, "<"))
1553
1554 if (!pszClosingTag)
1555 // no matching closing tag found:
1556 // return 2 (closing tag not found)
1557 ulrc = 2;
1558 } // end if (pszBeginTag)
1559 else
1560 // no matching ">" for opening tag found:
1561 ulrc = 3;
1562 }
1563
1564 return (ulrc);
1565}
1566
1567/* ******************************************************************
1568 *
1569 * Miscellaneous
1570 *
1571 ********************************************************************/
1572
1573/*
1574 *@@ strhArrayAppend:
1575 * this appends a string to a "string array".
1576 *
1577 * A string array is considered a sequence of
1578 * zero-terminated strings in memory. That is,
1579 * after each string's null-byte, the next
1580 * string comes up.
1581 *
1582 * This is useful for composing a single block
1583 * of memory from, say, list box entries, which
1584 * can then be written to OS2.INI in one flush.
1585 *
1586 * To append strings to such an array, call this
1587 * function for each string you wish to append.
1588 * This will re-allocate *ppszRoot with each call,
1589 * and update *pcbRoot, which then contains the
1590 * total size of all strings (including all null
1591 * terminators).
1592 *
1593 * Pass *pcbRoot to PrfSaveProfileData to have the
1594 * block saved.
1595 *
1596 * Note: On the first call, *ppszRoot and *pcbRoot
1597 * _must_ be both NULL, or this crashes.
1598 */
1599
1600VOID strhArrayAppend(PSZ *ppszRoot, // in: root of array
1601 const char *pcszNew, // in: string to append
1602 PULONG pcbRoot) // in/out: size of array
1603{
1604 ULONG cbNew = strlen(pcszNew);
1605 PSZ pszTemp = (PSZ)malloc(*pcbRoot
1606 + cbNew
1607 + 1); // two null bytes
1608 if (*ppszRoot)
1609 {
1610 // not first loop: copy old stuff
1611 memcpy(pszTemp,
1612 *ppszRoot,
1613 *pcbRoot);
1614 free(*ppszRoot);
1615 }
1616 // append new string
1617 strcpy(pszTemp + *pcbRoot,
1618 pcszNew);
1619 // update root
1620 *ppszRoot = pszTemp;
1621 // update length
1622 *pcbRoot += cbNew + 1;
1623}
1624
1625/*
1626 *@@ strhCreateDump:
1627 * this dumps a memory block into a string
1628 * and returns that string in a new buffer.
1629 *
1630 * You must free() the returned PSZ after use.
1631 *
1632 * The output looks like the following:
1633 *
1634 + 0000: FE FF 0E 02 90 00 00 00 ........
1635 + 0008: FD 01 00 00 57 50 46 6F ....WPFo
1636 + 0010: 6C 64 65 72 00 78 01 34 lder.x.4
1637 *
1638 * Each line is terminated with a newline (\n)
1639 * character only.
1640 *
1641 *@@added V0.9.1 (2000-01-22) [umoeller]
1642 */
1643
1644PSZ strhCreateDump(PBYTE pb, // in: start address of buffer
1645 ULONG ulSize, // in: size of buffer
1646 ULONG ulIndent) // in: indentation of every line
1647{
1648 PSZ pszReturn = 0;
1649 XSTRING strReturn;
1650 CHAR szTemp[1000];
1651
1652 PBYTE pbCurrent = pb; // current byte
1653 ULONG ulCount = 0,
1654 ulCharsInLine = 0; // if this grows > 7, a new line is started
1655 CHAR szLine[400] = "",
1656 szAscii[30] = " "; // ASCII representation; filled for every line
1657 PSZ pszLine = szLine,
1658 pszAscii = szAscii;
1659
1660 xstrInit(&strReturn, (ulSize * 30) + ulIndent);
1661
1662 for (pbCurrent = pb;
1663 ulCount < ulSize;
1664 pbCurrent++, ulCount++)
1665 {
1666 if (ulCharsInLine == 0)
1667 {
1668 memset(szLine, ' ', ulIndent);
1669 pszLine += ulIndent;
1670 }
1671 pszLine += sprintf(pszLine, "%02lX ", (ULONG)*pbCurrent);
1672
1673 if ( (*pbCurrent > 31) && (*pbCurrent < 127) )
1674 // printable character:
1675 *pszAscii = *pbCurrent;
1676 else
1677 *pszAscii = '.';
1678 pszAscii++;
1679
1680 ulCharsInLine++;
1681 if ( (ulCharsInLine > 7) // 8 bytes added?
1682 || (ulCount == ulSize-1) // end of buffer reached?
1683 )
1684 {
1685 // if we haven't had eight bytes yet,
1686 // fill buffer up to eight bytes with spaces
1687 ULONG ul2;
1688 for (ul2 = ulCharsInLine;
1689 ul2 < 8;
1690 ul2++)
1691 pszLine += sprintf(pszLine, " ");
1692
1693 sprintf(szTemp, "%04lX: %s %s\n",
1694 (ulCount & 0xFFFFFFF8), // offset in hex
1695 szLine, // bytes string
1696 szAscii); // ASCII string
1697 xstrcat(&strReturn, szTemp, 0);
1698
1699 // restart line buffer
1700 pszLine = szLine;
1701
1702 // clear ASCII buffer
1703 strcpy(szAscii, " ");
1704 pszAscii = szAscii;
1705
1706 // reset line counter
1707 ulCharsInLine = 0;
1708 }
1709 }
1710
1711 if (strReturn.cbAllocated)
1712 pszReturn = strReturn.psz;
1713
1714 return (pszReturn);
1715}
1716
1717/* ******************************************************************
1718 *
1719 * Wildcard matching
1720 *
1721 ********************************************************************/
1722
1723/*
1724 * The following code has been taken from "fnmatch.zip".
1725 *
1726 * (c) 1994-1996 by Eberhard Mattes.
1727 */
1728
1729/* In OS/2 and DOS styles, both / and \ separate components of a path.
1730 * This macro returns true iff C is a separator. */
1731
1732#define IS_OS2_COMP_SEP(C) ((C) == '/' || (C) == '\\')
1733
1734
1735/* This macro returns true if C is at the end of a component of a
1736 * path. */
1737
1738#define IS_OS2_COMP_END(C) ((C) == 0 || IS_OS2_COMP_SEP (C))
1739
1740/*
1741 * skip_comp_os2:
1742 * Return a pointer to the next component of the path SRC, for OS/2
1743 * and DOS styles. When the end of the string is reached, a pointer
1744 * to the terminating null character is returned.
1745 *
1746 * (c) 1994-1996 by Eberhard Mattes.
1747 */
1748
1749static const unsigned char* skip_comp_os2(const unsigned char *src)
1750{
1751 /* Skip characters until hitting a separator or the end of the
1752 * string. */
1753
1754 while (!IS_OS2_COMP_END(*src))
1755 ++src;
1756
1757 /* Skip the separator if we hit a separator. */
1758
1759 if (*src != 0)
1760 ++src;
1761 return src;
1762}
1763
1764/*
1765 * has_colon:
1766 * returns true iff the path P contains a colon.
1767 *
1768 * (c) 1994-1996 by Eberhard Mattes.
1769 */
1770
1771static int has_colon(const unsigned char *p)
1772{
1773 while (*p != 0)
1774 if (*p == ':')
1775 return 1;
1776 else
1777 ++p;
1778 return 0;
1779}
1780
1781/*
1782 * match_comp_os2:
1783 * Compare a single component (directory name or file name) of the
1784 * paths, for OS/2 and DOS styles. MASK and NAME point into a
1785 * component of the wildcard and the name to be checked, respectively.
1786 * Comparing stops at the next separator. The FLAGS argument is the
1787 * same as that of fnmatch(). HAS_DOT is true if a dot is in the
1788 * current component of NAME. The number of dots is not restricted,
1789 * even in DOS style. Return FNM_MATCH iff MASK and NAME match.
1790 * Note that this function is recursive.
1791 *
1792 * (c) 1994-1996 by Eberhard Mattes.
1793 */
1794
1795static int match_comp_os2(const unsigned char *mask,
1796 const unsigned char *name,
1797 unsigned flags,
1798 int has_dot)
1799{
1800 int rc;
1801
1802 for (;;)
1803 switch (*mask)
1804 {
1805 case 0:
1806
1807 /* There must be no extra characters at the end of NAME when
1808 * reaching the end of MASK unless _FNM_PATHPREFIX is set:
1809 * in that case, NAME may point to a separator. */
1810
1811 if (*name == 0)
1812 return FNM_MATCH;
1813 if ((flags & _FNM_PATHPREFIX) && IS_OS2_COMP_SEP(*name))
1814 return FNM_MATCH;
1815 return FNM_NOMATCH;
1816
1817 case '/':
1818 case '\\':
1819
1820 /* Separators match separators. */
1821
1822 if (IS_OS2_COMP_SEP(*name))
1823 return FNM_MATCH;
1824
1825 /* If _FNM_PATHPREFIX is set, a trailing separator in MASK
1826 * is ignored at the end of NAME. */
1827
1828 if ((flags & _FNM_PATHPREFIX) && mask[1] == 0 && *name == 0)
1829 return FNM_MATCH;
1830
1831 /* Stop comparing at the separator. */
1832
1833 return FNM_NOMATCH;
1834
1835 case '?':
1836
1837 /* A question mark matches one character. It does not match
1838 * a dot. At the end of the component (and before a dot),
1839 * it also matches zero characters. */
1840
1841 if (*name != '.' && !IS_OS2_COMP_END(*name))
1842 ++name;
1843 ++mask;
1844 break;
1845
1846 case '*':
1847
1848 /* An asterisk matches zero or more characters. In DOS
1849 * mode, dots are not matched. */
1850
1851 do
1852 {
1853 ++mask;
1854 }
1855 while (*mask == '*');
1856 for (;;)
1857 {
1858 rc = match_comp_os2(mask, name, flags, has_dot);
1859 if (rc != FNM_NOMATCH)
1860 return rc;
1861 if (IS_OS2_COMP_END(*name))
1862 return FNM_NOMATCH;
1863 if (*name == '.' && (flags & _FNM_STYLE_MASK) == _FNM_DOS)
1864 return FNM_NOMATCH;
1865 ++name;
1866 }
1867
1868 case '.':
1869
1870 /* A dot matches a dot. It also matches the implicit dot at
1871 * the end of a dot-less NAME. */
1872
1873 ++mask;
1874 if (*name == '.')
1875 ++name;
1876 else if (has_dot || !IS_OS2_COMP_END(*name))
1877 return FNM_NOMATCH;
1878 break;
1879
1880 default:
1881
1882 /* All other characters match themselves. */
1883
1884 if (flags & _FNM_IGNORECASE)
1885 {
1886 if (tolower(*mask) != tolower(*name))
1887 return FNM_NOMATCH;
1888 }
1889 else
1890 {
1891 if (*mask != *name)
1892 return FNM_NOMATCH;
1893 }
1894 ++mask;
1895 ++name;
1896 break;
1897 }
1898}
1899
1900/*
1901 * match_comp:
1902 * compare a single component (directory name or file name) of the
1903 * paths, for all styles which need component-by-component matching.
1904 * MASK and NAME point to the start of a component of the wildcard and
1905 * the name to be checked, respectively. Comparing stops at the next
1906 * separator. The FLAGS argument is the same as that of fnmatch().
1907 * Return FNM_MATCH iff MASK and NAME match.
1908 *
1909 * (c) 1994-1996 by Eberhard Mattes.
1910 */
1911
1912static int match_comp(const unsigned char *mask,
1913 const unsigned char *name,
1914 unsigned flags)
1915{
1916 const unsigned char *s;
1917
1918 switch (flags & _FNM_STYLE_MASK)
1919 {
1920 case _FNM_OS2:
1921 case _FNM_DOS:
1922
1923 /* For OS/2 and DOS styles, we add an implicit dot at the end of
1924 * the component if the component doesn't include a dot. */
1925
1926 s = name;
1927 while (!IS_OS2_COMP_END(*s) && *s != '.')
1928 ++s;
1929 return match_comp_os2(mask, name, flags, *s == '.');
1930
1931 default:
1932 return FNM_ERR;
1933 }
1934}
1935
1936/* In Unix styles, / separates components of a path. This macro
1937 * returns true iff C is a separator. */
1938
1939#define IS_UNIX_COMP_SEP(C) ((C) == '/')
1940
1941
1942/* This macro returns true if C is at the end of a component of a
1943 * path. */
1944
1945#define IS_UNIX_COMP_END(C) ((C) == 0 || IS_UNIX_COMP_SEP (C))
1946
1947/*
1948 * match_unix:
1949 * match complete paths for Unix styles. The FLAGS argument is the
1950 * same as that of fnmatch(). COMP points to the start of the current
1951 * component in NAME. Return FNM_MATCH iff MASK and NAME match. The
1952 * backslash character is used for escaping ? and * unless
1953 * FNM_NOESCAPE is set.
1954 *
1955 * (c) 1994-1996 by Eberhard Mattes.
1956 */
1957
1958static int match_unix(const unsigned char *mask,
1959 const unsigned char *name,
1960 unsigned flags,
1961 const unsigned char *comp)
1962{
1963 unsigned char c1, c2;
1964 char invert, matched;
1965 const unsigned char *start;
1966 int rc;
1967
1968 for (;;)
1969 switch (*mask)
1970 {
1971 case 0:
1972
1973 /* There must be no extra characters at the end of NAME when
1974 * reaching the end of MASK unless _FNM_PATHPREFIX is set:
1975 * in that case, NAME may point to a separator. */
1976
1977 if (*name == 0)
1978 return FNM_MATCH;
1979 if ((flags & _FNM_PATHPREFIX) && IS_UNIX_COMP_SEP(*name))
1980 return FNM_MATCH;
1981 return FNM_NOMATCH;
1982
1983 case '?':
1984
1985 /* A question mark matches one character. It does not match
1986 * the component separator if FNM_PATHNAME is set. It does
1987 * not match a dot at the start of a component if FNM_PERIOD
1988 * is set. */
1989
1990 if (*name == 0)
1991 return FNM_NOMATCH;
1992 if ((flags & FNM_PATHNAME) && IS_UNIX_COMP_SEP(*name))
1993 return FNM_NOMATCH;
1994 if (*name == '.' && (flags & FNM_PERIOD) && name == comp)
1995 return FNM_NOMATCH;
1996 ++mask;
1997 ++name;
1998 break;
1999
2000 case '*':
2001
2002 /* An asterisk matches zero or more characters. It does not
2003 * match the component separator if FNM_PATHNAME is set. It
2004 * does not match a dot at the start of a component if
2005 * FNM_PERIOD is set. */
2006
2007 if (*name == '.' && (flags & FNM_PERIOD) && name == comp)
2008 return FNM_NOMATCH;
2009 do
2010 {
2011 ++mask;
2012 }
2013 while (*mask == '*');
2014 for (;;)
2015 {
2016 rc = match_unix(mask, name, flags, comp);
2017 if (rc != FNM_NOMATCH)
2018 return rc;
2019 if (*name == 0)
2020 return FNM_NOMATCH;
2021 if ((flags & FNM_PATHNAME) && IS_UNIX_COMP_SEP(*name))
2022 return FNM_NOMATCH;
2023 ++name;
2024 }
2025
2026 case '/':
2027
2028 /* Separators match only separators. If _FNM_PATHPREFIX is
2029 * set, a trailing separator in MASK is ignored at the end
2030 * of NAME. */
2031
2032 if (!(IS_UNIX_COMP_SEP(*name)
2033 || ((flags & _FNM_PATHPREFIX) && *name == 0
2034 && (mask[1] == 0
2035 || (!(flags & FNM_NOESCAPE) && mask[1] == '\\'
2036 && mask[2] == 0)))))
2037 return FNM_NOMATCH;
2038
2039 ++mask;
2040 if (*name != 0)
2041 ++name;
2042
2043 /* This is the beginning of a new component if FNM_PATHNAME
2044 * is set. */
2045
2046 if (flags & FNM_PATHNAME)
2047 comp = name;
2048 break;
2049
2050 case '[':
2051
2052 /* A set of characters. Always case-sensitive. */
2053
2054 if (*name == 0)
2055 return FNM_NOMATCH;
2056 if ((flags & FNM_PATHNAME) && IS_UNIX_COMP_SEP(*name))
2057 return FNM_NOMATCH;
2058 if (*name == '.' && (flags & FNM_PERIOD) && name == comp)
2059 return FNM_NOMATCH;
2060
2061 invert = 0;
2062 matched = 0;
2063 ++mask;
2064
2065 /* If the first character is a ! or ^, the set matches all
2066 * characters not listed in the set. */
2067
2068 if (*mask == '!' || *mask == '^')
2069 {
2070 ++mask;
2071 invert = 1;
2072 }
2073
2074 /* Loop over all the characters of the set. The loop ends
2075 * if the end of the string is reached or if a ] is
2076 * encountered unless it directly follows the initial [ or
2077 * [-. */
2078
2079 start = mask;
2080 while (!(*mask == 0 || (*mask == ']' && mask != start)))
2081 {
2082 /* Get the next character which is optionally preceded
2083 * by a backslash. */
2084
2085 c1 = *mask++;
2086 if (!(flags & FNM_NOESCAPE) && c1 == '\\')
2087 {
2088 if (*mask == 0)
2089 break;
2090 c1 = *mask++;
2091 }
2092
2093 /* Ranges of characters are written as a-z. Don't
2094 * forget to check for the end of the string and to
2095 * handle the backslash. If the character after - is a
2096 * ], it isn't a range. */
2097
2098 if (*mask == '-' && mask[1] != ']')
2099 {
2100 ++mask; /* Skip the - character */
2101 if (!(flags & FNM_NOESCAPE) && *mask == '\\')
2102 ++mask;
2103 if (*mask == 0)
2104 break;
2105 c2 = *mask++;
2106 }
2107 else
2108 c2 = c1;
2109
2110 /* Now check whether this character or range matches NAME. */
2111
2112 if (c1 <= *name && *name <= c2)
2113 matched = 1;
2114 }
2115
2116 /* If the end of the string is reached before a ] is found,
2117 * back up to the [ and compare it to NAME. */
2118
2119 if (*mask == 0)
2120 {
2121 if (*name != '[')
2122 return FNM_NOMATCH;
2123 ++name;
2124 mask = start;
2125 if (invert)
2126 --mask;
2127 }
2128 else
2129 {
2130 if (invert)
2131 matched = !matched;
2132 if (!matched)
2133 return FNM_NOMATCH;
2134 ++mask; /* Skip the ] character */
2135 if (*name != 0)
2136 ++name;
2137 }
2138 break;
2139
2140 case '\\':
2141 ++mask;
2142 if (flags & FNM_NOESCAPE)
2143 {
2144 if (*name != '\\')
2145 return FNM_NOMATCH;
2146 ++name;
2147 }
2148 else if (*mask == '*' || *mask == '?')
2149 {
2150 if (*mask != *name)
2151 return FNM_NOMATCH;
2152 ++mask;
2153 ++name;
2154 }
2155 break;
2156
2157 default:
2158
2159 /* All other characters match themselves. */
2160
2161 if (flags & _FNM_IGNORECASE)
2162 {
2163 if (tolower(*mask) != tolower(*name))
2164 return FNM_NOMATCH;
2165 }
2166 else
2167 {
2168 if (*mask != *name)
2169 return FNM_NOMATCH;
2170 }
2171 ++mask;
2172 ++name;
2173 break;
2174 }
2175}
2176
2177/*
2178 * _fnmatch_unsigned:
2179 * Check whether the path name NAME matches the wildcard MASK.
2180 *
2181 * Return:
2182 * -- 0 (FNM_MATCH) if it matches,
2183 * -- _FNM_NOMATCH if it doesn't,
2184 * -- FNM_ERR on error.
2185 *
2186 * The operation of this function is controlled by FLAGS.
2187 * This is an internal function, with unsigned arguments.
2188 *
2189 * (c) 1994-1996 by Eberhard Mattes.
2190 */
2191
2192static int _fnmatch_unsigned(const unsigned char *mask,
2193 const unsigned char *name,
2194 unsigned flags)
2195{
2196 int m_drive, n_drive,
2197 rc;
2198
2199 /* Match and skip the drive name if present. */
2200
2201 m_drive = ((isalpha(mask[0]) && mask[1] == ':') ? mask[0] : -1);
2202 n_drive = ((isalpha(name[0]) && name[1] == ':') ? name[0] : -1);
2203
2204 if (m_drive != n_drive)
2205 {
2206 if (m_drive == -1 || n_drive == -1)
2207 return FNM_NOMATCH;
2208 if (!(flags & _FNM_IGNORECASE))
2209 return FNM_NOMATCH;
2210 if (tolower(m_drive) != tolower(n_drive))
2211 return FNM_NOMATCH;
2212 }
2213
2214 if (m_drive != -1)
2215 mask += 2;
2216 if (n_drive != -1)
2217 name += 2;
2218
2219 /* Colons are not allowed in path names, except for the drive name,
2220 * which was skipped above. */
2221
2222 if (has_colon(mask) || has_colon(name))
2223 return FNM_ERR;
2224
2225 /* The name "\\server\path" should not be matched by mask
2226 * "\*\server\path". Ditto for /. */
2227
2228 switch (flags & _FNM_STYLE_MASK)
2229 {
2230 case _FNM_OS2:
2231 case _FNM_DOS:
2232
2233 if (IS_OS2_COMP_SEP(name[0]) && IS_OS2_COMP_SEP(name[1]))
2234 {
2235 if (!(IS_OS2_COMP_SEP(mask[0]) && IS_OS2_COMP_SEP(mask[1])))
2236 return FNM_NOMATCH;
2237 name += 2;
2238 mask += 2;
2239 }
2240 break;
2241
2242 case _FNM_POSIX:
2243
2244 if (name[0] == '/' && name[1] == '/')
2245 {
2246 int i;
2247
2248 name += 2;
2249 for (i = 0; i < 2; ++i)
2250 if (mask[0] == '/')
2251 ++mask;
2252 else if (mask[0] == '\\' && mask[1] == '/')
2253 mask += 2;
2254 else
2255 return FNM_NOMATCH;
2256 }
2257
2258 /* In Unix styles, treating ? and * w.r.t. components is simple.
2259 * No need to do matching component by component. */
2260
2261 return match_unix(mask, name, flags, name);
2262 }
2263
2264 /* Now compare all the components of the path name, one by one.
2265 * Note that the path separator must not be enclosed in brackets. */
2266
2267 while (*mask != 0 || *name != 0)
2268 {
2269
2270 /* If _FNM_PATHPREFIX is set, the names match if the end of MASK
2271 * is reached even if there are components left in NAME. */
2272
2273 if (*mask == 0 && (flags & _FNM_PATHPREFIX))
2274 return FNM_MATCH;
2275
2276 /* Compare a single component of the path name. */
2277
2278 rc = match_comp(mask, name, flags);
2279 if (rc != FNM_MATCH)
2280 return rc;
2281
2282 /* Skip to the next component or to the end of the path name. */
2283
2284 mask = skip_comp_os2(mask);
2285 name = skip_comp_os2(name);
2286 }
2287
2288 /* If we reached the ends of both strings, the names match. */
2289
2290 if (*mask == 0 && *name == 0)
2291 return FNM_MATCH;
2292
2293 /* The names do not match. */
2294
2295 return FNM_NOMATCH;
2296}
2297
2298/*
2299 *@@ strhMatchOS2:
2300 * this matches wildcards, similar to what DosEditName does.
2301 * However, this does not require a file to be present, but
2302 * works on strings only.
2303 */
2304
2305BOOL strhMatchOS2(const unsigned char* pcszMask, // in: mask (e.g. "*.txt")
2306 const unsigned char* pcszName) // in: string to check (e.g. "test.txt")
2307{
2308 return ((BOOL)(_fnmatch_unsigned(pcszMask,
2309 pcszName,
2310 _FNM_OS2 | _FNM_IGNORECASE)
2311 == FNM_MATCH)
2312 );
2313}
2314
2315/* ******************************************************************
2316 *
2317 * Fast string searches
2318 *
2319 ********************************************************************/
2320
2321#define ASSERT(a)
2322
2323/*
2324 * The following code has been taken from the "Standard
2325 * Function Library", file sflfind.c, and only slightly
2326 * modified to conform to the rest of this file.
2327 *
2328 * Written: 96/04/24 iMatix SFL project team <sfl@imatix.com>
2329 * Revised: 98/05/04
2330 *
2331 * Copyright: Copyright (c) 1991-99 iMatix Corporation.
2332 *
2333 * The SFL Licence allows incorporating SFL code into other
2334 * programs, as long as the copyright is reprinted and the
2335 * code is marked as modified, so this is what we do.
2336 */
2337
2338/*
2339 *@@ strhmemfind:
2340 * searches for a pattern in a block of memory using the
2341 * Boyer-Moore-Horspool-Sunday algorithm.
2342 *
2343 * The block and pattern may contain any values; you must
2344 * explicitly provide their lengths. If you search for strings,
2345 * use strlen() on the buffers.
2346 *
2347 * Returns a pointer to the pattern if found within the block,
2348 * or NULL if the pattern was not found.
2349 *
2350 * This algorithm needs a "shift table" to cache data for the
2351 * search pattern. This table can be reused when performing
2352 * several searches with the same pattern.
2353 *
2354 * "shift" must point to an array big enough to hold 256 (8**2)
2355 * "size_t" values.
2356 *
2357 * If (*repeat_find == FALSE), the shift table is initialized.
2358 * So on the first search with a given pattern, *repeat_find
2359 * should be FALSE. This function sets it to TRUE after the
2360 * shift table is initialised, allowing the initialisation
2361 * phase to be skipped on subsequent searches.
2362 *
2363 * This function is most effective when repeated searches are
2364 * made for the same pattern in one or more large buffers.
2365 *
2366 * Example:
2367 *
2368 + PSZ pszHaystack = "This is a sample string.",
2369 + pszNeedle = "string";
2370 + size_t shift[256];
2371 + BOOL fRepeat = FALSE;
2372 +
2373 + PSZ pFound = strhmemfind(pszHaystack,
2374 + strlen(pszHaystack), // block size
2375 + pszNeedle,
2376 + strlen(pszNeedle), // pattern size
2377 + shift,
2378 + &fRepeat);
2379 *
2380 * Taken from the "Standard Function Library", file sflfind.c.
2381 * Copyright: Copyright (c) 1991-99 iMatix Corporation.
2382 * Slightly modified by umoeller.
2383 *
2384 *@@added V0.9.3 (2000-05-08) [umoeller]
2385 */
2386
2387void* strhmemfind(const void *in_block, // in: block containing data
2388 size_t block_size, // in: size of block in bytes
2389 const void *in_pattern, // in: pattern to search for
2390 size_t pattern_size, // in: size of pattern block
2391 size_t *shift, // in/out: shift table (search buffer)
2392 BOOL *repeat_find) // in/out: if TRUE, *shift is already initialized
2393{
2394 size_t byte_nbr, // Distance through block
2395 match_size; // Size of matched part
2396 const unsigned char
2397 *match_base = NULL, // Base of match of pattern
2398 *match_ptr = NULL, // Point within current match
2399 *limit = NULL; // Last potiental match point
2400 const unsigned char
2401 *block = (unsigned char *) in_block, // Concrete pointer to block data
2402 *pattern = (unsigned char *) in_pattern; // Concrete pointer to search value
2403
2404 if ( (block == NULL)
2405 || (pattern == NULL)
2406 || (shift == NULL)
2407 )
2408 return (NULL);
2409
2410 // Pattern must be smaller or equal in size to string
2411 if (block_size < pattern_size)
2412 return (NULL); // Otherwise it's not found
2413
2414 if (pattern_size == 0) // Empty patterns match at start
2415 return ((void *)block);
2416
2417 // Build the shift table unless we're continuing a previous search
2418
2419 // The shift table determines how far to shift before trying to match
2420 // again, if a match at this point fails. If the byte after where the
2421 // end of our pattern falls is not in our pattern, then we start to
2422 // match again after that byte; otherwise we line up the last occurence
2423 // of that byte in our pattern under that byte, and try match again.
2424
2425 if (!repeat_find || !*repeat_find)
2426 {
2427 for (byte_nbr = 0;
2428 byte_nbr < 256;
2429 byte_nbr++)
2430 shift[byte_nbr] = pattern_size + 1;
2431 for (byte_nbr = 0;
2432 byte_nbr < pattern_size;
2433 byte_nbr++)
2434 shift[(unsigned char)pattern[byte_nbr]] = pattern_size - byte_nbr;
2435
2436 if (repeat_find)
2437 *repeat_find = TRUE;
2438 }
2439
2440 // Search for the block, each time jumping up by the amount
2441 // computed in the shift table
2442
2443 limit = block + (block_size - pattern_size + 1);
2444 ASSERT (limit > block);
2445
2446 for (match_base = block;
2447 match_base < limit;
2448 match_base += shift[*(match_base + pattern_size)])
2449 {
2450 match_ptr = match_base;
2451 match_size = 0;
2452
2453 // Compare pattern until it all matches, or we find a difference
2454 while (*match_ptr++ == pattern[match_size++])
2455 {
2456 ASSERT (match_size <= pattern_size &&
2457 match_ptr == (match_base + match_size));
2458
2459 // If we found a match, return the start address
2460 if (match_size >= pattern_size)
2461 return ((void*)(match_base));
2462
2463 }
2464 }
2465 return (NULL); // Found nothing
2466}
2467
2468/*
2469 *@@ strhtxtfind:
2470 * searches for a case-insensitive text pattern in a string
2471 * using the Boyer-Moore-Horspool-Sunday algorithm. The string and
2472 * pattern are null-terminated strings. Returns a pointer to the pattern
2473 * if found within the string, or NULL if the pattern was not found.
2474 * Will match strings irrespective of case. To match exact strings, use
2475 * strhfind(). Will not work on multibyte characters.
2476 *
2477 * Examples:
2478 + char *result;
2479 +
2480 + result = strhtxtfind ("AbracaDabra", "cad");
2481 + if (result)
2482 + puts (result);
2483 +
2484 * Taken from the "Standard Function Library", file sflfind.c.
2485 * Copyright: Copyright (c) 1991-99 iMatix Corporation.
2486 * Slightly modified.
2487 *
2488 *@@added V0.9.3 (2000-05-08) [umoeller]
2489 */
2490
2491char* strhtxtfind (const char *string, // String containing data
2492 const char *pattern) // Pattern to search for
2493{
2494 size_t
2495 shift [256]; // Shift distance for each value
2496 size_t
2497 string_size,
2498 pattern_size,
2499 byte_nbr, // Index into byte array
2500 match_size; // Size of matched part
2501 const char
2502 *match_base = NULL, // Base of match of pattern
2503 *match_ptr = NULL, // Point within current match
2504 *limit = NULL; // Last potiental match point
2505
2506 ASSERT (string); // Expect non-NULL pointers, but
2507 ASSERT (pattern); // fail gracefully if not debugging
2508 if (string == NULL || pattern == NULL)
2509 return (NULL);
2510
2511 string_size = strlen (string);
2512 pattern_size = strlen (pattern);
2513
2514 // Pattern must be smaller or equal in size to string
2515 if (string_size < pattern_size)
2516 return (NULL); // Otherwise it cannot be found
2517
2518 if (pattern_size == 0) // Empty string matches at start
2519 return (char *) string;
2520
2521 // Build the shift table
2522
2523 // The shift table determines how far to shift before trying to match
2524 // again, if a match at this point fails. If the byte after where the
2525 // end of our pattern falls is not in our pattern, then we start to
2526 // match again after that byte; otherwise we line up the last occurence
2527 // of that byte in our pattern under that byte, and try match again.
2528
2529 for (byte_nbr = 0; byte_nbr < 256; byte_nbr++)
2530 shift [byte_nbr] = pattern_size + 1;
2531
2532 for (byte_nbr = 0; byte_nbr < pattern_size; byte_nbr++)
2533 shift [(unsigned char) tolower (pattern [byte_nbr])] = pattern_size - byte_nbr;
2534
2535 // Search for the string. If we don't find a match, move up by the
2536 // amount we computed in the shift table above, to find location of
2537 // the next potiental match.
2538
2539 limit = string + (string_size - pattern_size + 1);
2540 ASSERT (limit > string);
2541
2542 for (match_base = string;
2543 match_base < limit;
2544 match_base += shift [(unsigned char) tolower (*(match_base + pattern_size))])
2545 {
2546 match_ptr = match_base;
2547 match_size = 0;
2548
2549 // Compare pattern until it all matches, or we find a difference
2550 while (tolower (*match_ptr++) == tolower (pattern [match_size++]))
2551 {
2552 ASSERT (match_size <= pattern_size &&
2553 match_ptr == (match_base + match_size));
2554
2555 // If we found a match, return the start address
2556 if (match_size >= pattern_size)
2557 return ((char *)(match_base));
2558 }
2559 }
2560 return (NULL); // Found nothing
2561}
2562
Note: See TracBrowser for help on using the repository browser.