Sync with RFC.
[libidn.git] / contrib / idn-python / idn.c
blob53363e3bf628ffff3c3545954dc9691c43be20f4
1 /*
2 * This is a Python interface over Simon Josefsson's libidn
3 * <URL:http://josefsson.org/libidn/>.
5 * Stephane Bortzmeyer <bortzmeyer@nic.fr>
7 * $Id$
8 */
10 #include <Python.h>
11 #include <string.h>
12 #include <idna.h>
14 #define MESSAGE_SIZE 512
16 static PyObject *IDNError;
17 static PyObject *IDNInvLengthError;
19 #define onError(message) { PyErr_SetString(IDNError, message); free(message); return NULL; }
21 static PyObject *
22 idn2ace (PyObject * self, PyObject * args)
24 char *instr, *result;
25 int rc;
26 PyObject *outstr;
27 if (!PyArg_ParseTuple (args, "s", &instr))
28 onError ("Invalid argument");
29 rc = idna_utf8_to_ace (instr, &result);
30 if (rc != IDNA_SUCCESS)
32 switch (rc)
34 case IDNA_INVALID_LENGTH:
35 result = malloc (MESSAGE_SIZE);
36 sprintf (result, "%d bytes", strlen (instr));
37 PyErr_SetString (IDNInvLengthError, result);
38 free (result);
39 return NULL;
40 break;
41 default:
42 result = malloc (MESSAGE_SIZE);
43 sprintf (result, "IDN error: %d (see idna.h)", rc);
44 onError (result);
47 outstr = Py_BuildValue ("s", result);
48 return outstr;
51 static PyObject *
52 ace2idn (PyObject * self, PyObject * args)
54 char *instr, *result;
55 int rc;
56 PyObject *outstr;
57 if (!PyArg_ParseTuple (args, "s", &instr))
58 onError ("Invalid argument");
59 rc = idna_utf8ace_to_utf8 (instr, &result);
60 if (rc != IDNA_SUCCESS)
62 result = malloc (MESSAGE_SIZE);
63 sprintf (result, "IDN error: %d (see idna.h)", rc);
64 onError (result);
66 outstr = Py_BuildValue ("s", result);
67 return outstr;
70 static struct PyMethodDef methods[] = {
71 {"idn2ace", idn2ace, 1},
72 {"ace2idn", ace2idn, 1},
73 {NULL, NULL}
76 void
77 initidn ()
79 Py_InitModule ("idn", methods);
80 IDNError = PyErr_NewException ("idn.error", NULL, NULL);
81 IDNInvLengthError = PyErr_NewException ("idn.invalidLength", NULL, NULL);