int Trie_has_prefix(const Trie* trie, const char *prefix) { int first, last, mid; if(!prefix[0]) { return 1; } /* The transitions are stored in alphabetical order. Do a binary * search to find the proper one. */ first = 0; last = trie->num_transitions-1; while(first <= last) { Transition* transition; char *suffix; int suffixlen, prefixlen, minlen; int c; mid = (first+last)/2; transition = &trie->transitions[mid]; suffix = transition->suffix; suffixlen = strlen(suffix); prefixlen = strlen(prefix); minlen = (suffixlen < prefixlen) ? suffixlen : prefixlen; c = strncmp(prefix, suffix, minlen); if(c < 0) last = mid-1; else if(c > 0) first = mid+1; else return Trie_has_prefix(transition->next, prefix+minlen); } return 0; }
static PyObject * trie_has_prefix(trieobject *mp, PyObject *py_prefix) { unsigned char *prefix; int has_prefix; /* Make sure prefix is a string. */ if(!PyString_Check(py_prefix)) { PyErr_SetString(PyExc_TypeError, "k must be a string"); return NULL; } prefix = (unsigned char *)PyString_AS_STRING(py_prefix); has_prefix = Trie_has_prefix(mp->trie, prefix); return PyInt_FromLong((long)has_prefix); }
static PyObject * trie_has_prefix(trieobject *mp, PyObject *py_prefix) { const char *prefix; int has_prefix; #ifdef IS_PY3K PyObject* bytes; #endif /* Make sure prefix is a string. */ #ifdef IS_PY3K if(!PyUnicode_Check(py_prefix)) { #else if(!PyString_Check(py_prefix)) { #endif PyErr_SetString(PyExc_TypeError, "prefix must be a string"); return NULL; } #ifdef IS_PY3K bytes = PyUnicode_AsASCIIString(py_prefix); if(!bytes) { PyErr_SetString(PyExc_TypeError, "prefix must be an ASCII string"); return NULL; } prefix = PyBytes_AsString(bytes); #else prefix = PyString_AS_STRING(py_prefix); #endif has_prefix = Trie_has_prefix(mp->trie, prefix); #ifdef IS_PY3K Py_DECREF(bytes); return PyLong_FromLong((long)has_prefix); #else return PyInt_FromLong((long)has_prefix); #endif } static PyObject * trie_has_prefix_onearg(trieobject *mp, PyObject *py_args) { PyObject *py_arg; if(!PyArg_ParseTuple(py_args, "O", &py_arg)) return NULL; return trie_has_prefix(mp, py_arg); }