~ubuntu-branches/ubuntu/trusty/python3.4/trusty-proposed

« back to all changes in this revision

Viewing changes to Modules/unicodedata.c

  • Committer: Package Import Robot
  • Author(s): Matthias Klose
  • Date: 2013-11-25 09:44:27 UTC
  • Revision ID: package-import@ubuntu.com-20131125094427-lzxj8ap5w01lmo7f
Tags: upstream-3.4~b1
ImportĀ upstreamĀ versionĀ 3.4~b1

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* ------------------------------------------------------------------------
 
2
 
 
3
   unicodedata -- Provides access to the Unicode database.
 
4
 
 
5
   Data was extracted from the UnicodeData.txt file.
 
6
   The current version number is reported in the unidata_version constant.
 
7
 
 
8
   Written by Marc-Andre Lemburg (mal@lemburg.com).
 
9
   Modified for Python 2.0 by Fredrik Lundh (fredrik@pythonware.com)
 
10
   Modified by Martin v. Lƶwis (martin@v.loewis.de)
 
11
 
 
12
   Copyright (c) Corporation for National Research Initiatives.
 
13
 
 
14
   ------------------------------------------------------------------------ */
 
15
 
 
16
#include "Python.h"
 
17
#include "ucnhash.h"
 
18
#include "structmember.h"
 
19
 
 
20
/*[clinic]
 
21
module unicodedata
 
22
class unicodedata.UCD
 
23
[clinic]*/
 
24
/*[clinic checksum: da39a3ee5e6b4b0d3255bfef95601890afd80709]*/
 
25
 
 
26
/* character properties */
 
27
 
 
28
typedef struct {
 
29
    const unsigned char category;       /* index into
 
30
                                           _PyUnicode_CategoryNames */
 
31
    const unsigned char combining;      /* combining class value 0 - 255 */
 
32
    const unsigned char bidirectional;  /* index into
 
33
                                           _PyUnicode_BidirectionalNames */
 
34
    const unsigned char mirrored;       /* true if mirrored in bidir mode */
 
35
    const unsigned char east_asian_width;       /* index into
 
36
                                                   _PyUnicode_EastAsianWidth */
 
37
    const unsigned char normalization_quick_check; /* see is_normalized() */
 
38
} _PyUnicode_DatabaseRecord;
 
39
 
 
40
typedef struct change_record {
 
41
    /* sequence of fields should be the same as in merge_old_version */
 
42
    const unsigned char bidir_changed;
 
43
    const unsigned char category_changed;
 
44
    const unsigned char decimal_changed;
 
45
    const unsigned char mirrored_changed;
 
46
    const double numeric_changed;
 
47
} change_record;
 
48
 
 
49
/* data file generated by Tools/unicode/makeunicodedata.py */
 
50
#include "unicodedata_db.h"
 
51
 
 
52
static const _PyUnicode_DatabaseRecord*
 
53
_getrecord_ex(Py_UCS4 code)
 
54
{
 
55
    int index;
 
56
    if (code >= 0x110000)
 
57
        index = 0;
 
58
    else {
 
59
        index = index1[(code>>SHIFT)];
 
60
        index = index2[(index<<SHIFT)+(code&((1<<SHIFT)-1))];
 
61
    }
 
62
 
 
63
    return &_PyUnicode_Database_Records[index];
 
64
}
 
65
 
 
66
/* ------------- Previous-version API ------------------------------------- */
 
67
typedef struct previous_version {
 
68
    PyObject_HEAD
 
69
    const char *name;
 
70
    const change_record* (*getrecord)(Py_UCS4);
 
71
    Py_UCS4 (*normalization)(Py_UCS4);
 
72
} PreviousDBVersion;
 
73
 
 
74
#define get_old_record(self, v)    ((((PreviousDBVersion*)self)->getrecord)(v))
 
75
 
 
76
static PyMemberDef DB_members[] = {
 
77
        {"unidata_version", T_STRING, offsetof(PreviousDBVersion, name), READONLY},
 
78
        {NULL}
 
79
};
 
80
 
 
81
/* forward declaration */
 
82
static PyTypeObject UCD_Type;
 
83
#define UCD_Check(o) (Py_TYPE(o)==&UCD_Type)
 
84
 
 
85
static PyObject*
 
86
new_previous_version(const char*name, const change_record* (*getrecord)(Py_UCS4),
 
87
                     Py_UCS4 (*normalization)(Py_UCS4))
 
88
{
 
89
        PreviousDBVersion *self;
 
90
        self = PyObject_New(PreviousDBVersion, &UCD_Type);
 
91
        if (self == NULL)
 
92
                return NULL;
 
93
        self->name = name;
 
94
        self->getrecord = getrecord;
 
95
        self->normalization = normalization;
 
96
        return (PyObject*)self;
 
97
}
 
98
 
 
99
 
 
100
static Py_UCS4 getuchar(PyUnicodeObject *obj)
 
101
{
 
102
    if (PyUnicode_READY(obj))
 
103
        return (Py_UCS4)-1;
 
104
    if (PyUnicode_GET_LENGTH(obj) == 1) {
 
105
        if (PyUnicode_READY(obj))
 
106
            return (Py_UCS4)-1;
 
107
        return PyUnicode_READ_CHAR(obj, 0);
 
108
    }
 
109
    PyErr_SetString(PyExc_TypeError,
 
110
                    "need a single Unicode character as parameter");
 
111
    return (Py_UCS4)-1;
 
112
}
 
113
 
 
114
/* --- Module API --------------------------------------------------------- */
 
115
 
 
116
/*[clinic]
 
117
 
 
118
unicodedata.UCD.decimal
 
119
 
 
120
    unichr: object(type='str')
 
121
    default: object=NULL
 
122
    /
 
123
 
 
124
Converts a Unicode character into its equivalent decimal value.
 
125
 
 
126
Returns the decimal value assigned to the Unicode character unichr
 
127
as integer. If no such value is defined, default is returned, or, if
 
128
not given, ValueError is raised.
 
129
[clinic]*/
 
130
 
 
131
PyDoc_STRVAR(unicodedata_UCD_decimal__doc__,
 
132
"decimal(unichr, default=None)\n"
 
133
"Converts a Unicode character into its equivalent decimal value.\n"
 
134
"\n"
 
135
"Returns the decimal value assigned to the Unicode character unichr\n"
 
136
"as integer. If no such value is defined, default is returned, or, if\n"
 
137
"not given, ValueError is raised.");
 
138
 
 
139
#define UNICODEDATA_UCD_DECIMAL_METHODDEF    \
 
140
    {"decimal", (PyCFunction)unicodedata_UCD_decimal, METH_VARARGS, unicodedata_UCD_decimal__doc__},
 
141
 
 
142
static PyObject *
 
143
unicodedata_UCD_decimal_impl(PyObject *self, PyObject *unichr, PyObject *default_value);
 
144
 
 
145
static PyObject *
 
146
unicodedata_UCD_decimal(PyObject *self, PyObject *args)
 
147
{
 
148
    PyObject *return_value = NULL;
 
149
    PyObject *unichr;
 
150
    PyObject *default_value = NULL;
 
151
 
 
152
    if (!PyArg_ParseTuple(args,
 
153
        "O!|O:decimal",
 
154
        &PyUnicode_Type, &unichr, &default_value))
 
155
        goto exit;
 
156
    return_value = unicodedata_UCD_decimal_impl(self, unichr, default_value);
 
157
 
 
158
exit:
 
159
    return return_value;
 
160
}
 
161
 
 
162
static PyObject *
 
163
unicodedata_UCD_decimal_impl(PyObject *self, PyObject *unichr, PyObject *default_value)
 
164
/*[clinic checksum: 9576fa55f4ea0be82968af39dc9d0283e634beeb]*/
 
165
{
 
166
    PyUnicodeObject *v = (PyUnicodeObject *)unichr;
 
167
    int have_old = 0;
 
168
    long rc;
 
169
    Py_UCS4 c;
 
170
 
 
171
    c = getuchar(v);
 
172
    if (c == (Py_UCS4)-1)
 
173
        return NULL;
 
174
 
 
175
    if (self && UCD_Check(self)) {
 
176
        const change_record *old = get_old_record(self, c);
 
177
        if (old->category_changed == 0) {
 
178
            /* unassigned */
 
179
            have_old = 1;
 
180
            rc = -1;
 
181
        }
 
182
        else if (old->decimal_changed != 0xFF) {
 
183
            have_old = 1;
 
184
            rc = old->decimal_changed;
 
185
        }
 
186
    }
 
187
 
 
188
    if (!have_old)
 
189
        rc = Py_UNICODE_TODECIMAL(c);
 
190
    if (rc < 0) {
 
191
        if (default_value == NULL) {
 
192
            PyErr_SetString(PyExc_ValueError,
 
193
                            "not a decimal");
 
194
            return NULL;
 
195
        }
 
196
        else {
 
197
            Py_INCREF(default_value);
 
198
            return default_value;
 
199
        }
 
200
    }
 
201
    return PyLong_FromLong(rc);
 
202
}
 
203
 
 
204
PyDoc_STRVAR(unicodedata_digit__doc__,
 
205
"digit(unichr[, default])\n\
 
206
\n\
 
207
Returns the digit value assigned to the Unicode character unichr as\n\
 
208
integer. If no such value is defined, default is returned, or, if\n\
 
209
not given, ValueError is raised.");
 
210
 
 
211
static PyObject *
 
212
unicodedata_digit(PyObject *self, PyObject *args)
 
213
{
 
214
    PyUnicodeObject *v;
 
215
    PyObject *defobj = NULL;
 
216
    long rc;
 
217
    Py_UCS4 c;
 
218
 
 
219
    if (!PyArg_ParseTuple(args, "O!|O:digit", &PyUnicode_Type, &v, &defobj))
 
220
        return NULL;
 
221
    c = getuchar(v);
 
222
    if (c == (Py_UCS4)-1)
 
223
        return NULL;
 
224
    rc = Py_UNICODE_TODIGIT(c);
 
225
    if (rc < 0) {
 
226
        if (defobj == NULL) {
 
227
            PyErr_SetString(PyExc_ValueError, "not a digit");
 
228
            return NULL;
 
229
        }
 
230
        else {
 
231
            Py_INCREF(defobj);
 
232
            return defobj;
 
233
        }
 
234
    }
 
235
    return PyLong_FromLong(rc);
 
236
}
 
237
 
 
238
PyDoc_STRVAR(unicodedata_numeric__doc__,
 
239
"numeric(unichr[, default])\n\
 
240
\n\
 
241
Returns the numeric value assigned to the Unicode character unichr\n\
 
242
as float. If no such value is defined, default is returned, or, if\n\
 
243
not given, ValueError is raised.");
 
244
 
 
245
static PyObject *
 
246
unicodedata_numeric(PyObject *self, PyObject *args)
 
247
{
 
248
    PyUnicodeObject *v;
 
249
    PyObject *defobj = NULL;
 
250
    int have_old = 0;
 
251
    double rc;
 
252
    Py_UCS4 c;
 
253
 
 
254
    if (!PyArg_ParseTuple(args, "O!|O:numeric", &PyUnicode_Type, &v, &defobj))
 
255
        return NULL;
 
256
    c = getuchar(v);
 
257
    if (c == (Py_UCS4)-1)
 
258
        return NULL;
 
259
 
 
260
    if (self && UCD_Check(self)) {
 
261
        const change_record *old = get_old_record(self, c);
 
262
        if (old->category_changed == 0) {
 
263
            /* unassigned */
 
264
            have_old = 1;
 
265
            rc = -1.0;
 
266
        }
 
267
        else if (old->decimal_changed != 0xFF) {
 
268
            have_old = 1;
 
269
            rc = old->decimal_changed;
 
270
        }
 
271
    }
 
272
 
 
273
    if (!have_old)
 
274
        rc = Py_UNICODE_TONUMERIC(c);
 
275
    if (rc == -1.0) {
 
276
        if (defobj == NULL) {
 
277
            PyErr_SetString(PyExc_ValueError, "not a numeric character");
 
278
            return NULL;
 
279
        }
 
280
        else {
 
281
            Py_INCREF(defobj);
 
282
            return defobj;
 
283
        }
 
284
    }
 
285
    return PyFloat_FromDouble(rc);
 
286
}
 
287
 
 
288
PyDoc_STRVAR(unicodedata_category__doc__,
 
289
"category(unichr)\n\
 
290
\n\
 
291
Returns the general category assigned to the Unicode character\n\
 
292
unichr as string.");
 
293
 
 
294
static PyObject *
 
295
unicodedata_category(PyObject *self, PyObject *args)
 
296
{
 
297
    PyUnicodeObject *v;
 
298
    int index;
 
299
    Py_UCS4 c;
 
300
 
 
301
    if (!PyArg_ParseTuple(args, "O!:category",
 
302
                          &PyUnicode_Type, &v))
 
303
        return NULL;
 
304
    c = getuchar(v);
 
305
    if (c == (Py_UCS4)-1)
 
306
        return NULL;
 
307
    index = (int) _getrecord_ex(c)->category;
 
308
    if (self && UCD_Check(self)) {
 
309
        const change_record *old = get_old_record(self, c);
 
310
        if (old->category_changed != 0xFF)
 
311
            index = old->category_changed;
 
312
    }
 
313
    return PyUnicode_FromString(_PyUnicode_CategoryNames[index]);
 
314
}
 
315
 
 
316
PyDoc_STRVAR(unicodedata_bidirectional__doc__,
 
317
"bidirectional(unichr)\n\
 
318
\n\
 
319
Returns the bidirectional class assigned to the Unicode character\n\
 
320
unichr as string. If no such value is defined, an empty string is\n\
 
321
returned.");
 
322
 
 
323
static PyObject *
 
324
unicodedata_bidirectional(PyObject *self, PyObject *args)
 
325
{
 
326
    PyUnicodeObject *v;
 
327
    int index;
 
328
    Py_UCS4 c;
 
329
 
 
330
    if (!PyArg_ParseTuple(args, "O!:bidirectional",
 
331
                          &PyUnicode_Type, &v))
 
332
        return NULL;
 
333
    c = getuchar(v);
 
334
    if (c == (Py_UCS4)-1)
 
335
        return NULL;
 
336
    index = (int) _getrecord_ex(c)->bidirectional;
 
337
    if (self && UCD_Check(self)) {
 
338
        const change_record *old = get_old_record(self, c);
 
339
        if (old->category_changed == 0)
 
340
            index = 0; /* unassigned */
 
341
        else if (old->bidir_changed != 0xFF)
 
342
            index = old->bidir_changed;
 
343
    }
 
344
    return PyUnicode_FromString(_PyUnicode_BidirectionalNames[index]);
 
345
}
 
346
 
 
347
PyDoc_STRVAR(unicodedata_combining__doc__,
 
348
"combining(unichr)\n\
 
349
\n\
 
350
Returns the canonical combining class assigned to the Unicode\n\
 
351
character unichr as integer. Returns 0 if no combining class is\n\
 
352
defined.");
 
353
 
 
354
static PyObject *
 
355
unicodedata_combining(PyObject *self, PyObject *args)
 
356
{
 
357
    PyUnicodeObject *v;
 
358
    int index;
 
359
    Py_UCS4 c;
 
360
 
 
361
    if (!PyArg_ParseTuple(args, "O!:combining",
 
362
                          &PyUnicode_Type, &v))
 
363
        return NULL;
 
364
    c = getuchar(v);
 
365
    if (c == (Py_UCS4)-1)
 
366
        return NULL;
 
367
    index = (int) _getrecord_ex(c)->combining;
 
368
    if (self && UCD_Check(self)) {
 
369
        const change_record *old = get_old_record(self, c);
 
370
        if (old->category_changed == 0)
 
371
            index = 0; /* unassigned */
 
372
    }
 
373
    return PyLong_FromLong(index);
 
374
}
 
375
 
 
376
PyDoc_STRVAR(unicodedata_mirrored__doc__,
 
377
"mirrored(unichr)\n\
 
378
\n\
 
379
Returns the mirrored property assigned to the Unicode character\n\
 
380
unichr as integer. Returns 1 if the character has been identified as\n\
 
381
a \"mirrored\" character in bidirectional text, 0 otherwise.");
 
382
 
 
383
static PyObject *
 
384
unicodedata_mirrored(PyObject *self, PyObject *args)
 
385
{
 
386
    PyUnicodeObject *v;
 
387
    int index;
 
388
    Py_UCS4 c;
 
389
 
 
390
    if (!PyArg_ParseTuple(args, "O!:mirrored",
 
391
                          &PyUnicode_Type, &v))
 
392
        return NULL;
 
393
    c = getuchar(v);
 
394
    if (c == (Py_UCS4)-1)
 
395
        return NULL;
 
396
    index = (int) _getrecord_ex(c)->mirrored;
 
397
    if (self && UCD_Check(self)) {
 
398
        const change_record *old = get_old_record(self, c);
 
399
        if (old->category_changed == 0)
 
400
            index = 0; /* unassigned */
 
401
        else if (old->mirrored_changed != 0xFF)
 
402
            index = old->mirrored_changed;
 
403
    }
 
404
    return PyLong_FromLong(index);
 
405
}
 
406
 
 
407
PyDoc_STRVAR(unicodedata_east_asian_width__doc__,
 
408
"east_asian_width(unichr)\n\
 
409
\n\
 
410
Returns the east asian width assigned to the Unicode character\n\
 
411
unichr as string.");
 
412
 
 
413
static PyObject *
 
414
unicodedata_east_asian_width(PyObject *self, PyObject *args)
 
415
{
 
416
    PyUnicodeObject *v;
 
417
    int index;
 
418
    Py_UCS4 c;
 
419
 
 
420
    if (!PyArg_ParseTuple(args, "O!:east_asian_width",
 
421
                          &PyUnicode_Type, &v))
 
422
        return NULL;
 
423
    c = getuchar(v);
 
424
    if (c == (Py_UCS4)-1)
 
425
        return NULL;
 
426
    index = (int) _getrecord_ex(c)->east_asian_width;
 
427
    if (self && UCD_Check(self)) {
 
428
        const change_record *old = get_old_record(self, c);
 
429
        if (old->category_changed == 0)
 
430
            index = 0; /* unassigned */
 
431
    }
 
432
    return PyUnicode_FromString(_PyUnicode_EastAsianWidthNames[index]);
 
433
}
 
434
 
 
435
PyDoc_STRVAR(unicodedata_decomposition__doc__,
 
436
"decomposition(unichr)\n\
 
437
\n\
 
438
Returns the character decomposition mapping assigned to the Unicode\n\
 
439
character unichr as string. An empty string is returned in case no\n\
 
440
such mapping is defined.");
 
441
 
 
442
static PyObject *
 
443
unicodedata_decomposition(PyObject *self, PyObject *args)
 
444
{
 
445
    PyUnicodeObject *v;
 
446
    char decomp[256];
 
447
    int code, index, count;
 
448
    size_t i;
 
449
    unsigned int prefix_index;
 
450
    Py_UCS4 c;
 
451
 
 
452
    if (!PyArg_ParseTuple(args, "O!:decomposition",
 
453
                          &PyUnicode_Type, &v))
 
454
        return NULL;
 
455
    c = getuchar(v);
 
456
    if (c == (Py_UCS4)-1)
 
457
        return NULL;
 
458
 
 
459
    code = (int)c;
 
460
 
 
461
    if (self && UCD_Check(self)) {
 
462
        const change_record *old = get_old_record(self, c);
 
463
        if (old->category_changed == 0)
 
464
            return PyUnicode_FromString(""); /* unassigned */
 
465
    }
 
466
 
 
467
    if (code < 0 || code >= 0x110000)
 
468
        index = 0;
 
469
    else {
 
470
        index = decomp_index1[(code>>DECOMP_SHIFT)];
 
471
        index = decomp_index2[(index<<DECOMP_SHIFT)+
 
472
                             (code&((1<<DECOMP_SHIFT)-1))];
 
473
    }
 
474
 
 
475
    /* high byte is number of hex bytes (usually one or two), low byte
 
476
       is prefix code (from*/
 
477
    count = decomp_data[index] >> 8;
 
478
 
 
479
    /* XXX: could allocate the PyString up front instead
 
480
       (strlen(prefix) + 5 * count + 1 bytes) */
 
481
 
 
482
    /* Based on how index is calculated above and decomp_data is generated
 
483
       from Tools/unicode/makeunicodedata.py, it should not be possible
 
484
       to overflow decomp_prefix. */
 
485
    prefix_index = decomp_data[index] & 255;
 
486
    assert(prefix_index < Py_ARRAY_LENGTH(decomp_prefix));
 
487
 
 
488
    /* copy prefix */
 
489
    i = strlen(decomp_prefix[prefix_index]);
 
490
    memcpy(decomp, decomp_prefix[prefix_index], i);
 
491
 
 
492
    while (count-- > 0) {
 
493
        if (i)
 
494
            decomp[i++] = ' ';
 
495
        assert(i < sizeof(decomp));
 
496
        PyOS_snprintf(decomp + i, sizeof(decomp) - i, "%04X",
 
497
                      decomp_data[++index]);
 
498
        i += strlen(decomp + i);
 
499
    }
 
500
    return PyUnicode_FromStringAndSize(decomp, i);
 
501
}
 
502
 
 
503
static void
 
504
get_decomp_record(PyObject *self, Py_UCS4 code, int *index, int *prefix, int *count)
 
505
{
 
506
    if (code >= 0x110000) {
 
507
        *index = 0;
 
508
    } else if (self && UCD_Check(self) &&
 
509
               get_old_record(self, code)->category_changed==0) {
 
510
        /* unassigned in old version */
 
511
        *index = 0;
 
512
    }
 
513
    else {
 
514
        *index = decomp_index1[(code>>DECOMP_SHIFT)];
 
515
        *index = decomp_index2[(*index<<DECOMP_SHIFT)+
 
516
                               (code&((1<<DECOMP_SHIFT)-1))];
 
517
    }
 
518
 
 
519
    /* high byte is number of hex bytes (usually one or two), low byte
 
520
       is prefix code (from*/
 
521
    *count = decomp_data[*index] >> 8;
 
522
    *prefix = decomp_data[*index] & 255;
 
523
 
 
524
    (*index)++;
 
525
}
 
526
 
 
527
#define SBase   0xAC00
 
528
#define LBase   0x1100
 
529
#define VBase   0x1161
 
530
#define TBase   0x11A7
 
531
#define LCount  19
 
532
#define VCount  21
 
533
#define TCount  28
 
534
#define NCount  (VCount*TCount)
 
535
#define SCount  (LCount*NCount)
 
536
 
 
537
static PyObject*
 
538
nfd_nfkd(PyObject *self, PyObject *input, int k)
 
539
{
 
540
    PyObject *result;
 
541
    Py_UCS4 *output;
 
542
    Py_ssize_t i, o, osize;
 
543
    int kind;
 
544
    void *data;
 
545
    /* Longest decomposition in Unicode 3.2: U+FDFA */
 
546
    Py_UCS4 stack[20];
 
547
    Py_ssize_t space, isize;
 
548
    int index, prefix, count, stackptr;
 
549
    unsigned char prev, cur;
 
550
 
 
551
    stackptr = 0;
 
552
    isize = PyUnicode_GET_LENGTH(input);
 
553
    /* Overallocate at most 10 characters. */
 
554
    space = (isize > 10 ? 10 : isize) + isize;
 
555
    osize = space;
 
556
    output = PyMem_Malloc(space * sizeof(Py_UCS4));
 
557
    if (!output) {
 
558
        PyErr_NoMemory();
 
559
        return NULL;
 
560
    }
 
561
    i = o = 0;
 
562
    kind = PyUnicode_KIND(input);
 
563
    data = PyUnicode_DATA(input);
 
564
 
 
565
    while (i < isize) {
 
566
        stack[stackptr++] = PyUnicode_READ(kind, data, i++);
 
567
        while(stackptr) {
 
568
            Py_UCS4 code = stack[--stackptr];
 
569
            /* Hangul Decomposition adds three characters in
 
570
               a single step, so we need at least that much room. */
 
571
            if (space < 3) {
 
572
                Py_UCS4 *new_output;
 
573
                osize += 10;
 
574
                space += 10;
 
575
                new_output = PyMem_Realloc(output, osize*sizeof(Py_UCS4));
 
576
                if (new_output == NULL) {
 
577
                    PyMem_Free(output);
 
578
                    PyErr_NoMemory();
 
579
                    return NULL;
 
580
                }
 
581
                output = new_output;
 
582
            }
 
583
            /* Hangul Decomposition. */
 
584
            if (SBase <= code && code < (SBase+SCount)) {
 
585
                int SIndex = code - SBase;
 
586
                int L = LBase + SIndex / NCount;
 
587
                int V = VBase + (SIndex % NCount) / TCount;
 
588
                int T = TBase + SIndex % TCount;
 
589
                output[o++] = L;
 
590
                output[o++] = V;
 
591
                space -= 2;
 
592
                if (T != TBase) {
 
593
                    output[o++] = T;
 
594
                    space --;
 
595
                }
 
596
                continue;
 
597
            }
 
598
            /* normalization changes */
 
599
            if (self && UCD_Check(self)) {
 
600
                Py_UCS4 value = ((PreviousDBVersion*)self)->normalization(code);
 
601
                if (value != 0) {
 
602
                    stack[stackptr++] = value;
 
603
                    continue;
 
604
                }
 
605
            }
 
606
 
 
607
            /* Other decompositions. */
 
608
            get_decomp_record(self, code, &index, &prefix, &count);
 
609
 
 
610
            /* Copy character if it is not decomposable, or has a
 
611
               compatibility decomposition, but we do NFD. */
 
612
            if (!count || (prefix && !k)) {
 
613
                output[o++] = code;
 
614
                space--;
 
615
                continue;
 
616
            }
 
617
            /* Copy decomposition onto the stack, in reverse
 
618
               order.  */
 
619
            while(count) {
 
620
                code = decomp_data[index + (--count)];
 
621
                stack[stackptr++] = code;
 
622
            }
 
623
        }
 
624
    }
 
625
 
 
626
    result = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
 
627
                                       output, o);
 
628
    PyMem_Free(output);
 
629
    if (!result)
 
630
        return NULL;
 
631
    /* result is guaranteed to be ready, as it is compact. */
 
632
    kind = PyUnicode_KIND(result);
 
633
    data = PyUnicode_DATA(result);
 
634
 
 
635
    /* Sort canonically. */
 
636
    i = 0;
 
637
    prev = _getrecord_ex(PyUnicode_READ(kind, data, i))->combining;
 
638
    for (i++; i < PyUnicode_GET_LENGTH(result); i++) {
 
639
        cur = _getrecord_ex(PyUnicode_READ(kind, data, i))->combining;
 
640
        if (prev == 0 || cur == 0 || prev <= cur) {
 
641
            prev = cur;
 
642
            continue;
 
643
        }
 
644
        /* Non-canonical order. Need to switch *i with previous. */
 
645
        o = i - 1;
 
646
        while (1) {
 
647
            Py_UCS4 tmp = PyUnicode_READ(kind, data, o+1);
 
648
            PyUnicode_WRITE(kind, data, o+1,
 
649
                            PyUnicode_READ(kind, data, o));
 
650
            PyUnicode_WRITE(kind, data, o, tmp);
 
651
            o--;
 
652
            if (o < 0)
 
653
                break;
 
654
            prev = _getrecord_ex(PyUnicode_READ(kind, data, o))->combining;
 
655
            if (prev == 0 || prev <= cur)
 
656
                break;
 
657
        }
 
658
        prev = _getrecord_ex(PyUnicode_READ(kind, data, i))->combining;
 
659
    }
 
660
    return result;
 
661
}
 
662
 
 
663
static int
 
664
find_nfc_index(PyObject *self, struct reindex* nfc, Py_UCS4 code)
 
665
{
 
666
    unsigned int index;
 
667
    for (index = 0; nfc[index].start; index++) {
 
668
        unsigned int start = nfc[index].start;
 
669
        if (code < start)
 
670
            return -1;
 
671
        if (code <= start + nfc[index].count) {
 
672
            unsigned int delta = code - start;
 
673
            return nfc[index].index + delta;
 
674
        }
 
675
    }
 
676
    return -1;
 
677
}
 
678
 
 
679
static PyObject*
 
680
nfc_nfkc(PyObject *self, PyObject *input, int k)
 
681
{
 
682
    PyObject *result;
 
683
    int kind;
 
684
    void *data;
 
685
    Py_UCS4 *output;
 
686
    Py_ssize_t i, i1, o, len;
 
687
    int f,l,index,index1,comb;
 
688
    Py_UCS4 code;
 
689
    Py_ssize_t skipped[20];
 
690
    int cskipped = 0;
 
691
 
 
692
    result = nfd_nfkd(self, input, k);
 
693
    if (!result)
 
694
        return NULL;
 
695
    /* result will be "ready". */
 
696
    kind = PyUnicode_KIND(result);
 
697
    data = PyUnicode_DATA(result);
 
698
    len = PyUnicode_GET_LENGTH(result);
 
699
 
 
700
    /* We allocate a buffer for the output.
 
701
       If we find that we made no changes, we still return
 
702
       the NFD result. */
 
703
    output = PyMem_Malloc(len * sizeof(Py_UCS4));
 
704
    if (!output) {
 
705
        PyErr_NoMemory();
 
706
        Py_DECREF(result);
 
707
        return 0;
 
708
    }
 
709
    i = o = 0;
 
710
 
 
711
  again:
 
712
    while (i < len) {
 
713
      for (index = 0; index < cskipped; index++) {
 
714
          if (skipped[index] == i) {
 
715
              /* *i character is skipped.
 
716
                 Remove from list. */
 
717
              skipped[index] = skipped[cskipped-1];
 
718
              cskipped--;
 
719
              i++;
 
720
              goto again; /* continue while */
 
721
          }
 
722
      }
 
723
      /* Hangul Composition. We don't need to check for <LV,T>
 
724
         pairs, since we always have decomposed data. */
 
725
      code = PyUnicode_READ(kind, data, i);
 
726
      if (LBase <= code && code < (LBase+LCount) &&
 
727
          i + 1 < len &&
 
728
          VBase <= PyUnicode_READ(kind, data, i+1) &&
 
729
          PyUnicode_READ(kind, data, i+1) <= (VBase+VCount)) {
 
730
          int LIndex, VIndex;
 
731
          LIndex = code - LBase;
 
732
          VIndex = PyUnicode_READ(kind, data, i+1) - VBase;
 
733
          code = SBase + (LIndex*VCount+VIndex)*TCount;
 
734
          i+=2;
 
735
          if (i < len &&
 
736
              TBase <= PyUnicode_READ(kind, data, i) &&
 
737
              PyUnicode_READ(kind, data, i) <= (TBase+TCount)) {
 
738
              code += PyUnicode_READ(kind, data, i)-TBase;
 
739
              i++;
 
740
          }
 
741
          output[o++] = code;
 
742
          continue;
 
743
      }
 
744
 
 
745
      /* code is still input[i] here */
 
746
      f = find_nfc_index(self, nfc_first, code);
 
747
      if (f == -1) {
 
748
          output[o++] = code;
 
749
          i++;
 
750
          continue;
 
751
      }
 
752
      /* Find next unblocked character. */
 
753
      i1 = i+1;
 
754
      comb = 0;
 
755
      /* output base character for now; might be updated later. */
 
756
      output[o] = PyUnicode_READ(kind, data, i);
 
757
      while (i1 < len) {
 
758
          Py_UCS4 code1 = PyUnicode_READ(kind, data, i1);
 
759
          int comb1 = _getrecord_ex(code1)->combining;
 
760
          if (comb) {
 
761
              if (comb1 == 0)
 
762
                  break;
 
763
              if (comb >= comb1) {
 
764
                  /* Character is blocked. */
 
765
                  i1++;
 
766
                  continue;
 
767
              }
 
768
          }
 
769
          l = find_nfc_index(self, nfc_last, code1);
 
770
          /* i1 cannot be combined with i. If i1
 
771
             is a starter, we don't need to look further.
 
772
             Otherwise, record the combining class. */
 
773
          if (l == -1) {
 
774
            not_combinable:
 
775
              if (comb1 == 0)
 
776
                  break;
 
777
              comb = comb1;
 
778
              i1++;
 
779
              continue;
 
780
          }
 
781
          index = f*TOTAL_LAST + l;
 
782
          index1 = comp_index[index >> COMP_SHIFT];
 
783
          code = comp_data[(index1<<COMP_SHIFT)+
 
784
                           (index&((1<<COMP_SHIFT)-1))];
 
785
          if (code == 0)
 
786
              goto not_combinable;
 
787
 
 
788
          /* Replace the original character. */
 
789
          output[o] = code;
 
790
          /* Mark the second character unused. */
 
791
          assert(cskipped < 20);
 
792
          skipped[cskipped++] = i1;
 
793
          i1++;
 
794
          f = find_nfc_index(self, nfc_first, output[o]);
 
795
          if (f == -1)
 
796
              break;
 
797
      }
 
798
      /* Output character was already written.
 
799
         Just advance the indices. */
 
800
      o++; i++;
 
801
    }
 
802
    if (o == len) {
 
803
        /* No changes. Return original string. */
 
804
        PyMem_Free(output);
 
805
        return result;
 
806
    }
 
807
    Py_DECREF(result);
 
808
    result = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
 
809
                                       output, o);
 
810
    PyMem_Free(output);
 
811
    return result;
 
812
}
 
813
 
 
814
/* Return 1 if the input is certainly normalized, 0 if it might not be. */
 
815
static int
 
816
is_normalized(PyObject *self, PyObject *input, int nfc, int k)
 
817
{
 
818
    Py_ssize_t i, len;
 
819
    int kind;
 
820
    void *data;
 
821
    unsigned char prev_combining = 0, quickcheck_mask;
 
822
 
 
823
    /* An older version of the database is requested, quickchecks must be
 
824
       disabled. */
 
825
    if (self && UCD_Check(self))
 
826
        return 0;
 
827
 
 
828
    /* The two quickcheck bits at this shift mean 0=Yes, 1=Maybe, 2=No,
 
829
       as described in http://unicode.org/reports/tr15/#Annex8. */
 
830
    quickcheck_mask = 3 << ((nfc ? 4 : 0) + (k ? 2 : 0));
 
831
 
 
832
    i = 0;
 
833
    kind = PyUnicode_KIND(input);
 
834
    data = PyUnicode_DATA(input);
 
835
    len = PyUnicode_GET_LENGTH(input);
 
836
    while (i < len) {
 
837
        Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
 
838
        const _PyUnicode_DatabaseRecord *record = _getrecord_ex(ch);
 
839
        unsigned char combining = record->combining;
 
840
        unsigned char quickcheck = record->normalization_quick_check;
 
841
 
 
842
        if (quickcheck & quickcheck_mask)
 
843
            return 0; /* this string might need normalization */
 
844
        if (combining && prev_combining > combining)
 
845
            return 0; /* non-canonical sort order, not normalized */
 
846
        prev_combining = combining;
 
847
    }
 
848
    return 1; /* certainly normalized */
 
849
}
 
850
 
 
851
PyDoc_STRVAR(unicodedata_normalize__doc__,
 
852
"normalize(form, unistr)\n\
 
853
\n\
 
854
Return the normal form 'form' for the Unicode string unistr.  Valid\n\
 
855
values for form are 'NFC', 'NFKC', 'NFD', and 'NFKD'.");
 
856
 
 
857
static PyObject*
 
858
unicodedata_normalize(PyObject *self, PyObject *args)
 
859
{
 
860
    char *form;
 
861
    PyObject *input;
 
862
 
 
863
    if(!PyArg_ParseTuple(args, "sO!:normalize",
 
864
                         &form, &PyUnicode_Type, &input))
 
865
        return NULL;
 
866
 
 
867
    if (PyUnicode_READY(input) == -1)
 
868
        return NULL;
 
869
 
 
870
    if (PyUnicode_GET_LENGTH(input) == 0) {
 
871
        /* Special case empty input strings, since resizing
 
872
           them  later would cause internal errors. */
 
873
        Py_INCREF(input);
 
874
        return input;
 
875
    }
 
876
 
 
877
    if (strcmp(form, "NFC") == 0) {
 
878
        if (is_normalized(self, input, 1, 0)) {
 
879
            Py_INCREF(input);
 
880
            return input;
 
881
        }
 
882
        return nfc_nfkc(self, input, 0);
 
883
    }
 
884
    if (strcmp(form, "NFKC") == 0) {
 
885
        if (is_normalized(self, input, 1, 1)) {
 
886
            Py_INCREF(input);
 
887
            return input;
 
888
        }
 
889
        return nfc_nfkc(self, input, 1);
 
890
    }
 
891
    if (strcmp(form, "NFD") == 0) {
 
892
        if (is_normalized(self, input, 0, 0)) {
 
893
            Py_INCREF(input);
 
894
            return input;
 
895
        }
 
896
        return nfd_nfkd(self, input, 0);
 
897
    }
 
898
    if (strcmp(form, "NFKD") == 0) {
 
899
        if (is_normalized(self, input, 0, 1)) {
 
900
            Py_INCREF(input);
 
901
            return input;
 
902
        }
 
903
        return nfd_nfkd(self, input, 1);
 
904
    }
 
905
    PyErr_SetString(PyExc_ValueError, "invalid normalization form");
 
906
    return NULL;
 
907
}
 
908
 
 
909
/* -------------------------------------------------------------------- */
 
910
/* unicode character name tables */
 
911
 
 
912
/* data file generated by Tools/unicode/makeunicodedata.py */
 
913
#include "unicodename_db.h"
 
914
 
 
915
/* -------------------------------------------------------------------- */
 
916
/* database code (cut and pasted from the unidb package) */
 
917
 
 
918
static unsigned long
 
919
_gethash(const char *s, int len, int scale)
 
920
{
 
921
    int i;
 
922
    unsigned long h = 0;
 
923
    unsigned long ix;
 
924
    for (i = 0; i < len; i++) {
 
925
        h = (h * scale) + (unsigned char) Py_TOUPPER(Py_CHARMASK(s[i]));
 
926
        ix = h & 0xff000000;
 
927
        if (ix)
 
928
            h = (h ^ ((ix>>24) & 0xff)) & 0x00ffffff;
 
929
    }
 
930
    return h;
 
931
}
 
932
 
 
933
static char *hangul_syllables[][3] = {
 
934
    { "G",  "A",   ""   },
 
935
    { "GG", "AE",  "G"  },
 
936
    { "N",  "YA",  "GG" },
 
937
    { "D",  "YAE", "GS" },
 
938
    { "DD", "EO",  "N", },
 
939
    { "R",  "E",   "NJ" },
 
940
    { "M",  "YEO", "NH" },
 
941
    { "B",  "YE",  "D"  },
 
942
    { "BB", "O",   "L"  },
 
943
    { "S",  "WA",  "LG" },
 
944
    { "SS", "WAE", "LM" },
 
945
    { "",   "OE",  "LB" },
 
946
    { "J",  "YO",  "LS" },
 
947
    { "JJ", "U",   "LT" },
 
948
    { "C",  "WEO", "LP" },
 
949
    { "K",  "WE",  "LH" },
 
950
    { "T",  "WI",  "M"  },
 
951
    { "P",  "YU",  "B"  },
 
952
    { "H",  "EU",  "BS" },
 
953
    { 0,    "YI",  "S"  },
 
954
    { 0,    "I",   "SS" },
 
955
    { 0,    0,     "NG" },
 
956
    { 0,    0,     "J"  },
 
957
    { 0,    0,     "C"  },
 
958
    { 0,    0,     "K"  },
 
959
    { 0,    0,     "T"  },
 
960
    { 0,    0,     "P"  },
 
961
    { 0,    0,     "H"  }
 
962
};
 
963
 
 
964
/* These ranges need to match makeunicodedata.py:cjk_ranges. */
 
965
static int
 
966
is_unified_ideograph(Py_UCS4 code)
 
967
{
 
968
    return
 
969
        (0x3400 <= code && code <= 0x4DB5)   || /* CJK Ideograph Extension A */
 
970
        (0x4E00 <= code && code <= 0x9FCC)   || /* CJK Ideograph */
 
971
        (0x20000 <= code && code <= 0x2A6D6) || /* CJK Ideograph Extension B */
 
972
        (0x2A700 <= code && code <= 0x2B734) || /* CJK Ideograph Extension C */
 
973
        (0x2B740 <= code && code <= 0x2B81D);   /* CJK Ideograph Extension D */
 
974
}
 
975
 
 
976
/* macros used to determine if the given codepoint is in the PUA range that
 
977
 * we are using to store aliases and named sequences */
 
978
#define IS_ALIAS(cp) ((cp >= aliases_start) && (cp < aliases_end))
 
979
#define IS_NAMED_SEQ(cp) ((cp >= named_sequences_start) && \
 
980
                          (cp < named_sequences_end))
 
981
 
 
982
static int
 
983
_getucname(PyObject *self, Py_UCS4 code, char* buffer, int buflen,
 
984
           int with_alias_and_seq)
 
985
{
 
986
    /* Find the name associated with the given codepoint.
 
987
     * If with_alias_and_seq is 1, check for names in the Private Use Area 15
 
988
     * that we are using for aliases and named sequences. */
 
989
    int offset;
 
990
    int i;
 
991
    int word;
 
992
    unsigned char* w;
 
993
 
 
994
    if (code >= 0x110000)
 
995
        return 0;
 
996
 
 
997
    /* XXX should we just skip all the codepoints in the PUAs here? */
 
998
    if (!with_alias_and_seq && (IS_ALIAS(code) || IS_NAMED_SEQ(code)))
 
999
        return 0;
 
1000
 
 
1001
    if (self && UCD_Check(self)) {
 
1002
        /* in 3.2.0 there are no aliases and named sequences */
 
1003
        const change_record *old;
 
1004
        if (IS_ALIAS(code) || IS_NAMED_SEQ(code))
 
1005
            return 0;
 
1006
        old = get_old_record(self, code);
 
1007
        if (old->category_changed == 0) {
 
1008
            /* unassigned */
 
1009
            return 0;
 
1010
        }
 
1011
    }
 
1012
 
 
1013
    if (SBase <= code && code < SBase+SCount) {
 
1014
        /* Hangul syllable. */
 
1015
        int SIndex = code - SBase;
 
1016
        int L = SIndex / NCount;
 
1017
        int V = (SIndex % NCount) / TCount;
 
1018
        int T = SIndex % TCount;
 
1019
 
 
1020
        if (buflen < 27)
 
1021
            /* Worst case: HANGUL SYLLABLE <10chars>. */
 
1022
            return 0;
 
1023
        strcpy(buffer, "HANGUL SYLLABLE ");
 
1024
        buffer += 16;
 
1025
        strcpy(buffer, hangul_syllables[L][0]);
 
1026
        buffer += strlen(hangul_syllables[L][0]);
 
1027
        strcpy(buffer, hangul_syllables[V][1]);
 
1028
        buffer += strlen(hangul_syllables[V][1]);
 
1029
        strcpy(buffer, hangul_syllables[T][2]);
 
1030
        buffer += strlen(hangul_syllables[T][2]);
 
1031
        *buffer = '\0';
 
1032
        return 1;
 
1033
    }
 
1034
 
 
1035
    if (is_unified_ideograph(code)) {
 
1036
        if (buflen < 28)
 
1037
            /* Worst case: CJK UNIFIED IDEOGRAPH-20000 */
 
1038
            return 0;
 
1039
        sprintf(buffer, "CJK UNIFIED IDEOGRAPH-%X", code);
 
1040
        return 1;
 
1041
    }
 
1042
 
 
1043
    /* get offset into phrasebook */
 
1044
    offset = phrasebook_offset1[(code>>phrasebook_shift)];
 
1045
    offset = phrasebook_offset2[(offset<<phrasebook_shift) +
 
1046
                               (code&((1<<phrasebook_shift)-1))];
 
1047
    if (!offset)
 
1048
        return 0;
 
1049
 
 
1050
    i = 0;
 
1051
 
 
1052
    for (;;) {
 
1053
        /* get word index */
 
1054
        word = phrasebook[offset] - phrasebook_short;
 
1055
        if (word >= 0) {
 
1056
            word = (word << 8) + phrasebook[offset+1];
 
1057
            offset += 2;
 
1058
        } else
 
1059
            word = phrasebook[offset++];
 
1060
        if (i) {
 
1061
            if (i > buflen)
 
1062
                return 0; /* buffer overflow */
 
1063
            buffer[i++] = ' ';
 
1064
        }
 
1065
        /* copy word string from lexicon.  the last character in the
 
1066
           word has bit 7 set.  the last word in a string ends with
 
1067
           0x80 */
 
1068
        w = lexicon + lexicon_offset[word];
 
1069
        while (*w < 128) {
 
1070
            if (i >= buflen)
 
1071
                return 0; /* buffer overflow */
 
1072
            buffer[i++] = *w++;
 
1073
        }
 
1074
        if (i >= buflen)
 
1075
            return 0; /* buffer overflow */
 
1076
        buffer[i++] = *w & 127;
 
1077
        if (*w == 128)
 
1078
            break; /* end of word */
 
1079
    }
 
1080
 
 
1081
    return 1;
 
1082
}
 
1083
 
 
1084
static int
 
1085
_cmpname(PyObject *self, int code, const char* name, int namelen)
 
1086
{
 
1087
    /* check if code corresponds to the given name */
 
1088
    int i;
 
1089
    char buffer[NAME_MAXLEN];
 
1090
    if (!_getucname(self, code, buffer, sizeof(buffer), 1))
 
1091
        return 0;
 
1092
    for (i = 0; i < namelen; i++) {
 
1093
        if (Py_TOUPPER(Py_CHARMASK(name[i])) != buffer[i])
 
1094
            return 0;
 
1095
    }
 
1096
    return buffer[namelen] == '\0';
 
1097
}
 
1098
 
 
1099
static void
 
1100
find_syllable(const char *str, int *len, int *pos, int count, int column)
 
1101
{
 
1102
    int i, len1;
 
1103
    *len = -1;
 
1104
    for (i = 0; i < count; i++) {
 
1105
        char *s = hangul_syllables[i][column];
 
1106
        len1 = Py_SAFE_DOWNCAST(strlen(s), size_t, int);
 
1107
        if (len1 <= *len)
 
1108
            continue;
 
1109
        if (strncmp(str, s, len1) == 0) {
 
1110
            *len = len1;
 
1111
            *pos = i;
 
1112
        }
 
1113
    }
 
1114
    if (*len == -1) {
 
1115
        *len = 0;
 
1116
    }
 
1117
}
 
1118
 
 
1119
static int
 
1120
_check_alias_and_seq(unsigned int cp, Py_UCS4* code, int with_named_seq)
 
1121
{
 
1122
    /* check if named sequences are allowed */
 
1123
    if (!with_named_seq && IS_NAMED_SEQ(cp))
 
1124
        return 0;
 
1125
    /* if the codepoint is in the PUA range that we use for aliases,
 
1126
     * convert it to obtain the right codepoint */
 
1127
    if (IS_ALIAS(cp))
 
1128
        *code = name_aliases[cp-aliases_start];
 
1129
    else
 
1130
        *code = cp;
 
1131
    return 1;
 
1132
}
 
1133
 
 
1134
static int
 
1135
_getcode(PyObject* self, const char* name, int namelen, Py_UCS4* code,
 
1136
         int with_named_seq)
 
1137
{
 
1138
    /* Return the codepoint associated with the given name.
 
1139
     * Named aliases are resolved too (unless self != NULL (i.e. we are using
 
1140
     * 3.2.0)).  If with_named_seq is 1, returns the PUA codepoint that we are
 
1141
     * using for the named sequence, and the caller must then convert it. */
 
1142
    unsigned int h, v;
 
1143
    unsigned int mask = code_size-1;
 
1144
    unsigned int i, incr;
 
1145
 
 
1146
    /* Check for hangul syllables. */
 
1147
    if (strncmp(name, "HANGUL SYLLABLE ", 16) == 0) {
 
1148
        int len, L = -1, V = -1, T = -1;
 
1149
        const char *pos = name + 16;
 
1150
        find_syllable(pos, &len, &L, LCount, 0);
 
1151
        pos += len;
 
1152
        find_syllable(pos, &len, &V, VCount, 1);
 
1153
        pos += len;
 
1154
        find_syllable(pos, &len, &T, TCount, 2);
 
1155
        pos += len;
 
1156
        if (L != -1 && V != -1 && T != -1 && pos-name == namelen) {
 
1157
            *code = SBase + (L*VCount+V)*TCount + T;
 
1158
            return 1;
 
1159
        }
 
1160
        /* Otherwise, it's an illegal syllable name. */
 
1161
        return 0;
 
1162
    }
 
1163
 
 
1164
    /* Check for unified ideographs. */
 
1165
    if (strncmp(name, "CJK UNIFIED IDEOGRAPH-", 22) == 0) {
 
1166
        /* Four or five hexdigits must follow. */
 
1167
        v = 0;
 
1168
        name += 22;
 
1169
        namelen -= 22;
 
1170
        if (namelen != 4 && namelen != 5)
 
1171
            return 0;
 
1172
        while (namelen--) {
 
1173
            v *= 16;
 
1174
            if (*name >= '0' && *name <= '9')
 
1175
                v += *name - '0';
 
1176
            else if (*name >= 'A' && *name <= 'F')
 
1177
                v += *name - 'A' + 10;
 
1178
            else
 
1179
                return 0;
 
1180
            name++;
 
1181
        }
 
1182
        if (!is_unified_ideograph(v))
 
1183
            return 0;
 
1184
        *code = v;
 
1185
        return 1;
 
1186
    }
 
1187
 
 
1188
    /* the following is the same as python's dictionary lookup, with
 
1189
       only minor changes.  see the makeunicodedata script for more
 
1190
       details */
 
1191
 
 
1192
    h = (unsigned int) _gethash(name, namelen, code_magic);
 
1193
    i = (~h) & mask;
 
1194
    v = code_hash[i];
 
1195
    if (!v)
 
1196
        return 0;
 
1197
    if (_cmpname(self, v, name, namelen))
 
1198
        return _check_alias_and_seq(v, code, with_named_seq);
 
1199
    incr = (h ^ (h >> 3)) & mask;
 
1200
    if (!incr)
 
1201
        incr = mask;
 
1202
    for (;;) {
 
1203
        i = (i + incr) & mask;
 
1204
        v = code_hash[i];
 
1205
        if (!v)
 
1206
            return 0;
 
1207
        if (_cmpname(self, v, name, namelen))
 
1208
            return _check_alias_and_seq(v, code, with_named_seq);
 
1209
        incr = incr << 1;
 
1210
        if (incr > mask)
 
1211
            incr = incr ^ code_poly;
 
1212
    }
 
1213
}
 
1214
 
 
1215
static const _PyUnicode_Name_CAPI hashAPI =
 
1216
{
 
1217
    sizeof(_PyUnicode_Name_CAPI),
 
1218
    _getucname,
 
1219
    _getcode
 
1220
};
 
1221
 
 
1222
/* -------------------------------------------------------------------- */
 
1223
/* Python bindings */
 
1224
 
 
1225
PyDoc_STRVAR(unicodedata_name__doc__,
 
1226
"name(unichr[, default])\n\
 
1227
Returns the name assigned to the Unicode character unichr as a\n\
 
1228
string. If no name is defined, default is returned, or, if not\n\
 
1229
given, ValueError is raised.");
 
1230
 
 
1231
static PyObject *
 
1232
unicodedata_name(PyObject* self, PyObject* args)
 
1233
{
 
1234
    char name[NAME_MAXLEN];
 
1235
    Py_UCS4 c;
 
1236
 
 
1237
    PyUnicodeObject* v;
 
1238
    PyObject* defobj = NULL;
 
1239
    if (!PyArg_ParseTuple(args, "O!|O:name", &PyUnicode_Type, &v, &defobj))
 
1240
        return NULL;
 
1241
 
 
1242
    c = getuchar(v);
 
1243
    if (c == (Py_UCS4)-1)
 
1244
        return NULL;
 
1245
 
 
1246
    if (!_getucname(self, c, name, sizeof(name), 0)) {
 
1247
        if (defobj == NULL) {
 
1248
            PyErr_SetString(PyExc_ValueError, "no such name");
 
1249
            return NULL;
 
1250
        }
 
1251
        else {
 
1252
            Py_INCREF(defobj);
 
1253
            return defobj;
 
1254
        }
 
1255
    }
 
1256
 
 
1257
    return PyUnicode_FromString(name);
 
1258
}
 
1259
 
 
1260
PyDoc_STRVAR(unicodedata_lookup__doc__,
 
1261
"lookup(name)\n\
 
1262
\n\
 
1263
Look up character by name.  If a character with the\n\
 
1264
given name is found, return the corresponding Unicode\n\
 
1265
character.  If not found, KeyError is raised.");
 
1266
 
 
1267
static PyObject *
 
1268
unicodedata_lookup(PyObject* self, PyObject* args)
 
1269
{
 
1270
    Py_UCS4 code;
 
1271
 
 
1272
    char* name;
 
1273
    int namelen;
 
1274
    unsigned int index;
 
1275
    if (!PyArg_ParseTuple(args, "s#:lookup", &name, &namelen))
 
1276
        return NULL;
 
1277
 
 
1278
    if (!_getcode(self, name, namelen, &code, 1)) {
 
1279
        PyErr_Format(PyExc_KeyError, "undefined character name '%s'", name);
 
1280
        return NULL;
 
1281
    }
 
1282
    /* check if code is in the PUA range that we use for named sequences
 
1283
       and convert it */
 
1284
    if (IS_NAMED_SEQ(code)) {
 
1285
        index = code-named_sequences_start;
 
1286
        return PyUnicode_FromKindAndData(PyUnicode_2BYTE_KIND,
 
1287
                                         named_sequences[index].seq,
 
1288
                                         named_sequences[index].seqlen);
 
1289
    }
 
1290
    return PyUnicode_FromOrdinal(code);
 
1291
}
 
1292
 
 
1293
/* XXX Add doc strings. */
 
1294
 
 
1295
static PyMethodDef unicodedata_functions[] = {
 
1296
    UNICODEDATA_UCD_DECIMAL_METHODDEF
 
1297
    {"digit", unicodedata_digit, METH_VARARGS, unicodedata_digit__doc__},
 
1298
    {"numeric", unicodedata_numeric, METH_VARARGS, unicodedata_numeric__doc__},
 
1299
    {"category", unicodedata_category, METH_VARARGS,
 
1300
                 unicodedata_category__doc__},
 
1301
    {"bidirectional", unicodedata_bidirectional, METH_VARARGS,
 
1302
                      unicodedata_bidirectional__doc__},
 
1303
    {"combining", unicodedata_combining, METH_VARARGS,
 
1304
                  unicodedata_combining__doc__},
 
1305
    {"mirrored", unicodedata_mirrored, METH_VARARGS,
 
1306
                 unicodedata_mirrored__doc__},
 
1307
    {"east_asian_width", unicodedata_east_asian_width, METH_VARARGS,
 
1308
                         unicodedata_east_asian_width__doc__},
 
1309
    {"decomposition", unicodedata_decomposition, METH_VARARGS,
 
1310
                      unicodedata_decomposition__doc__},
 
1311
    {"name", unicodedata_name, METH_VARARGS, unicodedata_name__doc__},
 
1312
    {"lookup", unicodedata_lookup, METH_VARARGS, unicodedata_lookup__doc__},
 
1313
    {"normalize", unicodedata_normalize, METH_VARARGS,
 
1314
                  unicodedata_normalize__doc__},
 
1315
    {NULL, NULL}                /* sentinel */
 
1316
};
 
1317
 
 
1318
static PyTypeObject UCD_Type = {
 
1319
        /* The ob_type field must be initialized in the module init function
 
1320
         * to be portable to Windows without using C++. */
 
1321
        PyVarObject_HEAD_INIT(NULL, 0)
 
1322
        "unicodedata.UCD",              /*tp_name*/
 
1323
        sizeof(PreviousDBVersion),      /*tp_basicsize*/
 
1324
        0,                      /*tp_itemsize*/
 
1325
        /* methods */
 
1326
        (destructor)PyObject_Del, /*tp_dealloc*/
 
1327
        0,                      /*tp_print*/
 
1328
        0,                      /*tp_getattr*/
 
1329
        0,                      /*tp_setattr*/
 
1330
        0,                      /*tp_reserved*/
 
1331
        0,                      /*tp_repr*/
 
1332
        0,                      /*tp_as_number*/
 
1333
        0,                      /*tp_as_sequence*/
 
1334
        0,                      /*tp_as_mapping*/
 
1335
        0,                      /*tp_hash*/
 
1336
        0,                      /*tp_call*/
 
1337
        0,                      /*tp_str*/
 
1338
        PyObject_GenericGetAttr,/*tp_getattro*/
 
1339
        0,                      /*tp_setattro*/
 
1340
        0,                      /*tp_as_buffer*/
 
1341
        Py_TPFLAGS_DEFAULT,     /*tp_flags*/
 
1342
        0,                      /*tp_doc*/
 
1343
        0,                      /*tp_traverse*/
 
1344
        0,                      /*tp_clear*/
 
1345
        0,                      /*tp_richcompare*/
 
1346
        0,                      /*tp_weaklistoffset*/
 
1347
        0,                      /*tp_iter*/
 
1348
        0,                      /*tp_iternext*/
 
1349
        unicodedata_functions,  /*tp_methods*/
 
1350
        DB_members,             /*tp_members*/
 
1351
        0,                      /*tp_getset*/
 
1352
        0,                      /*tp_base*/
 
1353
        0,                      /*tp_dict*/
 
1354
        0,                      /*tp_descr_get*/
 
1355
        0,                      /*tp_descr_set*/
 
1356
        0,                      /*tp_dictoffset*/
 
1357
        0,                      /*tp_init*/
 
1358
        0,                      /*tp_alloc*/
 
1359
        0,                      /*tp_new*/
 
1360
        0,                      /*tp_free*/
 
1361
        0,                      /*tp_is_gc*/
 
1362
};
 
1363
 
 
1364
PyDoc_STRVAR(unicodedata_docstring,
 
1365
"This module provides access to the Unicode Character Database which\n\
 
1366
defines character properties for all Unicode characters. The data in\n\
 
1367
this database is based on the UnicodeData.txt file version\n\
 
1368
" UNIDATA_VERSION " which is publically available from ftp://ftp.unicode.org/.\n\
 
1369
\n\
 
1370
The module uses the same names and symbols as defined by the\n\
 
1371
UnicodeData File Format " UNIDATA_VERSION ".");
 
1372
 
 
1373
static struct PyModuleDef unicodedatamodule = {
 
1374
        PyModuleDef_HEAD_INIT,
 
1375
        "unicodedata",
 
1376
        unicodedata_docstring,
 
1377
        -1,
 
1378
        unicodedata_functions,
 
1379
        NULL,
 
1380
        NULL,
 
1381
        NULL,
 
1382
        NULL
 
1383
};
 
1384
 
 
1385
PyMODINIT_FUNC
 
1386
PyInit_unicodedata(void)
 
1387
{
 
1388
    PyObject *m, *v;
 
1389
 
 
1390
    Py_TYPE(&UCD_Type) = &PyType_Type;
 
1391
 
 
1392
    m = PyModule_Create(&unicodedatamodule);
 
1393
    if (!m)
 
1394
        return NULL;
 
1395
 
 
1396
    PyModule_AddStringConstant(m, "unidata_version", UNIDATA_VERSION);
 
1397
    Py_INCREF(&UCD_Type);
 
1398
    PyModule_AddObject(m, "UCD", (PyObject*)&UCD_Type);
 
1399
 
 
1400
    /* Previous versions */
 
1401
    v = new_previous_version("3.2.0", get_change_3_2_0, normalization_3_2_0);
 
1402
    if (v != NULL)
 
1403
        PyModule_AddObject(m, "ucd_3_2_0", v);
 
1404
 
 
1405
    /* Export C API */
 
1406
    v = PyCapsule_New((void *)&hashAPI, PyUnicodeData_CAPSULE_NAME, NULL);
 
1407
    if (v != NULL)
 
1408
        PyModule_AddObject(m, "ucnhash_CAPI", v);
 
1409
    return m;
 
1410
}
 
1411
 
 
1412
/*
 
1413
Local variables:
 
1414
c-basic-offset: 4
 
1415
indent-tabs-mode: nil
 
1416
End:
 
1417
*/