aboutsummaryrefslogtreecommitdiff
path: root/contrib/soundex/soundex.c
blob: f2acba403666a21e00ea57120a6de082e52212c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/* $Header: /cvsroot/pgsql/contrib/soundex/Attic/soundex.c,v 1.7 2000/10/04 19:25:34 petere Exp $ */
#include "postgres.h"
#include "fmgr.h"
#include "utils/builtins.h"
#include <ctype.h>
#include <string.h>
#include <stdio.h>


Datum
text_soundex(PG_FUNCTION_ARGS);

static void
soundex(const char *instr, char *outstr);

#define SOUNDEX_LEN 4


#define _textin(str) DirectFunctionCall1(textin, CStringGetDatum(str))
#define _textout(str) DatumGetPointer(DirectFunctionCall1(textout, PointerGetDatum(str)))


#ifndef SOUNDEX_TEST
/*
 * SQL function: text_soundex(text) returns text
 */
Datum
text_soundex(PG_FUNCTION_ARGS)
{
	char		outstr[SOUNDEX_LEN + 1];
	char	   *arg;

	arg = _textout(PG_GETARG_TEXT_P(0));

	soundex(arg, outstr);

	PG_RETURN_TEXT_P(_textin(outstr));
}
#endif /* not SOUNDEX_TEST */


/*                                  ABCDEFGHIJKLMNOPQRSTUVWXYZ */
static const char *soundex_table = "01230120022455012623010202";
#define soundex_code(letter) soundex_table[toupper(letter) - 'A']


static void
soundex(const char *instr, char *outstr)
{
	int			count;

	AssertArg(instr);
	AssertArg(outstr);

	outstr[SOUNDEX_LEN] = '\0';

	/* Skip leading non-alphabetic characters */
	while (!isalpha(instr[0]) && instr[0])
		++instr;

	/* No string left */
	if (!instr[0])
	{
		outstr[0] = (char) 0;
		return;
	}

	/* Take the first letter as is */
	*outstr++ = (char) toupper(*instr++);

	count = 1;
	while (*instr && count < SOUNDEX_LEN)
	{
		if (isalpha(*instr) && soundex_code(*instr) != soundex_code(*(instr - 1)))
		{
			*outstr = soundex_code(instr[0]);
			if (*outstr != '0')
			{
				++outstr;
				++count;
			}
		}
		++instr;
	}

	/* Fill with 0's */
	while (count < SOUNDEX_LEN)
	{
		*outstr = '0';
		++outstr;
		++count;
	}
}



#ifdef SOUNDEX_TEST
int
main (int argc, char *argv[])
{
	if (argc < 2)
	{
		fprintf(stderr, "usage: %s string\n", argv[0]);
		return 1;
	}
	else
	{
		char output[SOUNDEX_LEN + 1];

		soundex(argv[1], output);
		printf("soundex(%s) = %s\n", argv[1], output);
		return 0;
	}
}
#endif /* SOUNDEX_TEST */