[
  {
    "path": ".gitignore",
    "content": "*.py[cod]\n\n# C extensions\n*.so\n\n# Packages\n*.egg\n*.egg-info\ndist\nbuild\neggs\nparts\nbin\nvar\nsdist\ndevelop-eggs\n.installed.cfg\nlib\nlib64\n\n# Installer logs\npip-log.txt\n\n# Unit test / coverage reports\n.coverage\n.tox\nnosetests.xml\n\n# Translations\n*.mo\n\n# Mr Developer\n.mr.developer.cfg\n.project\n.pydevproject\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: python\npython:\n  - \"3.2\"\n  - \"3.3\"\n  - \"3.4\"\n  - \"2.7\"\n  - \"2.6\"\n\n# command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors\n# Build steps taken from\n# https://github.com/nanomsg/nanomsg#build-it-with-cmake\ninstall:\n  - git clone --quiet --depth=100 \"https://github.com/nanomsg/nanomsg.git\" ~/builds/nanomsg\n      && pushd ~/builds/nanomsg\n      && mkdir build\n      && cd build\n      && cmake ..\n      && cmake --build .\n      && ctest -C Debug .\n      && sudo cmake --build . --target install\n      && sudo ldconfig\n      && popd\n\n# command to run tests, e.g. python setup.py test\nscript: LD_LIBRARY_PATH=/lib:/usr/lib:/usr/local/lib python setup.py test\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2013 Tony Simpson\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "nanomsg-python\n==============\n\nPython library for [nanomsg](http://nanomsg.org/) which does not compromise on\nusability or performance.\n\nLike nanomsg this library is still experimental, the API is fairly stable but\nif you plan to use it at this time be prepared to get your hands dirty,\nfixes and enhancements are very welcome.\n\nThe following versions of Python are supported CPython 2.6+, 3.2+ and Pypy 2.1.0+\n\nBugs and change requests can be made\n[here](https://github.com/tonysimpson/nanomsg-python/issues).\n\n\nnanommsg library in /usr/local\n==============================\n\n\nIf you're nanomsg is in /usr/local and your machine is not configured to find it there you can rename the usr_local_setup.cfg to setup.cfg to fix the problem.\n\n\nExample\n=======\n\n```python\nfrom __future__ import print_function\nfrom nanomsg import Socket, PAIR, PUB\ns1 = Socket(PAIR)\ns2 = Socket(PAIR)\ns1.bind('inproc://bob')\ns2.connect('inproc://bob')\ns1.send(b'hello nanomsg')\nprint(s2.recv())\ns1.close()\ns2.close()\n```\n\nOr if you don't mind nesting you can use Socket as a context manager\n\n```python\nwith Socket(PUB) as pub_socket:\n    .... do something with pub_socket\n# socket is closed\n```\n\nThe lower level API is also available if you need the additional control or\nperformance, but it is harder to use. Error checking left out for brevity.\n\n```python\nfrom nanomsg import wrapper as nn_wrapper\nfrom nanomsg import PAIR, AF_SP\n\ns1 = nn_wrapper.nn_socket(AF_SP, PAIR)\ns2 = nn_wrapper.nn_socket(AF_SP, PAIR)\nnn_wrapper.nn_bind(s1, 'inproc://bob')\nnn_wrapper.nn_connect(s2, 'inproc://bob')\nnn_wrapper.nn_send(s1, b'hello nanomsg', 0)\nresult, buffer = nn_wrapper.nn_recv(s2, 0)\nprint(bytes(buffer))\nnn_wrapper.nn_term()\n```\n\nLicense\n=======\n\nMIT\n\n\nAuthors\n=======\n\n[Tony Simpson](https://github.com/tonysimpson)\n"
  },
  {
    "path": "_nanomsg_cpy/wrapper.c",
    "content": "#include <Python.h>\n#include <structmember.h>\n#include <bytesobject.h>\n#include <nanomsg/nn.h>\n\n#ifdef WITH_NANOCONFIG\n#include <nanomsg/nanoconfig.h>\n#endif\n\n\n#if PY_MAJOR_VERSION >= 3\n#define IS_PY3K\n#endif\n\n/* This might be a good idea or not */\n#ifndef NO_CONCURRENY\n#define CONCURRENCY_POINT_BEGIN Py_BEGIN_ALLOW_THREADS\n#define CONCURRENCY_POINT_END Py_END_ALLOW_THREADS\n#else\n#define CONCURRENCY_POINT_BEGIN\n#define CONCURRENCY_POINT_END\n#endif\n\n\n/* defined to allow the same source for 2.6+ and 3.2+ */\n#ifdef IS_PY3K\n#define Py_TPFLAGS_HAVE_CLASS     0L\n#define Py_TPFLAGS_HAVE_NEWBUFFER 0L\n#endif\n\nconst static char MODULE_NAME[] = \"_nanomsg_cpy\";\n\n\ntypedef struct {\n    PyObject_HEAD\n    void *msg;\n    size_t size;\n} Message;\n\nstatic void\nMessage_dealloc(Message* self)\n{\n    if (self->msg != NULL) {\n        nn_freemsg(self->msg);\n    }\n    Py_TYPE(self)->tp_free((PyObject*)self);\n}\n\nstatic PyObject*\nMessage_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {\n    PyErr_Format(PyExc_TypeError,\n                 \"cannot create '%.100s' instances us nn_alloc instead\",\n                 type->tp_name);\n    return NULL;\n}\n\nstatic PyMemberDef Message_members[] = {\n    {NULL}  /* Sentinel */\n};\n\nstatic PyMethodDef Message_methods[] = {\n    {NULL}  /* Sentinel */\n};\n\nint Message_getbuffer(Message *self, Py_buffer *view, int flags) {\n    if( self->msg == NULL)\n    {\n         PyErr_BadInternalCall();\n         return -1;\n    }\n    return PyBuffer_FillInfo(view, (PyObject*)self, self->msg, self->size, 0, flags);\n}\n\n#ifndef IS_PY3K\nstatic int Message_getreadbuffer(Message *self, int segment, void **ptrptr)\n{\n    if(segment != 0 || self->msg == NULL)\n    {\n         PyErr_BadInternalCall();\n         return -1;\n    }\n    *ptrptr = ((Message*)self)->msg;\n    return ((Message*)self)->size;\n}\n\nstatic int Message_getwritebuffer(Message *self, int segment, void **ptrptr)\n{\n    if(segment != 0 || self->msg == NULL)\n    {\n         PyErr_BadInternalCall();\n         return -1;\n    }\n    *ptrptr = ((Message*)self)->msg;\n    return ((Message*)self)->size;\n}\n\nstatic int Message_getsegcountproc(PyObject *self, int *lenp) {\n    if (lenp != NULL) {\n        *lenp = ((Message*)self)->size;\n    }\n    return 1;\n}\n#endif\n\n\nstatic PyBufferProcs Message_bufferproces = {\n#ifndef IS_PY3K\n    (readbufferproc)Message_getreadbuffer,\n    (writebufferproc)Message_getwritebuffer,\n    (segcountproc)Message_getsegcountproc,\n    NULL,\n#endif\n    (getbufferproc)Message_getbuffer,\n    NULL\n};\n\nstatic PyObject *\nMessage_repr(Message * obj)\n{\n    return PyUnicode_FromFormat(\"<_nanomsg_cpy.Message size %zu, address %p >\",\n                               obj->size, obj->msg);\n}\n\n\nstatic PyObject *\nMessage_str(Message * obj)\n{\n    return PyBytes_FromStringAndSize(obj->msg, obj->size);\n}\n\nstatic PyTypeObject MessageType = {\n    PyVarObject_HEAD_INIT(NULL, 0)\n    \"_nanomsg_cpy.Message\",          /*tp_name*/\n    sizeof(Message),             /*tp_basicsize*/\n    0,                           /*tp_itemsize*/\n    (destructor)Message_dealloc, /*tp_dealloc*/\n    0,                           /*tp_print*/\n    0,                           /*tp_getattr*/\n    0,                           /*tp_setattr*/\n    0,                           /*tp_compare*/\n    (reprfunc)Message_repr,      /*tp_repr*/\n    0,                           /*tp_as_number*/\n    0,                           /*tp_as_sequence*/\n    0,                           /*tp_as_mapping*/\n    0,                           /*tp_hash */\n    0,                           /*tp_call*/\n    (reprfunc)Message_str,       /*tp_str*/\n    0,                           /*tp_getattro*/\n    0,                           /*tp_setattro*/\n    &Message_bufferproces,       /*tp_as_buffer*/\n    Py_TPFLAGS_HAVE_CLASS | Py_TPFLAGS_HAVE_NEWBUFFER |\n        Py_TPFLAGS_IS_ABSTRACT,  /*tp_flags*/\n    \"nanomsg allocated message wrapper supporting buffer protocol\", /* tp_doc */\n    0,                     /* tp_traverse */\n    0,                     /* tp_clear */\n    0,                     /* tp_richcompare */\n    0,                     /* tp_weaklistoffset */\n    0,                     /* tp_iter */\n    0,                     /* tp_iternext */\n    Message_methods,           /* tp_methods */\n    Message_members,           /* tp_members */\n    0,                         /* tp_getset */\n    0,                         /* tp_base */\n    0,                         /* tp_dict */\n    0,                         /* tp_descr_get */\n    0,                         /* tp_descr_set */\n    0,                         /* tp_dictoffset */\n    0,                         /* tp_init */\n    0,                         /* tp_alloc */\n    Message_new,               /* tp_new */\n};\n\nstatic PyObject *\n_nanomsg_cpy_nn_errno(PyObject *self, PyObject *args)\n{\n    return Py_BuildValue(\"i\", nn_errno());\n}\n\nstatic PyObject *\n_nanomsg_cpy_nn_strerror(PyObject *self, PyObject *args)\n{\n    int error_number;\n    if (!PyArg_ParseTuple(args, \"i\", &error_number))\n        return NULL;\n    return Py_BuildValue(\"s\", nn_strerror(error_number));\n}\n\nstatic PyObject *\n_nanomsg_cpy_nn_socket(PyObject *self, PyObject *args)\n{\n    int domain, protocol;\n    if (!PyArg_ParseTuple(args, \"ii\", &domain, &protocol))\n        return NULL;\n    return Py_BuildValue(\"i\", nn_socket(domain, protocol));\n}\n\nstatic PyObject *\n_nanomsg_cpy_nn_close(PyObject *self, PyObject *args)\n{\n    int nn_result, socket;\n\n    if (!PyArg_ParseTuple(args, \"i\", &socket))\n        return NULL;\n\n    CONCURRENCY_POINT_BEGIN\n    nn_result = nn_close(socket);\n    CONCURRENCY_POINT_END\n\n    return Py_BuildValue(\"i\", nn_result);\n}\n\n#ifdef WITH_NANOCONFIG\nstatic PyObject *\n_nanomsg_cpy_nc_close(PyObject *self, PyObject *args)\n{\n    int nn_result, socket;\n\n    if (!PyArg_ParseTuple(args, \"i\", &socket))\n        return NULL;\n\n    CONCURRENCY_POINT_BEGIN\n    nc_close(socket);\n    CONCURRENCY_POINT_END\n\n    Py_RETURN_NONE;\n}\n#endif\n\nstatic const char _nanomsg_cpy_nn_setsockopt__doc__[] =\n\"set a socket option\\n\"\n\"\\n\"\n\"socket - socket number\\n\"\n\"level - option level\\n\"\n\"option - option\\n\"\n\"value - a readable byte buffer (not a Unicode string) containing the value\\n\"\n\"returns - 0 on success or < 0 on error\\n\\n\";\n\nstatic PyObject *\n_nanomsg_cpy_nn_setsockopt(PyObject *self, PyObject *args)\n{\n    int nn_result, socket, level, option;\n    Py_buffer value;\n\n    if (!PyArg_ParseTuple(args, \"iiis*\", &socket, &level, &option, &value))\n        return NULL;\n\n    nn_result = nn_setsockopt(socket, level, option, value.buf, value.len);\n    PyBuffer_Release(&value);\n    return Py_BuildValue(\"i\", nn_result);\n}\n\n\nstatic const char _nanomsg_cpy_nn_getsockopt__doc__[] =\n\"retrieve a socket option\\n\"\n\"\\n\"\n\"socket - socket number\\n\"\n\"level - option level\\n\"\n\"option - option\\n\"\n\"value - a writable byte buffer (e.g. a bytearray) which the option value \"\n\"will be copied to.\\n\"\n\"returns - number of bytes copied or on error nunber < 0\\n\\n\";\n\nstatic PyObject *\n_nanomsg_cpy_nn_getsockopt(PyObject *self, PyObject *args)\n{\n    int nn_result, socket, level, option;\n    size_t length;\n    Py_buffer value;\n\n    if (!PyArg_ParseTuple(args, \"iiiw*\", &socket, &level, &option, &value))\n        return NULL;\n    length = value.len;\n    nn_result = nn_getsockopt(socket, level, option, value.buf, &length);\n    PyBuffer_Release(&value);\n    return Py_BuildValue(\"in\", nn_result, length);\n}\n\nstatic PyObject *\n_nanomsg_cpy_nn_bind(PyObject *self, PyObject *args)\n{\n    int socket;\n    const char *address;\n    if (!PyArg_ParseTuple(args, \"is\", &socket, &address))\n        return NULL;\n    return Py_BuildValue(\"i\", nn_bind(socket, address));\n}\n\nstatic PyObject *\n_nanomsg_cpy_nn_connect(PyObject *self, PyObject *args)\n{\n    int socket;\n    const char *address;\n    if (!PyArg_ParseTuple(args, \"is\", &socket, &address))\n        return NULL;\n    return Py_BuildValue(\"i\", nn_connect(socket, address));\n}\n\n#ifdef WITH_NANOCONFIG\nstatic PyObject *\n_nanomsg_cpy_nc_configure(PyObject *self, PyObject *args)\n{\n    int socket;\n    const char *address;\n    if (!PyArg_ParseTuple(args, \"is\", &socket, &address))\n        return NULL;\n    return Py_BuildValue(\"i\", nc_configure(socket, address));\n}\n#endif\n\nstatic PyObject *\n_nanomsg_cpy_nn_shutdown(PyObject *self, PyObject *args)\n{\n    int nn_result, socket, endpoint;\n\n    if (!PyArg_ParseTuple(args, \"ii\", &socket, &endpoint))\n        return NULL;\n\n    CONCURRENCY_POINT_BEGIN\n    nn_result = nn_shutdown(socket, endpoint);\n    CONCURRENCY_POINT_END\n    return Py_BuildValue(\"i\", nn_result);\n}\n\nstatic PyObject *\n_nanomsg_cpy_nn_send(PyObject *self, PyObject *args)\n{\n    int nn_result, socket, flags;\n    Py_buffer buffer;\n\n    if (!PyArg_ParseTuple(args, \"is*i\", &socket, &buffer, &flags))\n        return NULL;\n\n    CONCURRENCY_POINT_BEGIN\n    nn_result = nn_send(socket, buffer.buf, buffer.len, flags);\n    CONCURRENCY_POINT_END\n    PyBuffer_Release(&buffer);\n    return Py_BuildValue(\"i\", nn_result);\n}\n\nstatic PyObject *\n_nanomsg_cpy_nn_recv(PyObject *self, PyObject *args)\n{\n    int nn_result, socket, flags;\n    Py_buffer buffer;\n    Message* message;\n\n    if(PyTuple_GET_SIZE(args) == 2) {\n        if (!PyArg_ParseTuple(args, \"ii\", &socket, &flags))\n            return NULL;\n        message =  (Message*)PyType_GenericAlloc(&MessageType, 0);\n        if(message == NULL) {\n            return NULL;\n        }\n        CONCURRENCY_POINT_BEGIN\n        nn_result = nn_recv(socket, &message->msg, NN_MSG, flags);\n        CONCURRENCY_POINT_END\n        if (nn_result < 0) {\n            Py_DECREF((PyObject*)message);\n            return Py_BuildValue(\"is\", nn_result, NULL);\n        }\n        message->size = nn_result;\n        return Py_BuildValue(\"iN\", nn_result, message);\n    }\n    else {\n        if(!PyArg_ParseTuple(args, \"iw*i\", &socket, &buffer, &flags))\n            return NULL;\n        CONCURRENCY_POINT_BEGIN\n        nn_result = nn_recv(socket, buffer.buf, buffer.len, flags);\n        CONCURRENCY_POINT_END\n        PyBuffer_Release(&buffer);\n        return Py_BuildValue(\"iO\", nn_result, PyTuple_GET_ITEM(args, 1));\n    }\n}\n\nstatic PyObject *\n_nanomsg_cpy_nn_device(PyObject *self, PyObject *args)\n{\n    int socket_1, socket_2, nn_result;\n    if (!PyArg_ParseTuple(args, \"ii\", &socket_1, &socket_2))\n        return NULL;\n    CONCURRENCY_POINT_BEGIN\n    nn_result = nn_device(socket_1, socket_2);\n    CONCURRENCY_POINT_END\n    return Py_BuildValue(\"i\", nn_result);\n}\n\nstatic PyObject *\n_nanomsg_cpy_nn_poll(PyObject *self, PyObject *args)\n{\n    int timeout_ms, res;\n    PyObject *socket_event_dict, *sockets;\n    Py_ssize_t socket_count;\n    struct nn_pollfd *fds;\n    Py_ssize_t pos;\n    int i;\n    PyObject *key, *value;\n    PyObject *code;\n    PyObject *result;\n    if (!PyArg_ParseTuple(args, \"O!i\", &PyDict_Type, &socket_event_dict, &timeout_ms)) {\n        return NULL;\n    }\n\n    sockets = PyDict_New();\n    socket_count = PyDict_Size(socket_event_dict);\n    fds = malloc(sizeof(struct nn_pollfd)*socket_count);\n\n    // build up fds array\n    pos = 0;\n    i = 0;\n    while (PyDict_Next(socket_event_dict, &pos, &key, &value)) {\n        fds[i].fd = (int)PyLong_AsLong(key);\n        fds[i].events = (short)PyLong_AsLong(value);\n        fds[i].revents = 0;\n        i++;\n    }\n\n    CONCURRENCY_POINT_BEGIN\n    res = nn_poll(fds, (int)socket_count, timeout_ms);\n    CONCURRENCY_POINT_END\n\n    // if success build result dictionary\n    if (res > 0) {\n        for(i = 0; i < socket_count; i++) {\n            int fd = fds[i].fd;\n            int revents = fds[i].revents;\n            PyDict_SetItem(sockets, Py_BuildValue(\"i\", fd), Py_BuildValue(\"i\", revents));\n        }\n    }\n\n    free(fds);\n\n    code = PyLong_FromUnsignedLong(res);\n    result = PyTuple_Pack(2, code, sockets);\n\n    return result;\n}\n\nstatic PyObject *\n_nanomsg_cpy_nn_term(PyObject *self, PyObject *args)\n{\n    nn_term();\n    Py_RETURN_NONE;\n}\n\n#ifdef WITH_NANOCONFIG\nstatic PyObject *\n_nanomsg_cpy_nc_term(PyObject *self, PyObject *args)\n{\n    nc_term();\n    Py_RETURN_NONE;\n}\n#endif\n\n\nstatic PyObject *\n_nanomsg_cpy_nn_allocmsg(PyObject *self, PyObject *args)\n{\n    size_t size;\n    int type;\n    Message *message;\n\n    if (!PyArg_ParseTuple(args, \"ni\", &size, &type))\n        return NULL;\n\n    message = (Message*)PyType_GenericAlloc(&MessageType, 0);\n\n    message->msg = nn_allocmsg(size, type);\n\n    if (message->msg == NULL) {\n        Py_DECREF((PyObject*)message);\n        Py_RETURN_NONE;\n    }\n\n    message->size = size;\n\n    return (PyObject*)message;\n}\n\n\n\nconst char *nn_symbol (int i, int *value);\n\n\nstatic PyObject *\n_nanomsg_cpy_nn_symbols(PyObject *self, PyObject *args)\n{\n    PyObject* py_list;\n    const char *name;\n    int value, i;\n\n    py_list = PyList_New(0);\n\n    for(i = 0; /*break inside loop */ ; i++) {\n        name = nn_symbol(i,&value);\n        if(name == NULL) {\n            break;\n        }\n        PyList_Append(py_list, Py_BuildValue(\"si\", name, value));\n    }\n    return (PyObject*)py_list;\n}\n\n\nstatic PyMethodDef module_methods[] = {\n    {\"nn_errno\", _nanomsg_cpy_nn_errno, METH_VARARGS, \"retrieve the current errno\"},\n    {\"nn_strerror\", _nanomsg_cpy_nn_strerror, METH_VARARGS, \"convert an error number into human-readable string\"},\n    {\"nn_socket\", _nanomsg_cpy_nn_socket, METH_VARARGS, \"create an SP socket\"},\n    {\"nn_close\", _nanomsg_cpy_nn_close, METH_VARARGS, \"close an SP socket\"},\n    {\"nn_setsockopt\", _nanomsg_cpy_nn_setsockopt, METH_VARARGS, _nanomsg_cpy_nn_setsockopt__doc__},\n    {\"nn_getsockopt\", _nanomsg_cpy_nn_getsockopt, METH_VARARGS, _nanomsg_cpy_nn_getsockopt__doc__},\n    {\"nn_bind\", _nanomsg_cpy_nn_bind, METH_VARARGS, \"add a local endpoint to the socket\"},\n    {\"nn_connect\", _nanomsg_cpy_nn_connect, METH_VARARGS, \"add a remote endpoint to the socket\"},\n    {\"nn_shutdown\", _nanomsg_cpy_nn_shutdown, METH_VARARGS, \"remove an endpoint from a socket\"},\n    {\"nn_send\", _nanomsg_cpy_nn_send, METH_VARARGS, \"send a message\"},\n    {\"nn_recv\", _nanomsg_cpy_nn_recv, METH_VARARGS, \"receive a message\"},\n    {\"nn_device\", _nanomsg_cpy_nn_device, METH_VARARGS, \"start a device\"},\n    {\"nn_poll\", _nanomsg_cpy_nn_poll, METH_VARARGS, \"poll sockets\"},\n    {\"nn_term\", _nanomsg_cpy_nn_term, METH_VARARGS, \"notify all sockets about process termination\"},\n    {\"nn_allocmsg\", _nanomsg_cpy_nn_allocmsg, METH_VARARGS, \"allocate a message\"},\n    {\"nn_symbols\", _nanomsg_cpy_nn_symbols, METH_VARARGS, \"query the names and values of nanomsg symbols\"},\n#ifdef WITH_NANOCONFIG\n    {\"nc_configure\", _nanomsg_cpy_nc_configure, METH_VARARGS, \"configure socket using nanoconfig\"},\n    {\"nc_close\", _nanomsg_cpy_nc_close, METH_VARARGS, \"close an SP socket configured with nn_configure\"},\n    {\"nc_term\", _nanomsg_cpy_nc_term, METH_VARARGS, \"shut down nanoconfig worker thread\"},\n#endif\n    {NULL, NULL, 0, NULL}\n};\n\n\n#ifndef IS_PY3K\nPyMODINIT_FUNC\ninit_nanomsg_cpy(void)\n{\n    PyObject* m;\n\n    if (PyType_Ready(&MessageType) < 0)\n        return;\n    m = Py_InitModule(MODULE_NAME, module_methods);\n    if (m == NULL)\n      return;\n\n    Py_INCREF(&MessageType);\n    PyModule_AddObject(m, \"Message\", (PyObject *)&MessageType);\n}\n#else\nstatic struct PyModuleDef _nanomsg_cpy_module = {\n   PyModuleDef_HEAD_INIT,\n   MODULE_NAME,\n   NULL,\n   -1,\n   module_methods\n};\n\nPyMODINIT_FUNC\nPyInit__nanomsg_cpy(void)\n{\n    PyObject* m;\n\n    if (PyType_Ready(&MessageType) < 0)\n        return NULL;\n    m = PyModule_Create(&_nanomsg_cpy_module);\n    if(m != NULL) {\n        PyModule_AddObject(m, \"Message\", (PyObject *)&MessageType);\n    }\n    return m;\n}\n#endif\n"
  },
  {
    "path": "_nanomsg_ctypes/__init__.py",
    "content": "from __future__ import division, absolute_import, print_function,\\\n unicode_literals\n\nimport ctypes\nimport platform\nimport sys\n\nif sys.platform in ('win32', 'cygwin'):\n    _functype = ctypes.WINFUNCTYPE\n    _lib = ctypes.windll.nanomsg\nelif sys.platform == 'darwin':\n    _functype = ctypes.CFUNCTYPE\n    _lib = ctypes.cdll.LoadLibrary('libnanomsg.dylib')\nelse:\n    _functype = ctypes.CFUNCTYPE\n    _lib = ctypes.cdll.LoadLibrary('libnanomsg.so')\n\n\ndef _c_func_wrapper_factory(cdecl_text):\n    def move_pointer_and_strip(type_def, name):\n        if '*' in name:\n            type_def += ' ' + name[:name.rindex('*')+1]\n            name = name.rsplit('*', 1)[1]\n        return type_def.strip(), name.strip()\n\n    def type_lookup(type_def):\n        types = {\n            'void': None,\n            'char *': ctypes.c_char_p,\n            'const char *': ctypes.c_char_p,\n            'int': ctypes.c_int,\n            'int *': ctypes.POINTER(ctypes.c_int),\n            'void *': ctypes.c_void_p,\n            'size_t':  ctypes.c_size_t,\n            'size_t *':  ctypes.POINTER(ctypes.c_size_t),\n            'struct nn_msghdr *': ctypes.c_void_p,\n            'struct nn_pollfd *': ctypes.c_void_p,\n        }\n        type_def_without_const = type_def.replace('const ','')\n        if type_def_without_const in types:\n            return types[type_def_without_const]\n        elif (type_def_without_const.endswith('*') and\n                type_def_without_const[:-1] in types):\n            return ctypes.POINTER(types[type_def_without_const[:-1]])\n        else:\n            raise KeyError(type_def)\n\n        return types[type_def.replace('const ','')]\n\n    a, b = [i.strip() for i in cdecl_text.split('(',1)]\n    params, _ = b.rsplit(')',1)\n    rtn_type, name = move_pointer_and_strip(*a.rsplit(' ', 1))\n    param_spec = []\n    for param in params.split(','):\n        if param != 'void':\n            param_spec.append(move_pointer_and_strip(*param.rsplit(' ', 1)))\n    func = _functype(type_lookup(rtn_type),\n                     *[type_lookup(type_def) for type_def, _ in param_spec])(\n                        (name, _lib),\n                        tuple((2 if '**' in type_def else 1, name)\n                              for type_def, name in param_spec)\n                    )\n    func.__name__ = name\n    return func\n\n\n_C_HEADER = \"\"\"\nNN_EXPORT int nn_errno (void);\nNN_EXPORT const char *nn_strerror (int errnum);\nNN_EXPORT const char *nn_symbol (int i, int *value);\nNN_EXPORT void nn_term (void);\nNN_EXPORT void *nn_allocmsg (size_t size, int type);\nNN_EXPORT int nn_freemsg (void *msg);\nNN_EXPORT int nn_socket (int domain, int protocol);\nNN_EXPORT int nn_close (int s);\nNN_EXPORT int nn_setsockopt (int s, int level, int option, const void \\\n*optval, size_t optvallen);\nNN_EXPORT int nn_getsockopt (int s, int level, int option, void *optval, \\\nsize_t *optvallen);\nNN_EXPORT int nn_poll(struct nn_pollfd *fds, int nfds, int timeout);\nNN_EXPORT int nn_bind (int s, const char *addr);\nNN_EXPORT int nn_connect (int s, const char *addr);\nNN_EXPORT int nn_shutdown (int s, int how);\nNN_EXPORT int nn_send (int s, const void *buf, size_t len, int flags);\nNN_EXPORT int nn_recv (int s, void *buf, size_t len, int flags);\nNN_EXPORT int nn_sendmsg (int s, const struct nn_msghdr *msghdr, int flags);\nNN_EXPORT int nn_recvmsg (int s, struct nn_msghdr *msghdr, int flags);\nNN_EXPORT int nn_device (int s1, int s2);\\\n\"\"\".replace('NN_EXPORT', '')\n\n\nfor cdecl_text in _C_HEADER.splitlines():\n    if cdecl_text.strip():\n        func = _c_func_wrapper_factory(cdecl_text)\n        globals()['_' + func.__name__] = func\n\n\ndef nn_symbols():\n    \"query the names and values of nanomsg symbols\"\n    value = ctypes.c_int()\n    name_value_pairs = []\n    i = 0\n    while True:\n        name = _nn_symbol(i, ctypes.byref(value))\n        if name is None:\n            break\n        i += 1\n        name_value_pairs.append((name.decode('ascii'), value.value))\n    return name_value_pairs\n\n\nnn_errno = _nn_errno\nnn_errno.__doc__ = \"retrieve the current errno\"\n\nnn_strerror = _nn_strerror\nnn_strerror.__doc__ = \"convert an error number into human-readable string\"\n\nnn_socket = _nn_socket\nnn_socket.__doc__ = \"create an SP socket\"\n\nnn_close = _nn_close\nnn_close.__doc__ = \"close an SP socket\"\n\nnn_bind = _nn_bind\nnn_bind.__doc__ = \"add a local endpoint to the socket\"\n\nnn_connect = _nn_connect\nnn_connect.__doc__ = \"add a remote endpoint to the socket\"\n\nnn_shutdown = _nn_shutdown\nnn_shutdown.__doc__ = \"remove an endpoint from a socket\"\n\n\ndef create_writable_buffer(size):\n    \"\"\"Returns a writable buffer.\n\n    This is the ctypes implementation.\n    \"\"\"\n    return (ctypes.c_ubyte*size)()\n\n\ndef nn_setsockopt(socket, level, option, value):\n    \"\"\"set a socket option\n\n    socket - socket number\n    level - option level\n    option - option\n    value - a readable byte buffer (not a Unicode string) containing the value\n    returns - 0 on success or < 0 on error\n\n    \"\"\"\n    try:\n        return _nn_setsockopt(socket, level, option, ctypes.addressof(value),\n                              len(value))\n    except (TypeError, AttributeError):\n        buf_value = ctypes.create_string_buffer(value)\n        return _nn_setsockopt(socket, level, option,\n                              ctypes.addressof(buf_value), len(value))\n\n\ndef nn_getsockopt(socket, level, option, value):\n    \"\"\"retrieve a socket option\n\n    socket - socket number\n    level - option level\n    option - option\n    value - a writable byte buffer (e.g. a bytearray) which the option value\n    will be copied to\n    returns - number of bytes copied or on error nunber < 0\n\n    \"\"\"\n    if memoryview(value).readonly:\n        raise TypeError('Writable buffer is required')\n    size_t_size = ctypes.c_size_t(len(value))\n    rtn = _nn_getsockopt(socket, level, option, ctypes.addressof(value),\n                         ctypes.byref(size_t_size))\n    return (rtn, size_t_size.value)\n\n\ndef nn_send(socket, msg, flags):\n    \"send a message\"\n    try:\n        return _nn_send(socket, ctypes.addressof(msg), len(buffer(msg)), flags)\n    except (TypeError, AttributeError):\n        buf_msg = ctypes.create_string_buffer(msg)\n        return _nn_send(socket, ctypes.addressof(buf_msg), len(msg), flags)\n\n\ndef _create_message(address, length):\n    class Message(ctypes.Union):\n        _fields_ = [('_buf', ctypes.c_ubyte*length)]\n        _len = length\n        _address = address\n\n        def __repr__(self):\n            return '<_nanomsg_cpy.Message size %d, address 0x%x >' % (\n                self._len,\n                self._address\n            )\n\n        def __str__(self):\n            return bytes(buffer(self))\n\n        def __del__(self):\n            _nn_freemsg(self._address)\n            self._len = 0\n            self._address = 0\n\n    return Message.from_address(address)\n\n\ndef nn_allocmsg(size, type):\n    \"allocate a message\"\n    pointer = _nn_allocmsg(size, type)\n    if pointer is None:\n        return None\n    return _create_message(pointer, size)\n\n\nclass PollFds(ctypes.Structure):\n    _fields_ = (\"fd\", ctypes.c_int), (\"events\", ctypes.c_short), (\"revents\", ctypes.c_short)\n\n\ndef nn_poll(fds, timeout=-1):\n    \"\"\"\n    nn_pollfds\n    :param fds: dict (file descriptor => pollmode)\n    :param timeout: timeout in milliseconds\n    :return:\n    \"\"\"\n    polls = []\n    for i, entry in enumerate(fds.items()):\n        s = PollFds()\n        fd, event = entry\n        s.fd = fd\n        s.events = event\n        s.revents = 0\n        polls.append(s)\n\n    poll_array = (PollFds*len(fds))(*polls)\n    res = _nn_poll(poll_array, len(fds), int(timeout))\n    if res <= 0:\n        return res, {}\n    return res, {item.fd: item.revents for item in poll_array}\n\n\ndef nn_recv(socket, *args):\n    \"receive a message\"\n    if len(args) == 1:\n        flags, = args\n        pointer = ctypes.c_void_p()\n        rtn = _nn_recv(socket, ctypes.byref(pointer), ctypes.c_size_t(-1),\n                       flags)\n        if rtn < 0:\n            return rtn, None\n        else:\n            return rtn, _create_message(pointer.value, rtn)\n    elif len(args) == 2:\n        msg_buf, flags = args\n        mv_buf = memoryview(msg_buf)\n        if mv_buf.readonly:\n            raise TypeError('Writable buffer is required')\n        rtn = _nn_recv(socket, ctypes.addressof(msg_buf), len(mv_buf), flags)\n        return rtn, msg_buf\n\n\nnn_device = _nn_device\nnn_device.__doc__ = \"start a device\"\n\nnn_term = _nn_term\nnn_term.__doc__ = \"notify all sockets about process termination\"\n\ntry:\n    if sys.platform in ('win32', 'cygwin'):\n        _nclib = ctypes.windll.nanoconfig\n    else:\n        _nclib = ctypes.cdll.LoadLibrary('libnanoconfig.so')\nexcept OSError:\n    pass # No nanoconfig, sorry\nelse:\n    # int nc_configure (int s, const char *addr)\n    nc_configure = _functype(ctypes.c_int, ctypes.c_int, ctypes.c_char_p)(\n        ('nc_configure', _nclib), ((1, 's'), (1, 'addr')))\n    nc_configure.__doc__ = \"configure socket using nanoconfig\"\n\n    # void nc_close(int s);\n    nc_close = _functype(None, ctypes.c_int)(\n        ('nc_close', _nclib), ((1, 's'),))\n    nc_close.__doc__ = \"close an SP socket configured with nn_configure\"\n\n    # void nc_term();\n    nc_term = _functype(None)(\n        ('nc_term', _nclib), ())\n    nc_term.__doc__ = \"shutdown nanoconfig worker thread\"\n"
  },
  {
    "path": "appveyor.yml",
    "content": "# The template for this file was from https://packaging.python.org/appveyor/\n\nenvironment:\n  matrix:\n    # For Python versions available on Appveyor, see\n    # http://www.appveyor.com/docs/installed-software#python\n    - PYTHON: \"C:\\\\Python27\"\n      CMAKE_GENERATOR: \"Visual Studio 9 2008\"\n    - PYTHON: \"C:\\\\Python34\"\n      CMAKE_GENERATOR: \"Visual Studio 10 2010\"\n    - PYTHON: \"C:\\\\Python35\"\n      CMAKE_GENERATOR: \"Visual Studio 14 2015\"\n    - PYTHON: \"C:\\\\Python36\"\n      CMAKE_GENERATOR: \"Visual Studio 14 2015\"\n    - PYTHON: \"C:\\\\Python27\"\n      CMAKE_GENERATOR: \"Visual Studio 9 2008 Win64\"  \n    - PYTHON: \"C:\\\\Python34-x64\"\n      CMAKE_GENERATOR: \"Visual Studio 10 2010 Win64\"\n    - PYTHON: \"C:\\\\Python35-x64\"\n      CMAKE_GENERATOR: \"Visual Studio 14 2015 Win64\"\n    - PYTHON: \"C:\\\\Python36-x64\"\n      CMAKE_GENERATOR: \"Visual Studio 14 2015 Win64\"\n\ninstall:\n  # We need wheel installed to build wheels\n  - \"%PYTHON%\\\\python.exe -m pip install wheel\"\n  # Visual Studio 9 2008 does not come with stdint.h, so we'll copy over a\n  # different version.  We only need to do it whenever we're building with\n  # 2008, but it doesn't hurt to copy it unconditionally.  The first copy is to\n  # build nanomsg, the second is to build the extension.\n  - ps: cp \"C:\\\\Program Files (x86)\\\\Microsoft Visual Studio 10.0\\\\VC\\\\include\\\\stdint.h\"\n           \"C:\\\\Program Files (x86)\\\\Microsoft Visual Studio 9.0\\\\VC\\\\include\\\\stdint.h\"\n  - ps: cp \"C:\\\\Program Files (x86)\\\\Microsoft Visual Studio 10.0\\\\VC\\\\include\\\\stdint.h\"\n           \"C:\\\\Users\\\\appveyor\\\\AppData\\\\Local\\\\Programs\\\\Common\\\\Microsoft\\\\Visual C++ for Python\\\\9.0\\\\VC\\include\\\\stdint.h\"\n  - git clone https://github.com/nanomsg/nanomsg.git nanomsg-src\n  - pwd\n  - ps: pushd nanomsg-src\n  - git checkout 1.0.0\n  - ps: mkdir build\n  - ps: cd build\n  - cmake -DNN_STATIC_LIB=ON  -G\"%CMAKE_GENERATOR%\" ..\n  - cmake --build .\n  - cmake --build . --target install\n  - ps: cp Debug\\nanomsg.lib ..\\..\n  - ps: popd\n  - pwd\n\nbuild_script:\n  - \"%PYTHON%\\\\python.exe setup.py install\"\n\ntest_script:\n  - \"build.cmd %PYTHON%\\\\python.exe setup.py test\"\n\nafter_test:\n  # build the wheel.\n  # build.cmd sets up necessary variables for 64-bit builds\n  - \"build.cmd %PYTHON%\\\\python.exe setup.py bdist_wheel\"\n\nartifacts:\n  # bdist_wheel puts your built wheel in the dist directory\n  - path: dist\\*\n\n#on_success:\n#  You can use this step to upload your artifacts to a public website.\n#  See Appveyor's documentation for more details. Or you can simply\n#  access your wheels from the Appveyor \"artifacts\" tab for your build.\n"
  },
  {
    "path": "build.cmd",
    "content": "@echo off\n:: To build extensions for 64 bit Python 3, we need to configure environment\n:: variables to use the MSVC 2010 C++ compilers from GRMSDKX_EN_DVD.iso of:\n:: MS Windows SDK for Windows 7 and .NET Framework 4\n::\n:: More details at:\n:: https://github.com/cython/cython/wiki/64BitCythonExtensionsOnWindows\n\nIF \"%DISTUTILS_USE_SDK%\"==\"1\" (\n    ECHO Configuring environment to build with MSVC on a 64bit architecture\n    ECHO Using Windows SDK 7.1\n    \"C:\\Program Files\\Microsoft SDKs\\Windows\\v7.1\\Setup\\WindowsSdkVer.exe\" -q -version:v7.1\n    CALL \"C:\\Program Files\\Microsoft SDKs\\Windows\\v7.1\\Bin\\SetEnv.cmd\" /x64 /release\n    SET MSSdk=1\n    REM Need the following to allow tox to see the SDK compiler\n    SET TOX_TESTENV_PASSENV=DISTUTILS_USE_SDK MSSdk INCLUDE LIB\n) ELSE (\n    ECHO Using default MSVC build environment\n)\n\nCALL %*\n"
  },
  {
    "path": "docs/Makefile",
    "content": "# Makefile for Sphinx documentation\n#\n\n# You can set these variables from the command line.\nSPHINXOPTS    =\nSPHINXBUILD   = sphinx-build\nPAPER         =\nBUILDDIR      = _build\n\n# User-friendly check for sphinx-build\nifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)\n$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)\nendif\n\n# Internal variables.\nPAPEROPT_a4     = -D latex_paper_size=a4\nPAPEROPT_letter = -D latex_paper_size=letter\nALLSPHINXOPTS   = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .\n# the i18n builder cannot share the environment and doctrees with the others\nI18NSPHINXOPTS  = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .\n\n.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext\n\nhelp:\n\t@echo \"Please use \\`make <target>' where <target> is one of\"\n\t@echo \"  html       to make standalone HTML files\"\n\t@echo \"  dirhtml    to make HTML files named index.html in directories\"\n\t@echo \"  singlehtml to make a single large HTML file\"\n\t@echo \"  pickle     to make pickle files\"\n\t@echo \"  json       to make JSON files\"\n\t@echo \"  htmlhelp   to make HTML files and a HTML help project\"\n\t@echo \"  qthelp     to make HTML files and a qthelp project\"\n\t@echo \"  devhelp    to make HTML files and a Devhelp project\"\n\t@echo \"  epub       to make an epub\"\n\t@echo \"  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter\"\n\t@echo \"  latexpdf   to make LaTeX files and run them through pdflatex\"\n\t@echo \"  latexpdfja to make LaTeX files and run them through platex/dvipdfmx\"\n\t@echo \"  text       to make text files\"\n\t@echo \"  man        to make manual pages\"\n\t@echo \"  texinfo    to make Texinfo files\"\n\t@echo \"  info       to make Texinfo files and run them through makeinfo\"\n\t@echo \"  gettext    to make PO message catalogs\"\n\t@echo \"  changes    to make an overview of all changed/added/deprecated items\"\n\t@echo \"  xml        to make Docutils-native XML files\"\n\t@echo \"  pseudoxml  to make pseudoxml-XML files for display purposes\"\n\t@echo \"  linkcheck  to check all external links for integrity\"\n\t@echo \"  doctest    to run all doctests embedded in the documentation (if enabled)\"\n\nclean:\n\trm -rf $(BUILDDIR)/*\n\nhtml:\n\t$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html\n\t@echo\n\t@echo \"Build finished. The HTML pages are in $(BUILDDIR)/html.\"\n\ndirhtml:\n\t$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml\n\t@echo\n\t@echo \"Build finished. The HTML pages are in $(BUILDDIR)/dirhtml.\"\n\nsinglehtml:\n\t$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml\n\t@echo\n\t@echo \"Build finished. The HTML page is in $(BUILDDIR)/singlehtml.\"\n\npickle:\n\t$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle\n\t@echo\n\t@echo \"Build finished; now you can process the pickle files.\"\n\njson:\n\t$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json\n\t@echo\n\t@echo \"Build finished; now you can process the JSON files.\"\n\nhtmlhelp:\n\t$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp\n\t@echo\n\t@echo \"Build finished; now you can run HTML Help Workshop with the\" \\\n\t      \".hhp project file in $(BUILDDIR)/htmlhelp.\"\n\nqthelp:\n\t$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp\n\t@echo\n\t@echo \"Build finished; now you can run \"qcollectiongenerator\" with the\" \\\n\t      \".qhcp project file in $(BUILDDIR)/qthelp, like this:\"\n\t@echo \"# qcollectiongenerator $(BUILDDIR)/qthelp/nanomsg-python.qhcp\"\n\t@echo \"To view the help file:\"\n\t@echo \"# assistant -collectionFile $(BUILDDIR)/qthelp/nanomsg-python.qhc\"\n\ndevhelp:\n\t$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp\n\t@echo\n\t@echo \"Build finished.\"\n\t@echo \"To view the help file:\"\n\t@echo \"# mkdir -p $$HOME/.local/share/devhelp/nanomsg-python\"\n\t@echo \"# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/nanomsg-python\"\n\t@echo \"# devhelp\"\n\nepub:\n\t$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub\n\t@echo\n\t@echo \"Build finished. The epub file is in $(BUILDDIR)/epub.\"\n\nlatex:\n\t$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex\n\t@echo\n\t@echo \"Build finished; the LaTeX files are in $(BUILDDIR)/latex.\"\n\t@echo \"Run \\`make' in that directory to run these through (pdf)latex\" \\\n\t      \"(use \\`make latexpdf' here to do that automatically).\"\n\nlatexpdf:\n\t$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex\n\t@echo \"Running LaTeX files through pdflatex...\"\n\t$(MAKE) -C $(BUILDDIR)/latex all-pdf\n\t@echo \"pdflatex finished; the PDF files are in $(BUILDDIR)/latex.\"\n\nlatexpdfja:\n\t$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex\n\t@echo \"Running LaTeX files through platex and dvipdfmx...\"\n\t$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja\n\t@echo \"pdflatex finished; the PDF files are in $(BUILDDIR)/latex.\"\n\ntext:\n\t$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text\n\t@echo\n\t@echo \"Build finished. The text files are in $(BUILDDIR)/text.\"\n\nman:\n\t$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man\n\t@echo\n\t@echo \"Build finished. The manual pages are in $(BUILDDIR)/man.\"\n\ntexinfo:\n\t$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo\n\t@echo\n\t@echo \"Build finished. The Texinfo files are in $(BUILDDIR)/texinfo.\"\n\t@echo \"Run \\`make' in that directory to run these through makeinfo\" \\\n\t      \"(use \\`make info' here to do that automatically).\"\n\ninfo:\n\t$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo\n\t@echo \"Running Texinfo files through makeinfo...\"\n\tmake -C $(BUILDDIR)/texinfo info\n\t@echo \"makeinfo finished; the Info files are in $(BUILDDIR)/texinfo.\"\n\ngettext:\n\t$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale\n\t@echo\n\t@echo \"Build finished. The message catalogs are in $(BUILDDIR)/locale.\"\n\nchanges:\n\t$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes\n\t@echo\n\t@echo \"The overview file is in $(BUILDDIR)/changes.\"\n\nlinkcheck:\n\t$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck\n\t@echo\n\t@echo \"Link check complete; look for any errors in the above output \" \\\n\t      \"or in $(BUILDDIR)/linkcheck/output.txt.\"\n\ndoctest:\n\t$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest\n\t@echo \"Testing of doctests in the sources finished, look at the \" \\\n\t      \"results in $(BUILDDIR)/doctest/output.txt.\"\n\nxml:\n\t$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml\n\t@echo\n\t@echo \"Build finished. The XML files are in $(BUILDDIR)/xml.\"\n\npseudoxml:\n\t$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml\n\t@echo\n\t@echo \"Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml.\"\n"
  },
  {
    "path": "docs/conf.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# nanomsg-python documentation build configuration file, created by\n# sphinx-quickstart on Fri Jan 23 17:17:17 2015.\n#\n# This file is execfile()d with the current directory set to its\n# containing dir.\n#\n# Note that not all possible configuration values are present in this\n# autogenerated file.\n#\n# All configuration values have a default; values that are commented out\n# serve to show the default.\n\nimport sys\nimport os\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#sys.path.insert(0, os.path.abspath('.'))\n\n# -- General configuration ------------------------------------------------\n\n# If your documentation needs a minimal Sphinx version, state it here.\n#needs_sphinx = '1.0'\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n    'sphinx.ext.autodoc',\n]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# The suffix of source filenames.\nsource_suffix = '.rst'\n\n# The encoding of source files.\n#source_encoding = 'utf-8-sig'\n\n# The master toctree document.\nmaster_doc = 'index'\n\n# General information about the project.\nproject = u'nanomsg-python'\ncopyright = u'2015, Tony Simpson <agjasimpson@gmail.com>'\n\n# The version info for the project you're documenting, acts as replacement for\n# |version| and |release|, also used in various other places throughout the\n# built documents.\n#\n# The short X.Y version.\nversion = '1.0'\n# The full version, including alpha/beta/rc tags.\nrelease = '1.0'\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#language = None\n\n# There are two options for replacing |today|: either, you set today to some\n# non-false value, then it is used:\n#today = ''\n# Else, today_fmt is used as the format for a strftime call.\n#today_fmt = '%B %d, %Y'\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\nexclude_patterns = ['_build']\n\n# The reST default role (used for this markup: `text`) to use for all\n# documents.\n#default_role = None\n\n# If true, '()' will be appended to :func: etc. cross-reference text.\n#add_function_parentheses = True\n\n# If true, the current module name will be prepended to all description\n# unit titles (such as .. function::).\n#add_module_names = True\n\n# If true, sectionauthor and moduleauthor directives will be shown in the\n# output. They are ignored by default.\n#show_authors = False\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = 'sphinx'\n\n# A list of ignored prefixes for module index sorting.\n#modindex_common_prefix = []\n\n# If true, keep warnings as \"system message\" paragraphs in the built documents.\n#keep_warnings = False\n\n\n# -- Options for HTML output ----------------------------------------------\n\n# The theme to use for HTML and HTML Help pages.  See the documentation for\n# a list of builtin themes.\nhtml_theme = 'default'\n\n# Theme options are theme-specific and customize the look and feel of a theme\n# further.  For a list of options available for each theme, see the\n# documentation.\n#html_theme_options = {}\n\n# Add any paths that contain custom themes here, relative to this directory.\n#html_theme_path = []\n\n# The name for this set of Sphinx documents.  If None, it defaults to\n# \"<project> v<release> documentation\".\n#html_title = None\n\n# A shorter title for the navigation bar.  Default is the same as html_title.\n#html_short_title = None\n\n# The name of an image file (relative to this directory) to place at the top\n# of the sidebar.\n#html_logo = None\n\n# The name of an image file (within the static path) to use as favicon of the\n# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32\n# pixels large.\n#html_favicon = None\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = ['_static']\n\n# Add any extra paths that contain custom files (such as robots.txt or\n# .htaccess) here, relative to this directory. These files are copied\n# directly to the root of the documentation.\n#html_extra_path = []\n\n# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,\n# using the given strftime format.\n#html_last_updated_fmt = '%b %d, %Y'\n\n# If true, SmartyPants will be used to convert quotes and dashes to\n# typographically correct entities.\n#html_use_smartypants = True\n\n# Custom sidebar templates, maps document names to template names.\n#html_sidebars = {}\n\n# Additional templates that should be rendered to pages, maps page names to\n# template names.\n#html_additional_pages = {}\n\n# If false, no module index is generated.\n#html_domain_indices = True\n\n# If false, no index is generated.\n#html_use_index = True\n\n# If true, the index is split into individual pages for each letter.\n#html_split_index = False\n\n# If true, links to the reST sources are added to the pages.\n#html_show_sourcelink = True\n\n# If true, \"Created using Sphinx\" is shown in the HTML footer. Default is True.\n#html_show_sphinx = True\n\n# If true, \"(C) Copyright ...\" is shown in the HTML footer. Default is True.\n#html_show_copyright = True\n\n# If true, an OpenSearch description file will be output, and all pages will\n# contain a <link> tag referring to it.  The value of this option must be the\n# base URL from which the finished HTML is served.\n#html_use_opensearch = ''\n\n# This is the file name suffix for HTML files (e.g. \".xhtml\").\n#html_file_suffix = None\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = 'nanomsg-pythondoc'\n\n\n# -- Options for LaTeX output ---------------------------------------------\n\nlatex_elements = {\n# The paper size ('letterpaper' or 'a4paper').\n#'papersize': 'letterpaper',\n\n# The font size ('10pt', '11pt' or '12pt').\n#'pointsize': '10pt',\n\n# Additional stuff for the LaTeX preamble.\n#'preamble': '',\n}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title,\n#  author, documentclass [howto, manual, or own class]).\nlatex_documents = [\n  ('index', 'nanomsg-python.tex', u'nanomsg-python Documentation',\n   u'Tony Simpson \\\\textless{}agjasimpson@gmail.com\\\\textgreater{}', 'manual'),\n]\n\n# The name of an image file (relative to this directory) to place at the top of\n# the title page.\n#latex_logo = None\n\n# For \"manual\" documents, if this is true, then toplevel headings are parts,\n# not chapters.\n#latex_use_parts = False\n\n# If true, show page references after internal links.\n#latex_show_pagerefs = False\n\n# If true, show URL addresses after external links.\n#latex_show_urls = False\n\n# Documents to append as an appendix to all manuals.\n#latex_appendices = []\n\n# If false, no module index is generated.\n#latex_domain_indices = True\n\n\n# -- Options for manual page output ---------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [\n    ('index', 'nanomsg-python', u'nanomsg-python Documentation',\n     [u'Tony Simpson <agjasimpson@gmail.com>'], 1)\n]\n\n# If true, show URL addresses after external links.\n#man_show_urls = False\n\n\n# -- Options for Texinfo output -------------------------------------------\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n#  dir menu entry, description, category)\ntexinfo_documents = [\n  ('index', 'nanomsg-python', u'nanomsg-python Documentation',\n   u'Tony Simpson <agjasimpson@gmail.com>', 'nanomsg-python', 'One line description of project.',\n   'Miscellaneous'),\n]\n\n# Documents to append as an appendix to all manuals.\n#texinfo_appendices = []\n\n# If false, no module index is generated.\n#texinfo_domain_indices = True\n\n# How to display URL addresses: 'footnote', 'no', or 'inline'.\n#texinfo_show_urls = 'footnote'\n\n# If true, do not generate a @detailmenu in the \"Top\" node's menu.\n#texinfo_no_detailmenu = False\n"
  },
  {
    "path": "docs/index.rst",
    "content": "Welcome to nanomsg-python's documentation!\n==========================================\n\n.. automodule:: nanomsg\n    :members:\n    :inherited-members:\n    :undoc-members:\n\n.. automodule:: nanomsg_wrappers\n    :members:\n    :inherited-members:\n    :undoc-members:\n\n\nIndices and tables\n==================\n\n* :ref:`genindex`\n* :ref:`modindex`\n* :ref:`search`\n\n"
  },
  {
    "path": "nanomsg/__init__.py",
    "content": "from __future__ import division, absolute_import, print_function, unicode_literals\n\nfrom .version import __version__\nfrom struct import Struct as _Struct\nimport warnings\n\nfrom . import wrapper\n\ntry:\n    buffer\nexcept NameError:\n    buffer = memoryview  # py3\n\nnanoconfig_started = False\n\n#Import constants into module with NN_ prefix stripped\nfor name, value in wrapper.nn_symbols():\n    if name.startswith('NN_'):\n        name = name[3:]\n    globals()[name] = value\n\n\nif hasattr(wrapper, 'create_writable_buffer'):\n    create_writable_buffer = wrapper.create_writable_buffer\nelse:\n    def create_writable_buffer(size):\n        \"\"\"Returns a writable buffer\"\"\"\n        return bytearray(size)\n\n\ndef create_message_buffer(size, type):\n    \"\"\"Create a message buffer\"\"\"\n    rtn = wrapper.nn_allocmsg(size, type)\n    if rtn is None:\n        raise NanoMsgAPIError()\n    return rtn\n\n\nclass NanoMsgError(Exception):\n    \"\"\"Base Exception for all errors in the nanomsg python package\n\n    \"\"\"\n    pass\n\n\nclass NanoMsgAPIError(NanoMsgError):\n    \"\"\"Exception for all errors reported by the C API.\n\n    msg and errno are from nanomsg C library.\n\n    \"\"\"\n    __slots__ = ('msg', 'errno')\n\n    def __init__(self):\n        errno = wrapper.nn_errno()\n        msg = wrapper.nn_strerror(errno)\n        NanoMsgError.__init__(self, msg)\n        self.errno, self.msg = errno, msg\n\n\ndef _nn_check_positive_rtn(rtn):\n    if rtn < 0:\n        raise NanoMsgAPIError()\n    return rtn\n\n\nclass Device(object):\n    \"\"\"Create a nanomsg device to relay messages between sockets.\n\n    If only one socket is supplied the device loops messages on that socket.\n    \"\"\"\n    def __init__(self, socket1, socket2=None):\n        self._fd1 = socket1.fd\n        self._fd2 = -1 if socket2 is None else socket2.fd\n\n    def start(self):\n        \"\"\"Run the device in the current thread.\n\n        This will not return until the device stops due to error or\n        termination.\n        \"\"\"\n        _nn_check_positive_rtn(wrapper.nn_device(self._fd1, self._fd2))\n\n\ndef terminate_all():\n    \"\"\"Close all sockets and devices\"\"\"\n    global nanoconfig_started\n    if nanoconfig_started:\n        wrapper.nc_term()\n        nanoconfig_started = False\n    wrapper.nn_term()\n\n\ndef poll(in_sockets, out_sockets, timeout=-1):\n    \"\"\"\n    Poll a list of sockets\n    :param in_sockets: sockets for reading\n    :param out_sockets: sockets for writing\n    :param timeout: poll timeout in seconds, -1 is infinite wait\n    :return: tuple (read socket list, write socket list)\n    \"\"\"\n    sockets = {}\n    # reverse map fd => socket\n    fd_sockets = {}\n    for s in in_sockets:\n        sockets[s.fd] = POLLIN\n        fd_sockets[s.fd] = s\n    for s in out_sockets:\n        modes = sockets.get(s.fd, 0)\n        sockets[s.fd] = modes | POLLOUT\n        fd_sockets[s.fd] = s\n\n    # convert to milliseconds or -1\n    if timeout >= 0:\n        timeout_ms = int(timeout*1000)\n    else:\n        timeout_ms = -1\n    res, sockets = wrapper.nn_poll(sockets, timeout_ms)\n    _nn_check_positive_rtn(res)\n    read_list, write_list = [], []\n    for fd, result in sockets.items():\n        if (result & POLLIN) != 0:\n            read_list.append(fd_sockets[fd])\n        if (result & POLLOUT) != 0:\n            write_list.append(fd_sockets[fd])\n\n    return read_list, write_list\n\n\nclass Socket(object):\n    \"\"\"Class wrapping nanomsg socket.\n\n    protocol should be a nanomsg protocol constant e.g. nanomsg.PAIR\n\n    This class supports being used as a context manager which should guarantee\n    it is closed.\n\n    e.g.:\n        import time\n        from nanomsg import PUB, Socket\n\n        with Socket(PUB) as pub_socket:\n            pub_socket.bind('tcp://127.0.0.1:49234')\n            for i in range(100):\n                pub_socket.send(b'hello all')\n                time.sleep(0.5)\n        #pub_socket is closed\n\n    Socket.bind and Socket.connect return subclass of Endpoint which allow\n    you to shutdown selected endpoints.\n\n    The constructor also allows you to wrap existing sockets by passing in the\n    socket fd instead of the protocol e.g.:\n        from nanomsg import AF_SP, PAIR, Socket\n        from nanomsg import wrapper as nn\n\n        socket_fd = nn.nn_socket(AF_SP, PAIR)\n        socket = Socket(socket_fd=socket_fd)\n\n    \"\"\"\n\n    _INT_PACKER = _Struct(str('i'))\n\n    class _Endpoint(object):\n        def __init__(self, socket, endpoint_id, address):\n            self._endpoint_id = endpoint_id\n            self._fdocket = socket\n            self._address = address\n\n        @property\n        def address(self):\n            return self._address\n\n        def shutdown(self):\n            self._fdocket._endpoints.remove(self)\n            _nn_check_positive_rtn(wrapper.nn_shutdown(self._fdocket._fd,\n                                               self._endpoint_id))\n\n        def __repr__(self):\n            return '<%s socket %r, id %r, address %r>' % (\n                self.__class__.__name__,\n                self._fdocket,\n                self._endpoint_id,\n                self._address\n            )\n\n    class BindEndpoint(_Endpoint):\n        pass\n\n    class ConnectEndpoint(_Endpoint):\n        pass\n\n    class NanoconfigEndpoint(_Endpoint):\n\n        def shutdown(self):\n            raise NotImplementedError(\n                \"Shutdown of nanoconfig endpoint is not supported\")\n\n    def __init__(self, protocol=None, socket_fd=None, domain=AF_SP):\n        if protocol is not None and socket_fd is not None:\n            raise NanoMsgError('Only one of protocol or socket_fd should be '\n                               'passed to the Socket constructor')\n        if protocol is not None:\n            self._fd = _nn_check_positive_rtn(\n                wrapper.nn_socket(domain, protocol)\n            )\n        else:\n            self._fd = socket_fd\n        self._endpoints = []\n\n    def _get_send_fd(self):\n        return self.get_int_option(SOL_SOCKET, SNDFD)\n\n    def _get_recv_fd(self):\n        return self.get_int_option(SOL_SOCKET, RCVFD)\n\n    def _get_linger(self):\n        return self.get_int_option(SOL_SOCKET, LINGER)\n\n    def _set_linger(self, value):\n        return self.set_int_option(SOL_SOCKET, LINGER, value)\n\n    def _get_send_buffer_size(self):\n        return self.get_int_option(SOL_SOCKET, SNDBUF)\n\n    def _set_send_buffer_size(self, value):\n        return self.set_int_option(SOL_SOCKET, SNDBUF, value)\n\n    def _get_recv_buffer_size(self):\n        return self.get_int_option(SOL_SOCKET, RCVBUF)\n\n    def _set_recv_buffer_size(self, value):\n        return self.set_int_option(SOL_SOCKET, RCVBUF, value)\n\n    def _get_send_timeout(self):\n        return self.get_int_option(SOL_SOCKET, SNDTIMEO)\n\n    def _set_send_timeout(self, value):\n        return self.set_int_option(SOL_SOCKET, SNDTIMEO, value)\n\n    def _get_recv_timeout(self):\n        return self.get_int_option(SOL_SOCKET, RCVTIMEO)\n\n    def _set_recv_timeout(self, value):\n        return self.set_int_option(SOL_SOCKET, RCVTIMEO, value)\n\n    def _get_reconnect_interval(self):\n        return self.get_int_option(SOL_SOCKET, RECONNECT_IVL)\n\n    def _set_reconnect_interval(self, value):\n        return self.set_int_option(SOL_SOCKET, RECONNECT_IVL, value)\n\n    def _get_reconnect_interval_max(self):\n        return self.get_int_option(SOL_SOCKET, RECONNECT_IVL_MAX)\n\n    def _set_reconnect_interval_max(self, value):\n        return self.set_int_option(SOL_SOCKET, RECONNECT_IVL_MAX, value)\n\n    send_fd = property(_get_send_fd, doc='Send file descripter')\n    recv_fd = property(_get_recv_fd, doc='Receive file descripter')\n    linger  = property(_get_linger, _set_linger, doc='Socket linger in '\n                       'milliseconds (0.001 seconds)')\n    recv_buffer_size = property(_get_recv_buffer_size, _set_recv_buffer_size,\n                                doc='Receive buffer size in bytes')\n    send_buffer_size = property(_get_send_buffer_size, _set_send_buffer_size,\n                                doc='Send buffer size in bytes')\n    send_timeout = property(_get_send_timeout, _set_send_timeout,\n                            doc='Send timeout in milliseconds (0.001 seconds)')\n    recv_timeout = property(_get_recv_timeout, _set_recv_timeout,\n                            doc='Receive timeout in milliseconds (0.001 '\n                            'seconds)')\n    reconnect_interval = property(\n        _get_reconnect_interval,\n        _set_reconnect_interval,\n        doc='Base interval between connection failure and reconnect'\n        ' attempt in milliseconds (0.001 seconds).'\n    )\n    reconnect_interval_max = property(\n        _get_reconnect_interval_max,\n        _set_reconnect_interval_max,\n        doc='Max reconnect interval - see C API documentation.'\n    )\n\n    @property\n    def fd(self):\n        \"\"\"Socket file descripter.\n\n        Note this is not an OS file descripter (see .send_fd, .recv_fd).\n        \"\"\"\n        return self._fd\n\n    @property\n    def endpoints(self):\n        \"\"\"Endpoints list\n\n        \"\"\"\n        return list(self._endpoints)\n\n    @property\n    def uses_nanoconfig(self):\n        return (self._endpoints and\n            isinstance(self._endpoints[0], Socket.NanoconfigEndpoint))\n\n    def bind(self, address):\n        \"\"\"Add a local endpoint to the socket\"\"\"\n        if self.uses_nanoconfig:\n            raise ValueError(\"Nanoconfig address must be sole endpoint\")\n        endpoint_id = _nn_check_positive_rtn(\n            wrapper.nn_bind(self._fd, address)\n        )\n        ep = Socket.BindEndpoint(self, endpoint_id, address)\n        self._endpoints.append(ep)\n        return ep\n\n    def connect(self, address):\n        \"\"\"Add a remote endpoint to the socket\"\"\"\n        if self.uses_nanoconfig:\n            raise ValueError(\"Nanoconfig address must be sole endpoint\")\n        endpoint_id = _nn_check_positive_rtn(\n            wrapper.nn_connect(self.fd, address)\n        )\n        ep = Socket.ConnectEndpoint(self, endpoint_id, address)\n        self._endpoints.append(ep)\n        return ep\n\n    def configure(self, address):\n        \"\"\"Configure socket's addresses with nanoconfig\"\"\"\n        global nanoconfig_started\n        if len(self._endpoints):\n            raise ValueError(\"Nanoconfig address must be sole endpoint\")\n        endpoint_id = _nn_check_positive_rtn(\n            wrapper.nc_configure(self.fd, address)\n        )\n        if not nanoconfig_started:\n            nanoconfig_started = True\n        ep = Socket.NanoconfigEndpoint(self, endpoint_id, address)\n        self._endpoints.append(ep)\n        return ep\n\n    def close(self):\n        \"\"\"Close the socket\"\"\"\n        if self.is_open():\n            fd = self._fd\n            self._fd = -1\n            if self.uses_nanoconfig:\n                wrapper.nc_close(fd)\n            else:\n                _nn_check_positive_rtn(wrapper.nn_close(fd))\n\n    def is_open(self):\n        \"\"\"Returns true if the socket has a valid socket id.\n\n        If the underlying socket is closed by some other means than\n        Socket.close this method may return True when the socket is actually\n        closed.\n        \"\"\"\n        return self.fd >= 0\n\n    def recv(self, buf=None, flags=0):\n        \"\"\"Recieve a message.\"\"\"\n        if buf is None:\n            rtn, out_buf = wrapper.nn_recv(self.fd, flags)\n        else:\n            rtn, out_buf = wrapper.nn_recv(self.fd, buf, flags)\n        _nn_check_positive_rtn(rtn)\n        return bytes(buffer(out_buf))[:rtn]\n\n    def set_string_option(self, level, option, value):\n        _nn_check_positive_rtn(wrapper.nn_setsockopt(self.fd, level, option,\n                               value))\n\n    def set_int_option(self, level, option, value):\n        buf = create_writable_buffer(Socket._INT_PACKER.size)\n        Socket._INT_PACKER.pack_into(buf, 0, value)\n        _nn_check_positive_rtn(wrapper.nn_setsockopt(self.fd, level, option,\n                                                     buf))\n\n    def get_int_option(self, level, option):\n        size = Socket._INT_PACKER.size\n        buf = create_writable_buffer(size)\n        rtn, length = wrapper.nn_getsockopt(self._fd, level, option, buf)\n        _nn_check_positive_rtn(rtn)\n        if length != size:\n            raise NanoMsgError(('Returned option size (%r) should be the same'\n                                ' as size of int (%r)') % (length, size))\n        return Socket._INT_PACKER.unpack_from(buffer(buf))[0]\n\n    def get_string_option(self, level, option, max_len=16*1024):\n        buf = create_writable_buffer(max_len)\n        rtn, length = wrapper.nn_getsockopt(self._fd, level, option, buf)\n        _nn_check_positive_rtn(rtn)\n        return bytes(buffer(buf))[:length]\n\n    def send(self, msg, flags=0):\n        \"\"\"Send a message\"\"\"\n        _nn_check_positive_rtn(wrapper.nn_send(self.fd, msg, flags))\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, *args):\n        self.close()\n\n    def __repr__(self):\n        return '<%s fd %r, connected to %r, bound to %r>' % (\n            self.__class__.__name__,\n            self.fd,\n            [i.address for i in self.endpoints if type(i) is\n             Socket.ConnectEndpoint],\n            [i.address for i in self.endpoints if type(i) is\n             Socket.BindEndpoint],\n        )\n\n    def __del__(self):\n        try:\n            self.close()\n        except NanoMsgError:\n            pass\n"
  },
  {
    "path": "nanomsg/version.py",
    "content": "\n__version__ = '1.0'\n"
  },
  {
    "path": "nanomsg/wrapper.py",
    "content": "from __future__ import division, absolute_import, print_function, unicode_literals\n\nfrom nanomsg_wrappers import load_wrapper as _load_wrapper\n_wrapper = _load_wrapper()\n\nglobals().update(_wrapper.__dict__)\n"
  },
  {
    "path": "nanomsg_wrappers/__init__.py",
    "content": "from __future__ import division, absolute_import, print_function, unicode_literals\n\nfrom platform import python_implementation\nimport pkgutil\nimport importlib\nimport warnings\n\n_choice = None\n\ndef set_wrapper_choice(name):\n    global _choice\n    _choice = name\n\ndef load_wrapper():\n    if _choice is not None:\n        return importlib.import_module('_nanomsg_' + _choice)\n    default = get_default_for_platform()\n    try:\n        return importlib.import_module('_nanomsg_' + default)\n    except ImportError:\n        warnings.warn((\"Could not load the default wrapper for your platform: \"\n                       \"%s, performance may be affected!\") % (default,))\n    return importlib.import_module('_nanomsg_ctypes')\n\ndef get_default_for_platform():\n    if python_implementation() == 'CPython':\n        return 'cpy'\n    else:\n        return 'ctypes'\n\n\ndef list_wrappers():\n    return [module_name.split('_',2)[-1] for _, module_name, _ in\n     pkgutil.iter_modules() if module_name.startswith('_nanomsg_')]\n"
  },
  {
    "path": "setup.py",
    "content": "from __future__ import division, absolute_import, print_function, unicode_literals\n\nimport os\nimport platform\nimport sys\nfrom setuptools import setup\nfrom distutils.core import Extension\nfrom distutils.command.build_ext import build_ext\n\n\nwith open(os.path.join('nanomsg','version.py')) as f:\n    exec(f.read())\n\n\nlibraries = [str('nanomsg')]\n# add additional necessary library/include path info if we're on Windows\nif sys.platform in (\"win32\", \"cygwin\"):\n    libraries.extend([str('ws2_32'), str('advapi32'), str('mswsock')])\n    # nanomsg installs to different directory based on architecture\n    arch = platform.architecture()[0]\n    if arch == \"64bit\":\n        include_dirs=[r'C:\\Program Files\\nanomsg\\include',]\n    else:\n        include_dirs=[r'C:\\Program Files (x86)\\nanomsg\\include',]\nelse:\n    include_dirs = None\n\ntry:\n    import ctypes\n    if sys.platform in ('win32', 'cygwin'):\n        _lib = ctypes.windll.nanoconfig\n    elif sys.platform == 'darwin':\n        _lib = ctypes.cdll.LoadLibrary('libnanoconfig.dylib')\n    else:\n        _lib = ctypes.cdll.LoadLibrary('libnanoconfig.so')\nexcept OSError:\n    # Building without nanoconfig; need to turn NN_STATIC_LIB on\n    define_macros = [('NN_STATIC_LIB','ON')]\nelse:\n    # Building with nanoconfig\n    libraries.append(str('nanoconfig'))\n    define_macros = [('WITH_NANOCONFIG', '1')]\n\ncpy_extension = Extension(str('_nanomsg_cpy'),\n                    define_macros=define_macros,\n                    sources=[str('_nanomsg_cpy/wrapper.c')],\n                    libraries=libraries,\n                    include_dirs=include_dirs,\n                    )\ninstall_requires = []\n\ntry:\n    import importlib\nexcept ImportError:\n    install_requires.append('importlib')\n\n\nsetup(\n    name='nanomsg',\n    version=__version__,\n    packages=[str('nanomsg'), str('_nanomsg_ctypes'), str('nanomsg_wrappers')],\n    ext_modules=[cpy_extension],\n    install_requires=install_requires,\n    description='Python library for nanomsg.',\n    classifiers=[\n        \"Development Status :: 3 - Alpha\",\n        \"Intended Audience :: Developers\",\n        \"Programming Language :: Python\",\n        \"Programming Language :: Python :: 2\",\n        \"Programming Language :: Python :: 2.6\",\n        \"Programming Language :: Python :: 2.7\",\n        \"Programming Language :: Python :: 3\",\n        \"Programming Language :: Python :: 3.2\",\n        \"Programming Language :: Python :: 3.3\",\n    ],\n    author='Tony Simpson',\n    author_email='agjasimpson@gmail.com',\n    url='https://github.com/tonysimpson/nanomsg-python',\n    keywords=['nanomsg', 'driver'],\n    license='MIT',\n    test_suite=\"tests\",\n)\n"
  },
  {
    "path": "test_utils/soaktest.py",
    "content": "import os\nfrom nanomsg_wrappers import set_wrapper_choice, get_default_for_platform\nset_wrapper_choice(os.environ.get('NANOMSG_PY_TEST_WRAPPER',\n                                  get_default_for_platform()))\n\nfrom nanomsg import (\n    SUB,\n    PUB,\n    SUB_SUBSCRIBE,\n    Socket\n)\n\nSOCKET_ADDRESS = os.environ.get('NANOMSG_PY_TEST_ADDRESS', \"inproc://a\")\n\nfrom nanomsg import Socket, BUS, PAIR\nimport sys\nimport random\nfrom itertools import count\n\nwith Socket(PAIR) as socket1:\n    with Socket(PAIR) as socket2:\n        socket1.bind(SOCKET_ADDRESS)\n        socket2.connect(SOCKET_ADDRESS)\n        for i in count(1):\n            msg = b''.join(chr(random.randint(0,255)) for i in range(1024*1024))\n            socket1.send(msg)\n            res = socket2.recv()\n            print i\n            if msg != res:\n                for num, (c1, c2) in enumerate(zip(msg, res)):\n                    if c1 != c2:\n                        print 'diff at', num, repr(c1), repr(c2)\n                        sys.exit()\n\n\n\n\n\n"
  },
  {
    "path": "test_utils/throughput.py",
    "content": "from __future__ import division, absolute_import, print_function,\\\n unicode_literals\nimport os\nfrom nanomsg_wrappers import set_wrapper_choice, get_default_for_platform\nWRAPPER = os.environ.get('NANOMSG_PY_TEST_WRAPPER', get_default_for_platform())\nset_wrapper_choice(WRAPPER)\n\nfrom nanomsg import (\n    PAIR,\n    Socket,\n    create_message_buffer\n)\n\nfrom nanomsg.wrapper import (\n    nn_send,\n    nn_recv\n)\n\nSOCKET_ADDRESS = os.environ.get('NANOMSG_PY_TEST_ADDRESS', \"inproc://a\")\nimport time\nBUFFER_SIZE = eval(os.environ.get('NANOMSG_PY_TEST_BUFFER_SIZE', \"1024\"))\n\nmsg = create_message_buffer(BUFFER_SIZE, 0)\n\nDURATION = 10\n\nprint(('Working NANOMSG_PY_TEST_BUFFER_SIZE %d NANOMSG_PY_TEST_WRAPPER %r '\n       'NANOMSG_PY_TEST_ADDRESS %r') % (BUFFER_SIZE, WRAPPER, SOCKET_ADDRESS))\ncount = 0\nstart_t = time.time()\nwith Socket(PAIR) as socket1:\n    with Socket(PAIR) as socket2:\n        socket1.bind(SOCKET_ADDRESS)\n        socket2.connect(SOCKET_ADDRESS)\n        while time.time() < start_t + DURATION:\n            c = chr(count % 255)\n            memoryview(msg)[0] = c\n            socket1.send(msg)\n            res = socket2.recv(msg)\n            assert res[0] == c\n            count += 1\n        stop_t = time.time()\n\nprint('Socket API throughput with checks - %f Mb/Second' % ((count * BUFFER_SIZE) / (stop_t - start_t) / 1024,))\n\ncount = 0\nstart_t = time.time()\nwith Socket(PAIR) as socket1:\n    with Socket(PAIR) as socket2:\n        socket1.bind(SOCKET_ADDRESS)\n        socket2.connect(SOCKET_ADDRESS)\n        while time.time() < start_t + DURATION:\n            nn_send(socket1.fd, msg, 0)\n            nn_recv(socket2.fd, msg, 0)\n            count += 1\n        stop_t = time.time()\nprint('Raw thoughtput no checks          - %f Mb/Second' % ((count * BUFFER_SIZE) / (stop_t - start_t) / 1024,))\n"
  },
  {
    "path": "tests/__init__.py",
    "content": ""
  },
  {
    "path": "tests/test_general_socket_methods.py",
    "content": "import unittest\nimport os\n\nfrom nanomsg_wrappers import set_wrapper_choice, get_default_for_platform\nset_wrapper_choice(os.environ.get('NANOMSG_PY_TEST_WRAPPER',\n                                  get_default_for_platform()))\n\nfrom nanomsg import (\n    PAIR,\n    Socket,\n    SNDBUF,\n    SOL_SOCKET\n)\n\nSOCKET_ADDRESS = os.environ.get('NANOMSG_PY_TEST_ADDRESS', \"inproc://a\")\n\n\nclass TestGeneralSocketMethods(unittest.TestCase):\n    def setUp(self):\n        self.socket = Socket(PAIR)\n\n    def tearDown(self):\n        self.socket.close()\n\n    def test_bind(self):\n        endpoint = self.socket.bind(SOCKET_ADDRESS)\n\n        self.assertNotEqual(None, endpoint)\n\n    def test_connect(self):\n        endpoint = self.socket.connect(SOCKET_ADDRESS)\n\n        self.assertNotEqual(None, endpoint)\n\n    def test_is_open_is_true_when_open(self):\n        self.assertTrue(self.socket.is_open())\n\n    def test_is_open_is_false_when_closed(self):\n        self.socket.close()\n\n        self.assertFalse(self.socket.is_open())\n\n    def test_set_and_get_int_option(self):\n        expected = 500\n\n        self.socket.set_int_option(SOL_SOCKET, SNDBUF, expected)\n\n        actual = self.socket.get_int_option(SOL_SOCKET, SNDBUF)\n        self.assertEqual(expected, actual)\n\n\nif __name__ == '__main__':\n    unittest.main()\n"
  },
  {
    "path": "tests/test_pair.py",
    "content": "import unittest\nimport os\n\nfrom nanomsg_wrappers import set_wrapper_choice, get_default_for_platform\nset_wrapper_choice(os.environ.get('NANOMSG_PY_TEST_WRAPPER',\n                                  get_default_for_platform()))\n\nfrom nanomsg import (\n    PAIR,\n    Socket\n)\n\nSOCKET_ADDRESS = os.environ.get('NANOMSG_PY_TEST_ADDRESS', \"inproc://a\")\n\n\nclass TestPairSockets(unittest.TestCase):\n    def test_send_recv(self):\n        with Socket(PAIR) as s1:\n            with Socket(PAIR) as s2:\n                s1.bind(SOCKET_ADDRESS)\n                s2.connect(SOCKET_ADDRESS)\n\n                sent = b'ABC'\n                s2.send(sent)\n                recieved = s1.recv()\n        self.assertEqual(sent, recieved)\n\n    def test_send_recv_with_embeded_nulls(self):\n        with Socket(PAIR) as s1:\n            with Socket(PAIR) as s2:\n                s1.bind(SOCKET_ADDRESS)\n                s2.connect(SOCKET_ADDRESS)\n\n                sent = b'ABC\\x00DEFEDDSS'\n                s2.send(sent)\n                recieved = s1.recv()\n        self.assertEqual(sent, recieved)\n\n    def test_send_recv_large_message(self):\n        with Socket(PAIR) as s1:\n            with Socket(PAIR) as s2:\n                s1.bind(SOCKET_ADDRESS)\n                s2.connect(SOCKET_ADDRESS)\n\n                sent = b'B'*(1024*1024)\n                s2.send(sent)\n                recieved = s1.recv()\n        self.assertEqual(sent, recieved)\n\n\n\n\nif __name__ == '__main__':\n    unittest.main()\n"
  },
  {
    "path": "tests/test_poll.py",
    "content": "import unittest\nimport os\nimport uuid\nimport time\n\nfrom nanomsg_wrappers import set_wrapper_choice, get_default_for_platform\nset_wrapper_choice(os.environ.get('NANOMSG_PY_TEST_WRAPPER',\n                                  get_default_for_platform()))\n\nfrom nanomsg import (\n    PAIR,\n    DONTWAIT,\n    SOL_SOCKET,\n    SNDBUF,\n    poll,\n    Socket,\n    NanoMsgAPIError\n)\n\nSOCKET_ADDRESS = os.environ.get('NANOMSG_PY_TEST_ADDRESS', \"inproc://{0}\".format(uuid.uuid4()))\n\n\nclass TestPoll(unittest.TestCase):\n    def test_read_poll(self):\n        with Socket(PAIR) as s1:\n            with Socket(PAIR) as s2:\n                s1.bind(SOCKET_ADDRESS)\n                s2.connect(SOCKET_ADDRESS)\n                r, _ = poll([s1, s2], [], 0)\n                self.assertEqual(0, len(r), \"Precondition nothing to read\")\n                sent = b'ABC'\n                s2.send(sent)\n                r, _ = poll([s1, s2], [], 0)\n                self.assertTrue(s1 in r, \"Socket is in read list\")\n                received = s1.recv()\n\n    def test_write_poll(self):\n        with Socket(PAIR) as s1:\n            with Socket(PAIR) as s2:\n                s1.bind(SOCKET_ADDRESS)\n                s2.connect(SOCKET_ADDRESS)\n                r, w = poll([], [s1, s2], 2)\n                self.assertEqual(2, len(w), \"Precondition nothing to read\")\n                sent = b'ABCD'\n\n                # minimum send size\n                snd_buf_size = 128*1024\n                s2.set_int_option(SOL_SOCKET, SNDBUF, snd_buf_size)\n\n                # send until full\n                for i in range(snd_buf_size//len(sent)+1):\n                    try:\n                        s2.send(sent, DONTWAIT)\n                    except:\n                        pass\n\n                # poll\n                r, w = poll([], [s1, s2], 0)\n                self.assertTrue(s2 not in w, \"Socket is in write list\")\n                received = s1.recv()\n\n    def test_poll_timeout(self):\n        with Socket(PAIR) as s1:\n            with Socket(PAIR) as s2:\n                s1.bind(SOCKET_ADDRESS)\n                s2.connect(SOCKET_ADDRESS)\n                start_time = time.time()\n                timeout = .05\n                r, _ = poll([s1, s2], [], timeout)\n                end_time = time.time()\n                self.assertTrue(end_time-start_time-timeout < .030)\n                self.assertEqual(0, len(r), \"No sockets to read\")\n\n\n\nif __name__ == '__main__':\n    unittest.main()\n"
  },
  {
    "path": "tests/test_pubsub.py",
    "content": "import unittest\nimport os\n\nfrom nanomsg_wrappers import set_wrapper_choice, get_default_for_platform\nset_wrapper_choice(os.environ.get('NANOMSG_PY_TEST_WRAPPER',\n                                  get_default_for_platform()))\n\nfrom nanomsg import (\n    SUB,\n    PUB,\n    SUB_SUBSCRIBE,\n    Socket\n)\n\nSOCKET_ADDRESS = os.environ.get('NANOMSG_PY_TEST_ADDRESS', \"inproc://a\")\n\n\nclass TestPubSubSockets(unittest.TestCase):\n    def test_subscribe_works(self):\n        with Socket(PUB) as s1:\n            with Socket(SUB) as s2:\n                s1.bind(SOCKET_ADDRESS)\n                s2.connect(SOCKET_ADDRESS)\n                s2.set_string_option(SUB, SUB_SUBSCRIBE, 'test')\n                s1.send('test')\n                s2.recv()\n                s1.send('a') # should not get received\n                expected = b'test121212'\n                s1.send(expected)\n\n                actual = s2.recv()\n\n                self.assertEquals(expected, actual)\n\nif __name__ == '__main__':\n    unittest.main()\n"
  },
  {
    "path": "usr_local_setup.cfg",
    "content": "[build_ext]\ninclude_dirs=/usr/local/include\nlibrary_dirs=/usr/local/lib\nrpath=/usr/local/lib\n\n"
  }
]