summaryrefslogtreecommitdiff
path: root/app/tools/halibut/charset/sbcs.c
blob: e8be5a85f130320e7051f0f8e2f97cd90a268abf (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
/*
 * sbcs.c - routines to handle single-byte character sets.
 */

#include "charset.h"
#include "internal.h"

/*
 * The charset_spec for any single-byte character set should
 * provide read_sbcs() as its read function, and its `data' field
 * should be a wchar_t string constant containing the 256 entries
 * of the translation table.
 */

long int sbcs_to_unicode(const struct sbcs_data *sd, long int input_chr)
{
    return sd->sbcs2ucs[input_chr];
}

void read_sbcs(charset_spec const *charset, long int input_chr,
	       charset_state *state,
	       void (*emit)(void *ctx, long int output), void *emitctx)
{
    const struct sbcs_data *sd = charset->data;

    UNUSEDARG(state);

    emit(emitctx, sbcs_to_unicode(sd, input_chr));
}

long int sbcs_from_unicode(const struct sbcs_data *sd, long int input_chr)
{
    int i, j, k, c;

    /*
     * Binary-search in the ucs2sbcs table.
     */
    i = -1;
    j = sd->nvalid;
    while (i+1 < j) {
	k = (i+j)/2;
	c = sd->ucs2sbcs[k];
	if (input_chr < (long int)sd->sbcs2ucs[c])
	    j = k;
	else if (input_chr > (long int)sd->sbcs2ucs[c])
	    i = k;
	else {
	    return c;
	}
    }
    return ERROR;
}

int write_sbcs(charset_spec const *charset, long int input_chr,
	       charset_state *state,
	       void (*emit)(void *ctx, long int output), void *emitctx)
{
    const struct sbcs_data *sd = charset->data;
    long int ret;

    UNUSEDARG(state);

    if (input_chr == -1)
	return TRUE;		       /* stateless; no cleanup required */

    ret = sbcs_from_unicode(sd, input_chr);
    if (ret == ERROR)
	return FALSE;

    emit(emitctx, ret);
    return TRUE;
}