Use "Returns:" instead of the invalid "@returns" for annotating return values.
[platform/upstream/glib.git] / glib / gpattern.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997, 1999  Peter Mattis, Red Hat, Inc.
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 #include "config.h"
21
22 #include <string.h>
23
24 #include "gpattern.h"
25
26 #include "gmacros.h"
27 #include "gmessages.h"
28 #include "gmem.h"
29 #include "gunicode.h"
30 #include "gutils.h" 
31
32 /**
33  * SECTION:patterns
34  * @title: Glob-style pattern matching
35  * @short_description: matches strings against patterns containing '*'
36  *                     (wildcard) and '?' (joker)
37  *
38  * The <function>g_pattern_match*</function> functions match a string
39  * against a pattern containing '*' and '?' wildcards with similar
40  * semantics as the standard glob() function: '*' matches an arbitrary,
41  * possibly empty, string, '?' matches an arbitrary character.
42  *
43  * Note that in contrast to glob(), the '/' character
44  * <emphasis>can</emphasis> be matched by the wildcards, there are no
45  * '[...]' character ranges and '*' and '?' can
46  * <emphasis>not</emphasis> be escaped to include them literally in a
47  * pattern.
48  *
49  * When multiple strings must be matched against the same pattern, it
50  * is better to compile the pattern to a #GPatternSpec using
51  * g_pattern_spec_new() and use g_pattern_match_string() instead of
52  * g_pattern_match_simple(). This avoids the overhead of repeated
53  * pattern compilation.
54  **/
55
56 /**
57  * GPatternSpec:
58  *
59  * A <structname>GPatternSpec</structname> is the 'compiled' form of a
60  * pattern. This structure is opaque and its fields cannot be accessed
61  * directly.
62  **/
63
64 /* keep enum and structure of gpattern.c and patterntest.c in sync */
65 typedef enum
66 {
67   G_MATCH_ALL,       /* "*A?A*" */
68   G_MATCH_ALL_TAIL,  /* "*A?AA" */
69   G_MATCH_HEAD,      /* "AAAA*" */
70   G_MATCH_TAIL,      /* "*AAAA" */
71   G_MATCH_EXACT,     /* "AAAAA" */
72   G_MATCH_LAST
73 } GMatchType;
74
75 struct _GPatternSpec
76 {
77   GMatchType match_type;
78   guint      pattern_length;
79   guint      min_length;
80   guint      max_length;
81   gchar     *pattern;
82 };
83
84
85 /* --- functions --- */
86 static inline gboolean
87 g_pattern_ph_match (const gchar *match_pattern,
88                     const gchar *match_string,
89                     gboolean    *wildcard_reached_p)
90 {
91   register const gchar *pattern, *string;
92   register gchar ch;
93
94   pattern = match_pattern;
95   string = match_string;
96
97   ch = *pattern;
98   pattern++;
99   while (ch)
100     {
101       switch (ch)
102         {
103         case '?':
104           if (!*string)
105             return FALSE;
106           string = g_utf8_next_char (string);
107           break;
108
109         case '*':
110           *wildcard_reached_p = TRUE;
111           do
112             {
113               ch = *pattern;
114               pattern++;
115               if (ch == '?')
116                 {
117                   if (!*string)
118                     return FALSE;
119                   string = g_utf8_next_char (string);
120                 }
121             }
122           while (ch == '*' || ch == '?');
123           if (!ch)
124             return TRUE;
125           do
126             {
127               gboolean next_wildcard_reached = FALSE;
128               while (ch != *string)
129                 {
130                   if (!*string)
131                     return FALSE;
132                   string = g_utf8_next_char (string);
133                 }
134               string++;
135               if (g_pattern_ph_match (pattern, string, &next_wildcard_reached))
136                 return TRUE;
137               if (next_wildcard_reached)
138                 /* the forthcoming pattern substring up to the next wildcard has
139                  * been matched, but a mismatch occoured for the rest of the
140                  * pattern, following the next wildcard.
141                  * there's no need to advance the current match position any
142                  * further if the rest pattern will not match.
143                  */
144                 return FALSE;
145             }
146           while (*string);
147           break;
148
149         default:
150           if (ch == *string)
151             string++;
152           else
153             return FALSE;
154           break;
155         }
156
157       ch = *pattern;
158       pattern++;
159     }
160
161   return *string == 0;
162 }
163
164 /**
165  * g_pattern_match:
166  * @pspec: a #GPatternSpec
167  * @string_length: the length of @string (in bytes, i.e. strlen(),
168  *                 <emphasis>not</emphasis> g_utf8_strlen())
169  * @string: the UTF-8 encoded string to match
170  * @string_reversed: (allow-none): the reverse of @string or %NULL
171  *
172  * Matches a string against a compiled pattern. Passing the correct
173  * length of the string given is mandatory. The reversed string can be
174  * omitted by passing %NULL, this is more efficient if the reversed
175  * version of the string to be matched is not at hand, as
176  * g_pattern_match() will only construct it if the compiled pattern
177  * requires reverse matches.
178  *
179  * Note that, if the user code will (possibly) match a string against a
180  * multitude of patterns containing wildcards, chances are high that
181  * some patterns will require a reversed string. In this case, it's
182  * more efficient to provide the reversed string to avoid multiple
183  * constructions thereof in the various calls to g_pattern_match().
184  *
185  * Note also that the reverse of a UTF-8 encoded string can in general
186  * <emphasis>not</emphasis> be obtained by g_strreverse(). This works
187  * only if the string doesn't contain any multibyte characters. GLib
188  * offers the g_utf8_strreverse() function to reverse UTF-8 encoded
189  * strings.
190  *
191  * Returns: %TRUE if @string matches @pspec
192  **/
193 gboolean
194 g_pattern_match (GPatternSpec *pspec,
195                  guint         string_length,
196                  const gchar  *string,
197                  const gchar  *string_reversed)
198 {
199   g_return_val_if_fail (pspec != NULL, FALSE);
200   g_return_val_if_fail (string != NULL, FALSE);
201
202   if (string_length < pspec->min_length ||
203       string_length > pspec->max_length)
204     return FALSE;
205
206   switch (pspec->match_type)
207     {
208       gboolean dummy;
209     case G_MATCH_ALL:
210       return g_pattern_ph_match (pspec->pattern, string, &dummy);
211     case G_MATCH_ALL_TAIL:
212       if (string_reversed)
213         return g_pattern_ph_match (pspec->pattern, string_reversed, &dummy);
214       else
215         {
216           gboolean result;
217           gchar *tmp;
218           tmp = g_utf8_strreverse (string, string_length);
219           result = g_pattern_ph_match (pspec->pattern, tmp, &dummy);
220           g_free (tmp);
221           return result;
222         }
223     case G_MATCH_HEAD:
224       if (pspec->pattern_length == string_length)
225         return strcmp (pspec->pattern, string) == 0;
226       else if (pspec->pattern_length)
227         return strncmp (pspec->pattern, string, pspec->pattern_length) == 0;
228       else
229         return TRUE;
230     case G_MATCH_TAIL:
231       if (pspec->pattern_length)
232         return strcmp (pspec->pattern, string + (string_length - pspec->pattern_length)) == 0;
233       else
234         return TRUE;
235     case G_MATCH_EXACT:
236       if (pspec->pattern_length != string_length)
237         return FALSE;
238       else
239         return strcmp (pspec->pattern, string) == 0;
240     default:
241       g_return_val_if_fail (pspec->match_type < G_MATCH_LAST, FALSE);
242       return FALSE;
243     }
244 }
245
246 /**
247  * g_pattern_spec_new:
248  * @pattern: a zero-terminated UTF-8 encoded string
249  *
250  * Compiles a pattern to a #GPatternSpec.
251  *
252  * Returns: a newly-allocated #GPatternSpec
253  **/
254 GPatternSpec*
255 g_pattern_spec_new (const gchar *pattern)
256 {
257   GPatternSpec *pspec;
258   gboolean seen_joker = FALSE, seen_wildcard = FALSE, more_wildcards = FALSE;
259   gint hw_pos = -1, tw_pos = -1, hj_pos = -1, tj_pos = -1;
260   gboolean follows_wildcard = FALSE;
261   guint pending_jokers = 0;
262   const gchar *s;
263   gchar *d;
264   guint i;
265   
266   g_return_val_if_fail (pattern != NULL, NULL);
267
268   /* canonicalize pattern and collect necessary stats */
269   pspec = g_new (GPatternSpec, 1);
270   pspec->pattern_length = strlen (pattern);
271   pspec->min_length = 0;
272   pspec->max_length = 0;
273   pspec->pattern = g_new (gchar, pspec->pattern_length + 1);
274   d = pspec->pattern;
275   for (i = 0, s = pattern; *s != 0; s++)
276     {
277       switch (*s)
278         {
279         case '*':
280           if (follows_wildcard) /* compress multiple wildcards */
281             {
282               pspec->pattern_length--;
283               continue;
284             }
285           follows_wildcard = TRUE;
286           if (hw_pos < 0)
287             hw_pos = i;
288           tw_pos = i;
289           break;
290         case '?':
291           pending_jokers++;
292           pspec->min_length++;
293           pspec->max_length += 4; /* maximum UTF-8 character length */
294           continue;
295         default:
296           for (; pending_jokers; pending_jokers--, i++) {
297             *d++ = '?';
298             if (hj_pos < 0)
299              hj_pos = i;
300             tj_pos = i;
301           }
302           follows_wildcard = FALSE;
303           pspec->min_length++;
304           pspec->max_length++;
305           break;
306         }
307       *d++ = *s;
308       i++;
309     }
310   for (; pending_jokers; pending_jokers--) {
311     *d++ = '?';
312     if (hj_pos < 0)
313       hj_pos = i;
314     tj_pos = i;
315   }
316   *d++ = 0;
317   seen_joker = hj_pos >= 0;
318   seen_wildcard = hw_pos >= 0;
319   more_wildcards = seen_wildcard && hw_pos != tw_pos;
320   if (seen_wildcard)
321     pspec->max_length = G_MAXUINT;
322
323   /* special case sole head/tail wildcard or exact matches */
324   if (!seen_joker && !more_wildcards)
325     {
326       if (pspec->pattern[0] == '*')
327         {
328           pspec->match_type = G_MATCH_TAIL;
329           memmove (pspec->pattern, pspec->pattern + 1, --pspec->pattern_length);
330           pspec->pattern[pspec->pattern_length] = 0;
331           return pspec;
332         }
333       if (pspec->pattern_length > 0 &&
334           pspec->pattern[pspec->pattern_length - 1] == '*')
335         {
336           pspec->match_type = G_MATCH_HEAD;
337           pspec->pattern[--pspec->pattern_length] = 0;
338           return pspec;
339         }
340       if (!seen_wildcard)
341         {
342           pspec->match_type = G_MATCH_EXACT;
343           return pspec;
344         }
345     }
346
347   /* now just need to distinguish between head or tail match start */
348   tw_pos = pspec->pattern_length - 1 - tw_pos;  /* last pos to tail distance */
349   tj_pos = pspec->pattern_length - 1 - tj_pos;  /* last pos to tail distance */
350   if (seen_wildcard)
351     pspec->match_type = tw_pos > hw_pos ? G_MATCH_ALL_TAIL : G_MATCH_ALL;
352   else /* seen_joker */
353     pspec->match_type = tj_pos > hj_pos ? G_MATCH_ALL_TAIL : G_MATCH_ALL;
354   if (pspec->match_type == G_MATCH_ALL_TAIL) {
355     gchar *tmp = pspec->pattern;
356     pspec->pattern = g_utf8_strreverse (pspec->pattern, pspec->pattern_length);
357     g_free (tmp);
358   }
359   return pspec;
360 }
361
362 /**
363  * g_pattern_spec_free:
364  * @pspec: a #GPatternSpec
365  *
366  * Frees the memory allocated for the #GPatternSpec.
367  **/
368 void
369 g_pattern_spec_free (GPatternSpec *pspec)
370 {
371   g_return_if_fail (pspec != NULL);
372
373   g_free (pspec->pattern);
374   g_free (pspec);
375 }
376
377 /**
378  * g_pattern_spec_equal:
379  * @pspec1: a #GPatternSpec
380  * @pspec2: another #GPatternSpec
381  *
382  * Compares two compiled pattern specs and returns whether they will
383  * match the same set of strings.
384  *
385  * Returns: Whether the compiled patterns are equal
386  **/
387 gboolean
388 g_pattern_spec_equal (GPatternSpec *pspec1,
389                       GPatternSpec *pspec2)
390 {
391   g_return_val_if_fail (pspec1 != NULL, FALSE);
392   g_return_val_if_fail (pspec2 != NULL, FALSE);
393
394   return (pspec1->pattern_length == pspec2->pattern_length &&
395           pspec1->match_type == pspec2->match_type &&
396           strcmp (pspec1->pattern, pspec2->pattern) == 0);
397 }
398
399 /**
400  * g_pattern_match_string:
401  * @pspec: a #GPatternSpec
402  * @string: the UTF-8 encoded string to match
403  *
404  * Matches a string against a compiled pattern. If the string is to be
405  * matched against more than one pattern, consider using
406  * g_pattern_match() instead while supplying the reversed string.
407  *
408  * Returns: %TRUE if @string matches @pspec
409  **/
410 gboolean
411 g_pattern_match_string (GPatternSpec *pspec,
412                         const gchar  *string)
413 {
414   g_return_val_if_fail (pspec != NULL, FALSE);
415   g_return_val_if_fail (string != NULL, FALSE);
416
417   return g_pattern_match (pspec, strlen (string), string, NULL);
418 }
419
420 /**
421  * g_pattern_match_simple:
422  * @pattern: the UTF-8 encoded pattern
423  * @string: the UTF-8 encoded string to match
424  *
425  * Matches a string against a pattern given as a string. If this
426  * function is to be called in a loop, it's more efficient to compile
427  * the pattern once with g_pattern_spec_new() and call
428  * g_pattern_match_string() repeatedly.
429  *
430  * Returns: %TRUE if @string matches @pspec
431  **/
432 gboolean
433 g_pattern_match_simple (const gchar *pattern,
434                         const gchar *string)
435 {
436   GPatternSpec *pspec;
437   gboolean ergo;
438
439   g_return_val_if_fail (pattern != NULL, FALSE);
440   g_return_val_if_fail (string != NULL, FALSE);
441
442   pspec = g_pattern_spec_new (pattern);
443   ergo = g_pattern_match (pspec, strlen (string), string, NULL);
444   g_pattern_spec_free (pspec);
445
446   return ergo;
447 }