Skip to content

Instantly share code, notes, and snippets.

@piskvorky
Last active July 14, 2018 23:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piskvorky/5512a30e1eb07f64c56e2151cfd40765 to your computer and use it in GitHub Desktop.
Save piskvorky/5512a30e1eb07f64c56e2151cfd40765 to your computer and use it in GitHub Desktop.
#include <Python.h>
/*
Return the sum of word lengths of all words (unicode strings) in the list `sentence`.
Return -1 if `sentence` isn't a list, and -2 if any of its elements is not a unicode string.
`sentence` and its elements are const = never changed inside this function, and guaranteed to live
throughout its execution, so we don't bother updating any reference counts.
*/
static long long process_const_sentence(PyObject *sentence) {
if (!PyList_Check(sentence)) {
return -1;
}
Py_ssize_t pos = 0;
long long result = 0;
for (; pos < PyList_Size(sentence); pos++) {
PyObject *word = PyList_GET_ITEM(sentence, pos);
if (!PyUnicode_Check(word)) {
return -2;
}
result += PyUnicode_GET_SIZE(word);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment