formats->format
[PyX/mjg.git] / pyx / font / _t1code.c
blobf806fed28a30e9f177c0ef2e966f516281fd69eb
1 /* t1code.c: Copyright 2005 Jörg Lehmann
2 * This program is distributed in the hope that it will be useful,
3 * but WITHOUT ANY WARRANTY; without even the implied warranty of
4 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
5 * GNU General Public License for more details.
7 * You should have received a copy of the GNU General Public License
8 * along with this program; if not, write to the Free Software
9 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
10 * USA.
13 #include <Python.h>
14 #include <stdlib.h>
15 #include <stdint.h>
17 #define C1 52845
18 #define C2 22719
20 /*
21 def decoder(code, r, n):
22 c1 = 52845
23 c2 = 22719
24 data = array.array("B")
25 for x in array.array("B", code):
26 data.append(x ^ (r >> 8))
27 r = ((x + r) * c1 + c2) & 0xffff
28 return data.tostring()[n:]
32 static PyObject *py_decoder(PyObject *self, PyObject *args)
34 unsigned char *code;
35 int lcode, pr, n;
37 if (PyArg_ParseTuple(args, "s#ii", (char **) &code, &lcode, &pr, &n)) {
38 unsigned char *data;
39 int i;
40 unsigned char x;
41 uint16_t r=pr;
42 PyObject *result;
44 if (! (data = (unsigned char *) malloc(lcode)) )
45 return NULL;
47 for (i=0; i<lcode; i++) {
48 x = code[i];
49 data[i] = x ^ ( r >> 8);
50 r = (x + r) * C1 + C2;
53 /* convert result to string stripping first n chars */
54 result = PyString_FromStringAndSize((const char *)data + n, lcode - n);
55 free(data);
56 return result;
58 else return NULL;
63 def encoder(data, r, random):
64 c1 = 52845
65 c2 = 22719
66 code = array.array("B")
67 for x in array.array("B", random+data):
68 code.append(x ^ (r >> 8))
69 r = ((code[-1] + r) * c1 + c2) & 0xffff;
70 return code.tostring()
73 static PyObject *py_encoder(PyObject *self, PyObject *args)
75 unsigned char *data;
76 unsigned char *random;
77 int ldata, pr, lrandom;
79 if (PyArg_ParseTuple(args, "s#is#", (char **) &data, &ldata, &pr, (char **) &random, &lrandom)) {
80 unsigned char *code;
81 int i;
82 uint16_t r=pr;
83 PyObject *result;
85 if (! (code = (unsigned char *) malloc(ldata + lrandom)) )
86 return NULL;
88 for (i=0; i<lrandom; i++) {
89 code[i] = random[i] ^ ( r >> 8);
90 r = (code[i] + r) * C1 + C2;
93 for (i=0; i<ldata; i++) {
94 code[i+lrandom] = data[i] ^ ( r >> 8);
95 r = (code[i+lrandom] + r) * C1 + C2;
98 result = PyString_FromStringAndSize((const char *)code, ldata + lrandom);
99 free(code);
100 return result;
102 else return NULL;
108 /* exported methods */
110 static PyMethodDef t1code_methods[] = {
111 {"decoder", py_decoder, METH_VARARGS},
112 {"encoder", py_encoder, METH_VARARGS},
113 {NULL, NULL}
116 void init_t1code(void) {
117 (void) Py_InitModule("_t1code", t1code_methods);