-
Notifications
You must be signed in to change notification settings - Fork 270
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Adding support for stack.ArrayStack
in C++ backend
#512
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
4b670e4
initial implementation steps
nubol23 c1c90dc
try to instantiate array
nubol23 4b028f1
Removed INCREF/DECREF calls and add array types to stack module as well
czgdp1807 528f183
added push method
nubol23 c126e74
added remaining methods and getters
nubol23 e60213d
changed __new__ method to handle instances with cpp backend
nubol23 ea90eb9
added tests for cpp backend
nubol23 6c51fbf
handle kwargs in c++
nubol23 4385edf
Apply suggestions from code review
czgdp1807 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
Empty file.
177 changes: 177 additions & 0 deletions
177
pydatastructs/miscellaneous_data_structures/_backend/cpp/stack/ArrayStack.hpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,177 @@ | ||
#ifndef MISCELLANEOUS_DATA_STRUCTURES_ARRAYSTACK_HPP | ||
#define MISCELLANEOUS_DATA_STRUCTURES_ARRAYSTACK_HPP | ||
|
||
#define PY_SSIZE_T_CLEAN | ||
#include <Python.h> | ||
#include <cstdlib> | ||
#include <iostream> | ||
#include <structmember.h> | ||
#include "../../../../linear_data_structures/_backend/cpp/arrays/DynamicOneDimensionalArray.hpp" | ||
|
||
typedef struct { | ||
PyObject_HEAD | ||
DynamicOneDimensionalArray* _items; | ||
} ArrayStack; | ||
|
||
static void ArrayStack_dealloc(ArrayStack *self) { | ||
DynamicOneDimensionalArray_dealloc(self->_items); | ||
Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self)); | ||
} | ||
|
||
static PyObject* ArrayStack__new__(PyTypeObject *type, PyObject *args, PyObject *kwds) { | ||
ArrayStack *self = reinterpret_cast<ArrayStack*>(type->tp_alloc(type, 0)); | ||
|
||
static char *kwlist[] = {"items", "dtype", NULL}; | ||
PyObject *initial_values = Py_None, *dtype = Py_None; | ||
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO", kwlist, &initial_values, &dtype)) { | ||
PyErr_SetString(PyExc_ValueError, "Error creating ArrayStack"); | ||
return NULL; | ||
} | ||
|
||
if (initial_values != Py_None && PyType_Check(initial_values)) { | ||
PyErr_SetString(PyExc_TypeError, "`items` must be an instance of list or tuple, received a type instead\n" | ||
"Did you mean to instantiate an ArrayStack with only the data type? " | ||
"if so, send the type parameter as a named argument " | ||
"for example: dtype=int"); | ||
return NULL; | ||
} | ||
|
||
PyObject* items = NULL; | ||
PyObject* doda_kwds = Py_BuildValue("{}"); | ||
if (initial_values == Py_None) { | ||
// If the only argument is the dtype, redefine the args as a tuple (dtype, 0) | ||
// where 0 is the initial array size | ||
PyObject* extended_args = PyTuple_Pack(2, dtype, PyLong_FromLong(0)); | ||
|
||
items = DynamicOneDimensionalArray___new__(&DynamicOneDimensionalArrayType, extended_args, doda_kwds); | ||
} else { | ||
// If the user provides dtype and initial values list, let the array initializer handle the checks. | ||
PyObject* doda_args = PyTuple_Pack(2, dtype, initial_values); | ||
items = DynamicOneDimensionalArray___new__(&DynamicOneDimensionalArrayType, doda_args, doda_kwds); | ||
} | ||
|
||
if (!items) { | ||
return NULL; | ||
} | ||
|
||
DynamicOneDimensionalArray* tmp = self->_items; | ||
self->_items = reinterpret_cast<DynamicOneDimensionalArray*>(items); | ||
|
||
return reinterpret_cast<PyObject*>(self); | ||
} | ||
|
||
static PyObject* ArrayStack_is_empty(ArrayStack *self) { | ||
bool is_empty = self->_items->_last_pos_filled == -1; | ||
|
||
if (is_empty) { | ||
Py_RETURN_TRUE; | ||
} | ||
|
||
Py_RETURN_FALSE; | ||
} | ||
|
||
static PyObject* ArrayStack_push(ArrayStack *self, PyObject* args) { | ||
size_t len_args = PyObject_Length(args); | ||
if (len_args != 1) { | ||
PyErr_SetString(PyExc_ValueError, "Expected one argument"); | ||
return NULL; | ||
} | ||
|
||
if (PyObject_IsTrue(ArrayStack_is_empty(self))) { | ||
self->_items->_one_dimensional_array->_dtype = reinterpret_cast<PyObject*>( | ||
Py_TYPE(PyObject_GetItem(args, PyZero)) | ||
); | ||
} | ||
|
||
DynamicOneDimensionalArray_append(self->_items, args); | ||
|
||
Py_RETURN_NONE; | ||
} | ||
|
||
static PyObject* ArrayStack_pop(ArrayStack *self) { | ||
if (PyObject_IsTrue(ArrayStack_is_empty(self))) { | ||
PyErr_SetString(PyExc_IndexError, "Stack is empty"); | ||
return NULL; | ||
} | ||
|
||
PyObject *top_element = DynamicOneDimensionalArray___getitem__( | ||
self->_items, PyLong_FromLong(self->_items->_last_pos_filled) | ||
); | ||
|
||
PyObject* last_pos_arg = PyTuple_Pack(1, PyLong_FromLong(self->_items->_last_pos_filled)); | ||
DynamicOneDimensionalArray_delete(self->_items, last_pos_arg); | ||
return top_element; | ||
} | ||
|
||
static PyObject* ArrayStack_peek(ArrayStack *self, void *closure) { | ||
return DynamicOneDimensionalArray___getitem__( | ||
self->_items, PyLong_FromLong(self->_items->_last_pos_filled) | ||
); | ||
} | ||
|
||
static Py_ssize_t ArrayStack__len__(ArrayStack *self) { | ||
return self->_items->_num; | ||
} | ||
|
||
static PyObject* ArrayStack__str__(ArrayStack* self){ | ||
return DynamicOneDimensionalArray___str__(self->_items); | ||
} | ||
|
||
static struct PyMethodDef ArrayStack_PyMethodDef[] = { | ||
{"push", (PyCFunction) ArrayStack_push, METH_VARARGS, NULL}, | ||
{"pop", (PyCFunction) ArrayStack_pop, METH_VARARGS, NULL}, | ||
{NULL} | ||
}; | ||
|
||
static PyMappingMethods ArrayStack_PyMappingMethods = { | ||
(lenfunc) ArrayStack__len__, | ||
}; | ||
|
||
static PyGetSetDef ArrayStack_GetterSetters[] = { | ||
{"peek", (getter) ArrayStack_peek, NULL, "peek top value", NULL}, | ||
{"is_empty", (getter) ArrayStack_is_empty, NULL, "check if the stack is empty", NULL}, | ||
{NULL} /* Sentinel */ | ||
}; | ||
|
||
static PyTypeObject ArrayStackType = { | ||
/* tp_name */ PyVarObject_HEAD_INIT(NULL, 0) "ArrayStack", | ||
/* tp_basicsize */ sizeof(ArrayStack), | ||
/* tp_itemsize */ 0, | ||
/* tp_dealloc */ (destructor) ArrayStack_dealloc, | ||
/* tp_print */ 0, | ||
/* tp_getattr */ 0, | ||
/* tp_setattr */ 0, | ||
/* tp_reserved */ 0, | ||
/* tp_repr */ 0, | ||
/* tp_as_number */ 0, | ||
/* tp_as_sequence */ 0, | ||
/* tp_as_mapping */ &ArrayStack_PyMappingMethods, | ||
/* tp_hash */ 0, | ||
/* tp_call */ 0, | ||
/* tp_str */ (reprfunc) ArrayStack__str__, | ||
/* tp_getattro */ 0, | ||
/* tp_setattro */ 0, | ||
/* tp_as_buffer */ 0, | ||
/* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, | ||
/* tp_doc */ 0, | ||
/* tp_traverse */ 0, | ||
/* tp_clear */ 0, | ||
/* tp_richcompare */ 0, | ||
/* tp_weaklistoffset */ 0, | ||
/* tp_iter */ 0, | ||
/* tp_iternext */ 0, | ||
/* tp_methods */ ArrayStack_PyMethodDef, | ||
/* tp_members */ 0, | ||
/* tp_getset */ ArrayStack_GetterSetters, | ||
/* tp_base */ 0, | ||
/* tp_dict */ 0, | ||
/* tp_descr_get */ 0, | ||
/* tp_descr_set */ 0, | ||
/* tp_dictoffset */ 0, | ||
/* tp_init */ 0, | ||
/* tp_alloc */ 0, | ||
/* tp_new */ ArrayStack__new__, | ||
}; | ||
|
||
|
||
#endif |
48 changes: 48 additions & 0 deletions
48
pydatastructs/miscellaneous_data_structures/_backend/cpp/stack/stack.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
#include <Python.h> | ||
#include "ArrayStack.hpp" | ||
|
||
static struct PyModuleDef stack_struct = { | ||
PyModuleDef_HEAD_INIT, | ||
"_stack", | ||
0, | ||
-1, | ||
NULL, | ||
}; | ||
|
||
PyMODINIT_FUNC PyInit__stack(void) { | ||
Py_Initialize(); | ||
PyObject *stack = PyModule_Create(&stack_struct); | ||
|
||
if (PyType_Ready(&ArrayStackType) < 0) { | ||
return NULL; | ||
} | ||
Py_INCREF(&ArrayStackType); | ||
PyModule_AddObject(stack, "ArrayStack", reinterpret_cast<PyObject*>(&ArrayStackType)); | ||
|
||
if (PyType_Ready(&ArrayType) < 0) { | ||
return NULL; | ||
} | ||
Py_INCREF(&ArrayType); | ||
PyModule_AddObject(stack, "Array", reinterpret_cast<PyObject*>(&ArrayType)); | ||
|
||
if (PyType_Ready(&OneDimensionalArrayType) < 0) { | ||
return NULL; | ||
} | ||
Py_INCREF(&OneDimensionalArrayType); | ||
PyModule_AddObject(stack, "OneDimensionalArray", reinterpret_cast<PyObject*>(&OneDimensionalArrayType)); | ||
|
||
if (PyType_Ready(&DynamicArrayType) < 0) { | ||
return NULL; | ||
} | ||
Py_INCREF(&DynamicArrayType); | ||
PyModule_AddObject(stack, "DynamicArray", reinterpret_cast<PyObject*>(&DynamicArrayType)); | ||
|
||
if (PyType_Ready(&DynamicOneDimensionalArrayType) < 0) { | ||
return NULL; | ||
} | ||
Py_INCREF(&DynamicOneDimensionalArrayType); | ||
PyModule_AddObject(stack, "DynamicOneDimensionalArray", reinterpret_cast<PyObject*>(&DynamicOneDimensionalArrayType)); | ||
|
||
|
||
return stack; | ||
} |
16 changes: 16 additions & 0 deletions
16
pydatastructs/miscellaneous_data_structures/_extensions.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
from setuptools import Extension | ||
|
||
project = 'pydatastructs' | ||
|
||
module = 'miscellaneous_data_structures' | ||
|
||
backend = '_backend' | ||
|
||
cpp = 'cpp' | ||
|
||
stack = '.'.join([project, module, backend, cpp, '_stack']) | ||
stack_sources = ['/'.join([project, module, backend, cpp, 'stack', 'stack.cpp'])] | ||
|
||
extensions = [ | ||
Extension(stack, sources=stack_sources), | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,9 +1,9 @@ | ||
project = 'pydatastructs' | ||
|
||
modules = ['linear_data_structures'] | ||
modules = ['linear_data_structures', 'miscellaneous_data_structures'] | ||
|
||
backend = '_backend' | ||
|
||
cpp = 'cpp' | ||
|
||
dummy_submodules_list = [('_arrays.py', '_algorithms.py')] | ||
dummy_submodules_list = [('_arrays.py', '_algorithms.py'), ('_stack.py',)] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The segmentation was being thrown because the array types weren't registered in the
stack
extension module. So there are two options,For now approach in point 1 seems much easier and efficient because we pre-register everything that's going to be used in the module's implementation. So no need to import them during function calls. The second approach is messier as well (
PyImport_Import
every now and then whenever we want to use something from another C++ extension module).There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The following code works for me for example with 4b028f1 commit.