2 * Copyright (C) 2009 Jelmer Vernooij <jelmer@samba.org>
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; version 2
7 * of the License or (at your option) a later version of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22 #define hexbyte(x) (isdigit(x)?(x)-'0':(x)-'a'+0xa)
23 #define bytehex(x) (((x)<0xa)?('0'+(x)):('a'-0xa+(x)))
25 static PyObject *py_hex_to_sha(PyObject *self, PyObject *py_hexsha)
31 if (!PyString_CheckExact(py_hexsha)) {
32 PyErr_SetString(PyExc_TypeError, "hex sha is not a string");
36 if (PyString_Size(py_hexsha) != 40) {
37 PyErr_SetString(PyExc_ValueError, "hex sha is not 40 bytes long");
41 hexsha = PyString_AsString(py_hexsha);
43 for (i = 0; i < 20; i++) {
44 sha[i] = (hexbyte(hexsha[i*2]) << 4) + hexbyte(hexsha[i*2+1]);
47 return PyString_FromStringAndSize(sha, 20);
50 static PyObject *sha_to_pyhex(const unsigned char *sha)
54 for (i = 0; i < 20; i++) {
55 hexsha[i*2] = bytehex((sha[i] & 0xF0) >> 4);
56 hexsha[i*2+1] = bytehex(sha[i] & 0x0F);
59 return PyString_FromStringAndSize(hexsha, 40);
62 static PyObject *py_sha_to_hex(PyObject *self, PyObject *py_sha)
64 if (!PyString_CheckExact(py_sha)) {
65 PyErr_SetString(PyExc_TypeError, "sha is not a string");
69 if (PyString_Size(py_sha) != 20) {
70 PyErr_SetString(PyExc_ValueError, "sha is not 20 bytes long");
74 return sha_to_pyhex((unsigned char *)PyString_AsString(py_sha));
77 static PyObject *py_parse_tree(PyObject *self, PyObject *args)
81 PyObject *ret, *item, *name;
83 if (!PyArg_ParseTuple(args, "s#", &text, &len))
95 mode = strtol(text, &text, 8);
98 PyErr_SetString(PyExc_RuntimeError, "Expected space");
105 namelen = strlen(text);
107 name = PyString_FromStringAndSize(text, namelen);
113 item = Py_BuildValue("(lN)", mode, sha_to_pyhex((unsigned char *)text+namelen+1));
119 if (PyDict_SetItem(ret, name, item) == -1) {
133 static PyMethodDef py_objects_methods[] = {
134 { "hex_to_sha", (PyCFunction)py_hex_to_sha, METH_O, NULL },
135 { "sha_to_hex", (PyCFunction)py_sha_to_hex, METH_O, NULL },
136 { "parse_tree", (PyCFunction)py_parse_tree, METH_VARARGS, NULL, },
139 void init_objects(void)
143 m = Py_InitModule3("_objects", py_objects_methods, NULL);