/*
* Copyright (c) 2012-2013, Steeve Morin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
*    this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
*    this list of conditions and the following disclaimer in the documentation
*    and/or other materials provided with the distribution.
*
* 3. Neither the name of Steeve Morin nor the names of its contributors may be
*    used to endorse or promote products derived from this software without
*    specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/

#include <Python.h>
#include <stdlib.h>
#include <math.h>
#include "lz4.h"
#include "python-lz4-raw.h"

static PyObject *py_lz4_raw_compress(PyObject *self, PyObject *args) {
  (void)self;
  PyObject *result;
  Py_buffer source;
  char *dest;
  int dest_size;

  if (!PyArg_ParseTuple(args, "s*", &source)) {
    return NULL;
  }

  dest_size = LZ4_compressBound(source.len);
  result = PyBytes_FromStringAndSize(NULL, dest_size);
  if (result == NULL) {
    goto exit;
  }
  dest = PyBytes_AS_STRING(result);
  if (source.len > 0) {
    int actual_size = LZ4_compress_default(source.buf, dest, source.len, LZ4_compressBound(source.len));
    if (actual_size < (dest_size / 4) * 3) {
      _PyBytes_Resize(&result, actual_size);
    } else {
      Py_SIZE(result) = actual_size;
    }
  }

 exit:
  if (source.buf) {
    PyBuffer_Release(&source);
  }
  return result;
}

static PyObject *py_lz4_raw_uncompress(PyObject *self, PyObject *args) {
  (void)self;
  PyObject *result;
  Py_buffer source;
  uint32_t bufsize = 1 << LZ4_MEMORY_USAGE;

  if (!PyArg_ParseTuple(args, "s*|i", &source, &bufsize)) {
    return NULL;
  }

  result = PyBytes_FromStringAndSize(NULL, bufsize);
  if (!result || bufsize <= 0) {
    goto exit;
  }

  char *dest = PyBytes_AS_STRING(result);
  int osize = -1;
  Py_BEGIN_ALLOW_THREADS
  osize = LZ4_decompress_safe(source.buf, dest, source.len, bufsize);
  Py_END_ALLOW_THREADS
  if (osize < 0) {
    PyErr_Format(PyExc_ValueError, "corrupt input at byte %d", -osize);
    Py_CLEAR(result);
  }

 exit:
  if (source.buf) {
    PyBuffer_Release(&source);
  }
  return result;
}

static PyObject *py_lz4_versionnumber(PyObject *self, PyObject *args) {
  (void)self;
  (void)args;
  return Py_BuildValue("i", LZ4_versionNumber());
}

static PyMethodDef Lz4Methods[] = {
  {"compress",  py_lz4_raw_compress, METH_VARARGS, COMPRESS_DOCSTRING},
  {"decompress",  py_lz4_raw_uncompress, METH_VARARGS, UNCOMPRESS_DOCSTRING},
  {"lz4version",  py_lz4_versionnumber, METH_VARARGS, "Returns the version number of the lz4 C library"},
  {NULL, NULL, 0, NULL}
};



struct module_state {
  PyObject *error;
};

#if PY_MAJOR_VERSION >= 3
#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
#else
#define GETSTATE(m) (&_state)
static struct module_state _state;
#endif

#if PY_MAJOR_VERSION >= 3

static int myextension_traverse(PyObject *m, visitproc visit, void *arg) {
  Py_VISIT(GETSTATE(m)->error);
  return 0;
}

static int myextension_clear(PyObject *m) {
  Py_CLEAR(GETSTATE(m)->error);
  return 0;
}


static struct PyModuleDef moduledef = {
  PyModuleDef_HEAD_INIT,
  "lz4",
  NULL,
  sizeof(struct module_state),
  Lz4Methods,
  NULL,
  myextension_traverse,
  myextension_clear,
  NULL
};

#define INITERROR return NULL
PyObject *PyInit_lz4(void)

#else
#define INITERROR return
void initlz4_raw(void)

#endif
{
  #if PY_MAJOR_VERSION >= 3
  PyObject *module = PyModule_Create(&moduledef);
  #else
  PyObject *module = Py_InitModule("lz4_raw", Lz4Methods);
  #endif
  struct module_state *st = NULL;

  if (module == NULL) {
    INITERROR;
  }
  st = GETSTATE(module);

  st->error = PyErr_NewException("lz4.Error", NULL, NULL);
  if (st->error == NULL) {
    Py_DECREF(module);
    INITERROR;
  }

  PyModule_AddStringConstant(module, "VERSION", VERSION);
  PyModule_AddStringConstant(module, "__version__", VERSION);
  #ifdef LZ4_VERSION /* Only defined if we're building against bundled lz4 */
  PyModule_AddStringConstant(module, "LZ4_VERSION", LZ4_VERSION);
  #endif

  #if PY_MAJOR_VERSION >= 3
  return module;
  #endif
}
