soundex.c 2.1 KB
Newer Older
B
Bruce Momjian 已提交
1
/* $Header: /cvsroot/pgsql/contrib/soundex/Attic/soundex.c,v 1.11 2001/03/22 03:59:10 momjian Exp $ */
2
#include "postgres.h"
3 4 5

#include <ctype.h>

6 7
#include "fmgr.h"
#include "utils/builtins.h"
8 9


B
Bruce Momjian 已提交
10
Datum		text_soundex(PG_FUNCTION_ARGS);
M
Marc G. Fournier 已提交
11

12
static void soundex(const char *instr, char *outstr);
M
Marc G. Fournier 已提交
13

14
#define SOUNDEX_LEN 4
15 16


17 18
#define _textin(str) DirectFunctionCall1(textin, CStringGetDatum(str))
#define _textout(str) DatumGetPointer(DirectFunctionCall1(textout, PointerGetDatum(str)))
19 20


21 22 23 24
#ifndef SOUNDEX_TEST
/*
 * SQL function: text_soundex(text) returns text
 */
25 26
PG_FUNCTION_INFO_V1(text_soundex);

27 28 29 30 31 32 33
Datum
text_soundex(PG_FUNCTION_ARGS)
{
	char		outstr[SOUNDEX_LEN + 1];
	char	   *arg;

	arg = _textout(PG_GETARG_TEXT_P(0));
34

35
	soundex(arg, outstr);
36

37
	PG_RETURN_TEXT_P(_textin(outstr));
M
Marc G. Fournier 已提交
38
}
39

B
Bruce Momjian 已提交
40
#endif	 /* not SOUNDEX_TEST */
41 42


B
Bruce Momjian 已提交
43
/*									ABCDEFGHIJKLMNOPQRSTUVWXYZ */
44
static const char *soundex_table = "01230120022455012623010202";
B
Bruce Momjian 已提交
45

46
#define soundex_code(letter) soundex_table[toupper((unsigned char) (letter)) - 'A']
47

M
Marc G. Fournier 已提交
48

49 50
static void
soundex(const char *instr, char *outstr)
51
{
52
	int			count;
53

54 55 56 57 58 59
	AssertArg(instr);
	AssertArg(outstr);

	outstr[SOUNDEX_LEN] = '\0';

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

63
	/* No string left */
64 65
	if (!instr[0])
	{
66 67
		outstr[0] = (char) 0;
		return;
68 69
	}

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

73 74
	count = 1;
	while (*instr && count < SOUNDEX_LEN)
75
	{
76 77
		if (isalpha((unsigned char) *instr) &&
			soundex_code(*instr) != soundex_code(*(instr - 1)))
78
		{
79
			*outstr = soundex_code(instr[0]);
80 81 82 83 84 85 86 87 88
			if (*outstr != '0')
			{
				++outstr;
				++count;
			}
		}
		++instr;
	}

89 90 91 92 93 94 95 96 97 98 99 100 101
	/* Fill with 0's */
	while (count < SOUNDEX_LEN)
	{
		*outstr = '0';
		++outstr;
		++count;
	}
}



#ifdef SOUNDEX_TEST
int
B
Bruce Momjian 已提交
102
main(int argc, char *argv[])
103 104 105 106 107 108 109 110
{
	if (argc < 2)
	{
		fprintf(stderr, "usage: %s string\n", argv[0]);
		return 1;
	}
	else
	{
B
Bruce Momjian 已提交
111
		char		output[SOUNDEX_LEN + 1];
112 113 114 115 116

		soundex(argv[1], output);
		printf("soundex(%s) = %s\n", argv[1], output);
		return 0;
	}
M
Marc G. Fournier 已提交
117
}
B
Bruce Momjian 已提交
118 119

#endif	 /* SOUNDEX_TEST */