]> granicus.if.org Git - postgresql/blob - contrib/fuzzystrmatch/fuzzystrmatch.c
Remove dead code.
[postgresql] / contrib / fuzzystrmatch / fuzzystrmatch.c
1 /*
2  * fuzzystrmatch.c
3  *
4  * Functions for "fuzzy" comparison of strings
5  *
6  * Joe Conway <mail@joeconway.com>
7  *
8  * contrib/fuzzystrmatch/fuzzystrmatch.c
9  * Copyright (c) 2001-2015, PostgreSQL Global Development Group
10  * ALL RIGHTS RESERVED;
11  *
12  * metaphone()
13  * -----------
14  * Modified for PostgreSQL by Joe Conway.
15  * Based on CPAN's "Text-Metaphone-1.96" by Michael G Schwern <schwern@pobox.com>
16  * Code slightly modified for use as PostgreSQL function (palloc, elog, etc).
17  * Metaphone was originally created by Lawrence Philips and presented in article
18  * in "Computer Language" December 1990 issue.
19  *
20  * Permission to use, copy, modify, and distribute this software and its
21  * documentation for any purpose, without fee, and without a written agreement
22  * is hereby granted, provided that the above copyright notice and this
23  * paragraph and the following two paragraphs appear in all copies.
24  *
25  * IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
26  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
27  * LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
28  * DOCUMENTATION, EVEN IF THE AUTHOR OR DISTRIBUTORS HAVE BEEN ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  *
31  * THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
32  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
33  * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
34  * ON AN "AS IS" BASIS, AND THE AUTHOR AND DISTRIBUTORS HAS NO OBLIGATIONS TO
35  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
36  *
37  */
38
39 #include "postgres.h"
40
41 #include <ctype.h>
42
43 #include "mb/pg_wchar.h"
44 #include "utils/builtins.h"
45
46 PG_MODULE_MAGIC;
47
48 /*
49  * Soundex
50  */
51 static void _soundex(const char *instr, char *outstr);
52
53 #define SOUNDEX_LEN 4
54
55 /*                                                                      ABCDEFGHIJKLMNOPQRSTUVWXYZ */
56 static const char *soundex_table = "01230120022455012623010202";
57
58 static char
59 soundex_code(char letter)
60 {
61         letter = toupper((unsigned char) letter);
62         /* Defend against non-ASCII letters */
63         if (letter >= 'A' && letter <= 'Z')
64                 return soundex_table[letter - 'A'];
65         return letter;
66 }
67
68 /*
69  * Metaphone
70  */
71 #define MAX_METAPHONE_STRLEN            255
72
73 /*
74  * Original code by Michael G Schwern starts here.
75  * Code slightly modified for use as PostgreSQL function.
76  */
77
78
79 /**************************************************************************
80         metaphone -- Breaks english phrases down into their phonemes.
81
82         Input
83                 word                    --      An english word to be phonized
84                 max_phonemes    --      How many phonemes to calculate.  If 0, then it
85                                                         will phonize the entire phrase.
86                 phoned_word             --      The final phonized word.  (We'll allocate the
87                                                         memory.)
88         Output
89                 error   --      A simple error flag, returns TRUE or FALSE
90
91         NOTES:  ALL non-alpha characters are ignored, this includes whitespace,
92         although non-alpha characters will break up phonemes.
93 ****************************************************************************/
94
95
96 /**************************************************************************
97         my constants -- constants I like
98
99         Probably redundant.
100
101 ***************************************************************************/
102
103 #define META_ERROR                      FALSE
104 #define META_SUCCESS            TRUE
105 #define META_FAILURE            FALSE
106
107
108 /*      I add modifications to the traditional metaphone algorithm that you
109         might find in books.  Define this if you want metaphone to behave
110         traditionally */
111 #undef USE_TRADITIONAL_METAPHONE
112
113 /* Special encodings */
114 #define  SH             'X'
115 #define  TH             '0'
116
117 static char Lookahead(char *word, int how_far);
118 static int      _metaphone(char *word, int max_phonemes, char **phoned_word);
119
120 /* Metachar.h ... little bits about characters for metaphone */
121
122
123 /*-- Character encoding array & accessing macros --*/
124 /* Stolen directly out of the book... */
125 static const char _codes[26] = {
126         1, 16, 4, 16, 9, 2, 4, 16, 9, 2, 0, 2, 2, 2, 1, 4, 0, 2, 4, 4, 1, 0, 0, 0, 8, 0
127 /*      a  b c  d e f g  h i j k l m n o p q r s t u v w x y z */
128 };
129
130 static int
131 getcode(char c)
132 {
133         if (isalpha((unsigned char) c))
134         {
135                 c = toupper((unsigned char) c);
136                 /* Defend against non-ASCII letters */
137                 if (c >= 'A' && c <= 'Z')
138                         return _codes[c - 'A'];
139         }
140         return 0;
141 }
142
143 #define isvowel(c)      (getcode(c) & 1)        /* AEIOU */
144
145 /* These letters are passed through unchanged */
146 #define NOCHANGE(c) (getcode(c) & 2)    /* FJMNR */
147
148 /* These form diphthongs when preceding H */
149 #define AFFECTH(c)      (getcode(c) & 4)        /* CGPST */
150
151 /* These make C and G soft */
152 #define MAKESOFT(c) (getcode(c) & 8)    /* EIY */
153
154 /* These prevent GH from becoming F */
155 #define NOGHTOF(c)      (getcode(c) & 16)       /* BDH */
156
157 PG_FUNCTION_INFO_V1(levenshtein_with_costs);
158 Datum
159 levenshtein_with_costs(PG_FUNCTION_ARGS)
160 {
161         text       *src = PG_GETARG_TEXT_PP(0);
162         text       *dst = PG_GETARG_TEXT_PP(1);
163         int                     ins_c = PG_GETARG_INT32(2);
164         int                     del_c = PG_GETARG_INT32(3);
165         int                     sub_c = PG_GETARG_INT32(4);
166         const char *s_data;
167         const char *t_data;
168         int                     s_bytes,
169                                 t_bytes;
170
171         /* Extract a pointer to the actual character data */
172         s_data = VARDATA_ANY(src);
173         t_data = VARDATA_ANY(dst);
174         /* Determine length of each string in bytes and characters */
175         s_bytes = VARSIZE_ANY_EXHDR(src);
176         t_bytes = VARSIZE_ANY_EXHDR(dst);
177
178         PG_RETURN_INT32(varstr_levenshtein(s_data, s_bytes, t_data, t_bytes, ins_c,
179                                                                            del_c, sub_c));
180 }
181
182
183 PG_FUNCTION_INFO_V1(levenshtein);
184 Datum
185 levenshtein(PG_FUNCTION_ARGS)
186 {
187         text       *src = PG_GETARG_TEXT_PP(0);
188         text       *dst = PG_GETARG_TEXT_PP(1);
189         const char *s_data;
190         const char *t_data;
191         int                     s_bytes,
192                                 t_bytes;
193
194         /* Extract a pointer to the actual character data */
195         s_data = VARDATA_ANY(src);
196         t_data = VARDATA_ANY(dst);
197         /* Determine length of each string in bytes and characters */
198         s_bytes = VARSIZE_ANY_EXHDR(src);
199         t_bytes = VARSIZE_ANY_EXHDR(dst);
200
201         PG_RETURN_INT32(varstr_levenshtein(s_data, s_bytes, t_data, t_bytes, 1, 1,
202                                                                            1));
203 }
204
205
206 PG_FUNCTION_INFO_V1(levenshtein_less_equal_with_costs);
207 Datum
208 levenshtein_less_equal_with_costs(PG_FUNCTION_ARGS)
209 {
210         text       *src = PG_GETARG_TEXT_PP(0);
211         text       *dst = PG_GETARG_TEXT_PP(1);
212         int                     ins_c = PG_GETARG_INT32(2);
213         int                     del_c = PG_GETARG_INT32(3);
214         int                     sub_c = PG_GETARG_INT32(4);
215         int                     max_d = PG_GETARG_INT32(5);
216         const char *s_data;
217         const char *t_data;
218         int                     s_bytes,
219                                 t_bytes;
220
221         /* Extract a pointer to the actual character data */
222         s_data = VARDATA_ANY(src);
223         t_data = VARDATA_ANY(dst);
224         /* Determine length of each string in bytes and characters */
225         s_bytes = VARSIZE_ANY_EXHDR(src);
226         t_bytes = VARSIZE_ANY_EXHDR(dst);
227
228         PG_RETURN_INT32(varstr_levenshtein_less_equal(s_data, s_bytes, t_data,
229                                                                                                   t_bytes, ins_c, del_c,
230                                                                                                   sub_c, max_d));
231 }
232
233
234 PG_FUNCTION_INFO_V1(levenshtein_less_equal);
235 Datum
236 levenshtein_less_equal(PG_FUNCTION_ARGS)
237 {
238         text       *src = PG_GETARG_TEXT_PP(0);
239         text       *dst = PG_GETARG_TEXT_PP(1);
240         int                     max_d = PG_GETARG_INT32(2);
241         const char *s_data;
242         const char *t_data;
243         int                     s_bytes,
244                                 t_bytes;
245
246         /* Extract a pointer to the actual character data */
247         s_data = VARDATA_ANY(src);
248         t_data = VARDATA_ANY(dst);
249         /* Determine length of each string in bytes and characters */
250         s_bytes = VARSIZE_ANY_EXHDR(src);
251         t_bytes = VARSIZE_ANY_EXHDR(dst);
252
253         PG_RETURN_INT32(varstr_levenshtein_less_equal(s_data, s_bytes, t_data,
254                                                                                                   t_bytes, 1, 1, 1, max_d));
255 }
256
257
258 /*
259  * Calculates the metaphone of an input string.
260  * Returns number of characters requested
261  * (suggested value is 4)
262  */
263 PG_FUNCTION_INFO_V1(metaphone);
264 Datum
265 metaphone(PG_FUNCTION_ARGS)
266 {
267         char       *str_i = TextDatumGetCString(PG_GETARG_DATUM(0));
268         size_t          str_i_len = strlen(str_i);
269         int                     reqlen;
270         char       *metaph;
271         int                     retval;
272
273         /* return an empty string if we receive one */
274         if (!(str_i_len > 0))
275                 PG_RETURN_TEXT_P(cstring_to_text(""));
276
277         if (str_i_len > MAX_METAPHONE_STRLEN)
278                 ereport(ERROR,
279                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
280                                  errmsg("argument exceeds the maximum length of %d bytes",
281                                                 MAX_METAPHONE_STRLEN)));
282
283         reqlen = PG_GETARG_INT32(1);
284         if (reqlen > MAX_METAPHONE_STRLEN)
285                 ereport(ERROR,
286                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
287                                  errmsg("output exceeds the maximum length of %d bytes",
288                                                 MAX_METAPHONE_STRLEN)));
289
290         if (!(reqlen > 0))
291                 ereport(ERROR,
292                                 (errcode(ERRCODE_ZERO_LENGTH_CHARACTER_STRING),
293                                  errmsg("output cannot be empty string")));
294
295
296         retval = _metaphone(str_i, reqlen, &metaph);
297         if (retval == META_SUCCESS)
298                 PG_RETURN_TEXT_P(cstring_to_text(metaph));
299         else
300         {
301                 /* internal error */
302                 elog(ERROR, "metaphone: failure");
303                 /* keep the compiler quiet */
304                 PG_RETURN_NULL();
305         }
306 }
307
308
309 /*
310  * Original code by Michael G Schwern starts here.
311  * Code slightly modified for use as PostgreSQL
312  * function (palloc, etc).
313  */
314
315 /* I suppose I could have been using a character pointer instead of
316  * accessing the array directly... */
317
318 /* Look at the next letter in the word */
319 #define Next_Letter (toupper((unsigned char) word[w_idx+1]))
320 /* Look at the current letter in the word */
321 #define Curr_Letter (toupper((unsigned char) word[w_idx]))
322 /* Go N letters back. */
323 #define Look_Back_Letter(n) \
324         (w_idx >= (n) ? toupper((unsigned char) word[w_idx-(n)]) : '\0')
325 /* Previous letter.  I dunno, should this return null on failure? */
326 #define Prev_Letter (Look_Back_Letter(1))
327 /* Look two letters down.  It makes sure you don't walk off the string. */
328 #define After_Next_Letter \
329         (Next_Letter != '\0' ? toupper((unsigned char) word[w_idx+2]) : '\0')
330 #define Look_Ahead_Letter(n) toupper((unsigned char) Lookahead(word+w_idx, n))
331
332
333 /* Allows us to safely look ahead an arbitrary # of letters */
334 /* I probably could have just used strlen... */
335 static char
336 Lookahead(char *word, int how_far)
337 {
338         char            letter_ahead = '\0';    /* null by default */
339         int                     idx;
340
341         for (idx = 0; word[idx] != '\0' && idx < how_far; idx++);
342         /* Edge forward in the string... */
343
344         letter_ahead = word[idx];       /* idx will be either == to how_far or at the
345                                                                  * end of the string */
346         return letter_ahead;
347 }
348
349
350 /* phonize one letter */
351 #define Phonize(c)      do {(*phoned_word)[p_idx++] = c;} while (0)
352 /* Slap a null character on the end of the phoned word */
353 #define End_Phoned_Word do {(*phoned_word)[p_idx] = '\0';} while (0)
354 /* How long is the phoned word? */
355 #define Phone_Len       (p_idx)
356
357 /* Note is a letter is a 'break' in the word */
358 #define Isbreak(c)      (!isalpha((unsigned char) (c)))
359
360
361 static int
362 _metaphone(char *word,                  /* IN */
363                    int max_phonemes,
364                    char **phoned_word)  /* OUT */
365 {
366         int                     w_idx = 0;              /* point in the phonization we're at. */
367         int                     p_idx = 0;              /* end of the phoned phrase */
368
369         /*-- Parameter checks --*/
370
371         /*
372          * Shouldn't be necessary, but left these here anyway jec Aug 3, 2001
373          */
374
375         /* Negative phoneme length is meaningless */
376         if (!(max_phonemes > 0))
377                 /* internal error */
378                 elog(ERROR, "metaphone: Requested output length must be > 0");
379
380         /* Empty/null string is meaningless */
381         if ((word == NULL) || !(strlen(word) > 0))
382                 /* internal error */
383                 elog(ERROR, "metaphone: Input string length must be > 0");
384
385         /*-- Allocate memory for our phoned_phrase --*/
386         if (max_phonemes == 0)
387         {                                                       /* Assume largest possible */
388                 *phoned_word = palloc(sizeof(char) * strlen(word) +1);
389         }
390         else
391         {
392                 *phoned_word = palloc(sizeof(char) * max_phonemes + 1);
393         }
394
395         /*-- The first phoneme has to be processed specially. --*/
396         /* Find our first letter */
397         for (; !isalpha((unsigned char) (Curr_Letter)); w_idx++)
398         {
399                 /* On the off chance we were given nothing but crap... */
400                 if (Curr_Letter == '\0')
401                 {
402                         End_Phoned_Word;
403                         return META_SUCCESS;    /* For testing */
404                 }
405         }
406
407         switch (Curr_Letter)
408         {
409                         /* AE becomes E */
410                 case 'A':
411                         if (Next_Letter == 'E')
412                         {
413                                 Phonize('E');
414                                 w_idx += 2;
415                         }
416                         /* Remember, preserve vowels at the beginning */
417                         else
418                         {
419                                 Phonize('A');
420                                 w_idx++;
421                         }
422                         break;
423                         /* [GKP]N becomes N */
424                 case 'G':
425                 case 'K':
426                 case 'P':
427                         if (Next_Letter == 'N')
428                         {
429                                 Phonize('N');
430                                 w_idx += 2;
431                         }
432                         break;
433
434                         /*
435                          * WH becomes H, WR becomes R W if followed by a vowel
436                          */
437                 case 'W':
438                         if (Next_Letter == 'H' ||
439                                 Next_Letter == 'R')
440                         {
441                                 Phonize(Next_Letter);
442                                 w_idx += 2;
443                         }
444                         else if (isvowel(Next_Letter))
445                         {
446                                 Phonize('W');
447                                 w_idx += 2;
448                         }
449                         /* else ignore */
450                         break;
451                         /* X becomes S */
452                 case 'X':
453                         Phonize('S');
454                         w_idx++;
455                         break;
456                         /* Vowels are kept */
457
458                         /*
459                          * We did A already case 'A': case 'a':
460                          */
461                 case 'E':
462                 case 'I':
463                 case 'O':
464                 case 'U':
465                         Phonize(Curr_Letter);
466                         w_idx++;
467                         break;
468                 default:
469                         /* do nothing */
470                         break;
471         }
472
473
474
475         /* On to the metaphoning */
476         for (; Curr_Letter != '\0' &&
477                  (max_phonemes == 0 || Phone_Len < max_phonemes);
478                  w_idx++)
479         {
480                 /*
481                  * How many letters to skip because an earlier encoding handled
482                  * multiple letters
483                  */
484                 unsigned short int skip_letter = 0;
485
486
487                 /*
488                  * THOUGHT:  It would be nice if, rather than having things like...
489                  * well, SCI.  For SCI you encode the S, then have to remember to skip
490                  * the C.  So the phonome SCI invades both S and C.  It would be
491                  * better, IMHO, to skip the C from the S part of the encoding. Hell,
492                  * I'm trying it.
493                  */
494
495                 /* Ignore non-alphas */
496                 if (!isalpha((unsigned char) (Curr_Letter)))
497                         continue;
498
499                 /* Drop duplicates, except CC */
500                 if (Curr_Letter == Prev_Letter &&
501                         Curr_Letter != 'C')
502                         continue;
503
504                 switch (Curr_Letter)
505                 {
506                                 /* B -> B unless in MB */
507                         case 'B':
508                                 if (Prev_Letter != 'M')
509                                         Phonize('B');
510                                 break;
511
512                                 /*
513                                  * 'sh' if -CIA- or -CH, but not SCH, except SCHW. (SCHW is
514                                  * handled in S) S if -CI-, -CE- or -CY- dropped if -SCI-,
515                                  * SCE-, -SCY- (handed in S) else K
516                                  */
517                         case 'C':
518                                 if (MAKESOFT(Next_Letter))
519                                 {                               /* C[IEY] */
520                                         if (After_Next_Letter == 'A' &&
521                                                 Next_Letter == 'I')
522                                         {                       /* CIA */
523                                                 Phonize(SH);
524                                         }
525                                         /* SC[IEY] */
526                                         else if (Prev_Letter == 'S')
527                                         {
528                                                 /* Dropped */
529                                         }
530                                         else
531                                                 Phonize('S');
532                                 }
533                                 else if (Next_Letter == 'H')
534                                 {
535 #ifndef USE_TRADITIONAL_METAPHONE
536                                         if (After_Next_Letter == 'R' ||
537                                                 Prev_Letter == 'S')
538                                         {                       /* Christ, School */
539                                                 Phonize('K');
540                                         }
541                                         else
542                                                 Phonize(SH);
543 #else
544                                         Phonize(SH);
545 #endif
546                                         skip_letter++;
547                                 }
548                                 else
549                                         Phonize('K');
550                                 break;
551
552                                 /*
553                                  * J if in -DGE-, -DGI- or -DGY- else T
554                                  */
555                         case 'D':
556                                 if (Next_Letter == 'G' &&
557                                         MAKESOFT(After_Next_Letter))
558                                 {
559                                         Phonize('J');
560                                         skip_letter++;
561                                 }
562                                 else
563                                         Phonize('T');
564                                 break;
565
566                                 /*
567                                  * F if in -GH and not B--GH, D--GH, -H--GH, -H---GH else
568                                  * dropped if -GNED, -GN, else dropped if -DGE-, -DGI- or
569                                  * -DGY- (handled in D) else J if in -GE-, -GI, -GY and not GG
570                                  * else K
571                                  */
572                         case 'G':
573                                 if (Next_Letter == 'H')
574                                 {
575                                         if (!(NOGHTOF(Look_Back_Letter(3)) ||
576                                                   Look_Back_Letter(4) == 'H'))
577                                         {
578                                                 Phonize('F');
579                                                 skip_letter++;
580                                         }
581                                         else
582                                         {
583                                                 /* silent */
584                                         }
585                                 }
586                                 else if (Next_Letter == 'N')
587                                 {
588                                         if (Isbreak(After_Next_Letter) ||
589                                                 (After_Next_Letter == 'E' &&
590                                                  Look_Ahead_Letter(3) == 'D'))
591                                         {
592                                                 /* dropped */
593                                         }
594                                         else
595                                                 Phonize('K');
596                                 }
597                                 else if (MAKESOFT(Next_Letter) &&
598                                                  Prev_Letter != 'G')
599                                         Phonize('J');
600                                 else
601                                         Phonize('K');
602                                 break;
603                                 /* H if before a vowel and not after C,G,P,S,T */
604                         case 'H':
605                                 if (isvowel(Next_Letter) &&
606                                         !AFFECTH(Prev_Letter))
607                                         Phonize('H');
608                                 break;
609
610                                 /*
611                                  * dropped if after C else K
612                                  */
613                         case 'K':
614                                 if (Prev_Letter != 'C')
615                                         Phonize('K');
616                                 break;
617
618                                 /*
619                                  * F if before H else P
620                                  */
621                         case 'P':
622                                 if (Next_Letter == 'H')
623                                         Phonize('F');
624                                 else
625                                         Phonize('P');
626                                 break;
627
628                                 /*
629                                  * K
630                                  */
631                         case 'Q':
632                                 Phonize('K');
633                                 break;
634
635                                 /*
636                                  * 'sh' in -SH-, -SIO- or -SIA- or -SCHW- else S
637                                  */
638                         case 'S':
639                                 if (Next_Letter == 'I' &&
640                                         (After_Next_Letter == 'O' ||
641                                          After_Next_Letter == 'A'))
642                                         Phonize(SH);
643                                 else if (Next_Letter == 'H')
644                                 {
645                                         Phonize(SH);
646                                         skip_letter++;
647                                 }
648 #ifndef USE_TRADITIONAL_METAPHONE
649                                 else if (Next_Letter == 'C' &&
650                                                  Look_Ahead_Letter(2) == 'H' &&
651                                                  Look_Ahead_Letter(3) == 'W')
652                                 {
653                                         Phonize(SH);
654                                         skip_letter += 2;
655                                 }
656 #endif
657                                 else
658                                         Phonize('S');
659                                 break;
660
661                                 /*
662                                  * 'sh' in -TIA- or -TIO- else 'th' before H else T
663                                  */
664                         case 'T':
665                                 if (Next_Letter == 'I' &&
666                                         (After_Next_Letter == 'O' ||
667                                          After_Next_Letter == 'A'))
668                                         Phonize(SH);
669                                 else if (Next_Letter == 'H')
670                                 {
671                                         Phonize(TH);
672                                         skip_letter++;
673                                 }
674                                 else
675                                         Phonize('T');
676                                 break;
677                                 /* F */
678                         case 'V':
679                                 Phonize('F');
680                                 break;
681                                 /* W before a vowel, else dropped */
682                         case 'W':
683                                 if (isvowel(Next_Letter))
684                                         Phonize('W');
685                                 break;
686                                 /* KS */
687                         case 'X':
688                                 Phonize('K');
689                                 if (max_phonemes == 0 || Phone_Len < max_phonemes)
690                                         Phonize('S');
691                                 break;
692                                 /* Y if followed by a vowel */
693                         case 'Y':
694                                 if (isvowel(Next_Letter))
695                                         Phonize('Y');
696                                 break;
697                                 /* S */
698                         case 'Z':
699                                 Phonize('S');
700                                 break;
701                                 /* No transformation */
702                         case 'F':
703                         case 'J':
704                         case 'L':
705                         case 'M':
706                         case 'N':
707                         case 'R':
708                                 Phonize(Curr_Letter);
709                                 break;
710                         default:
711                                 /* nothing */
712                                 break;
713                 }                                               /* END SWITCH */
714
715                 w_idx += skip_letter;
716         }                                                       /* END FOR */
717
718         End_Phoned_Word;
719
720         return (META_SUCCESS);
721 }       /* END metaphone */
722
723
724 /*
725  * SQL function: soundex(text) returns text
726  */
727 PG_FUNCTION_INFO_V1(soundex);
728
729 Datum
730 soundex(PG_FUNCTION_ARGS)
731 {
732         char            outstr[SOUNDEX_LEN + 1];
733         char       *arg;
734
735         arg = text_to_cstring(PG_GETARG_TEXT_P(0));
736
737         _soundex(arg, outstr);
738
739         PG_RETURN_TEXT_P(cstring_to_text(outstr));
740 }
741
742 static void
743 _soundex(const char *instr, char *outstr)
744 {
745         int                     count;
746
747         AssertArg(instr);
748         AssertArg(outstr);
749
750         outstr[SOUNDEX_LEN] = '\0';
751
752         /* Skip leading non-alphabetic characters */
753         while (!isalpha((unsigned char) instr[0]) && instr[0])
754                 ++instr;
755
756         /* No string left */
757         if (!instr[0])
758         {
759                 outstr[0] = (char) 0;
760                 return;
761         }
762
763         /* Take the first letter as is */
764         *outstr++ = (char) toupper((unsigned char) *instr++);
765
766         count = 1;
767         while (*instr && count < SOUNDEX_LEN)
768         {
769                 if (isalpha((unsigned char) *instr) &&
770                         soundex_code(*instr) != soundex_code(*(instr - 1)))
771                 {
772                         *outstr = soundex_code(instr[0]);
773                         if (*outstr != '0')
774                         {
775                                 ++outstr;
776                                 ++count;
777                         }
778                 }
779                 ++instr;
780         }
781
782         /* Fill with 0's */
783         while (count < SOUNDEX_LEN)
784         {
785                 *outstr = '0';
786                 ++outstr;
787                 ++count;
788         }
789 }
790
791 PG_FUNCTION_INFO_V1(difference);
792
793 Datum
794 difference(PG_FUNCTION_ARGS)
795 {
796         char            sndx1[SOUNDEX_LEN + 1],
797                                 sndx2[SOUNDEX_LEN + 1];
798         int                     i,
799                                 result;
800
801         _soundex(text_to_cstring(PG_GETARG_TEXT_P(0)), sndx1);
802         _soundex(text_to_cstring(PG_GETARG_TEXT_P(1)), sndx2);
803
804         result = 0;
805         for (i = 0; i < SOUNDEX_LEN; i++)
806         {
807                 if (sndx1[i] == sndx2[i])
808                         result++;
809         }
810
811         PG_RETURN_INT32(result);
812 }