_objects.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * Copyright (C) 2009 Jelmer Vernooij <jelmer@samba.org>
  3. *
  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.
  8. *
  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.
  13. *
  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,
  17. * MA 02110-1301, USA.
  18. */
  19. #include <Python.h>
  20. #define hexbyte(x) (isdigit(x)?(x)-'0':(x)-'a'+0xa)
  21. #define bytehex(x) (((x)<0xa)?('0'+(x)):('a'-0xa+(x)))
  22. static PyObject *py_hex_to_sha(PyObject *self, PyObject *py_hexsha)
  23. {
  24. char *hexsha;
  25. char sha[20];
  26. int i;
  27. if (!PyString_Check(py_hexsha)) {
  28. PyErr_SetString(PyExc_TypeError, "hex sha is not a string");
  29. return NULL;
  30. }
  31. if (PyString_Size(py_hexsha) != 40) {
  32. PyErr_SetString(PyExc_ValueError, "hex sha is not 40 bytes long");
  33. return NULL;
  34. }
  35. hexsha = PyString_AsString(py_hexsha);
  36. for (i = 0; i < 20; i++) {
  37. sha[i] = (hexbyte(hexsha[i*2]) << 4) + hexbyte(hexsha[i*2+1]);
  38. }
  39. return PyString_FromStringAndSize(sha, 20);
  40. }
  41. static PyObject *py_sha_to_hex(PyObject *self, PyObject *py_sha)
  42. {
  43. char hexsha[41];
  44. unsigned char *sha;
  45. int i;
  46. if (!PyString_Check(py_sha)) {
  47. PyErr_SetString(PyExc_TypeError, "sha is not a string");
  48. return NULL;
  49. }
  50. if (PyString_Size(py_sha) != 20) {
  51. PyErr_SetString(PyExc_ValueError, "sha is not 20 bytes long");
  52. return NULL;
  53. }
  54. sha = (unsigned char *)PyString_AsString(py_sha);
  55. for (i = 0; i < 20; i++) {
  56. hexsha[i*2] = bytehex((sha[i] & 0xF0) >> 4);
  57. hexsha[i*2+1] = bytehex(sha[i] & 0x0F);
  58. }
  59. return PyString_FromStringAndSize(hexsha, 40);
  60. }
  61. static PyMethodDef py_objects_methods[] = {
  62. { "hex_to_sha", (PyCFunction)py_hex_to_sha, METH_O, NULL },
  63. { "sha_to_hex", (PyCFunction)py_sha_to_hex, METH_O, NULL },
  64. };
  65. void init_objects(void)
  66. {
  67. PyObject *m;
  68. m = Py_InitModule3("_objects", py_objects_methods, NULL);
  69. if (m == NULL)
  70. return;
  71. }