MCPcopy Create free account
hub / github.com/ashvardanian/StringZilla / Str_init

Function Str_init

python/stringzilla.c:1137–1199  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1135#pragma region Str
1136
1137static int Str_init(Str *self, PyObject *args, PyObject *kwargs) {
1138
1139 // Parse all arguments into PyObjects first
1140 Py_ssize_t nargs = PyTuple_Size(args);
1141 if (nargs > 3) {
1142 PyErr_SetString(PyExc_TypeError, "Invalid number of arguments");
1143 return -1;
1144 }
1145 PyObject *parent_obj = nargs >= 1 ? PyTuple_GET_ITEM(args, 0) : NULL;
1146 PyObject *from_obj = nargs >= 2 ? PyTuple_GET_ITEM(args, 1) : NULL;
1147 PyObject *to_obj = nargs >= 3 ? PyTuple_GET_ITEM(args, 2) : NULL;
1148
1149 // Parse keyword arguments, if provided, and ensure no duplicates
1150 if (kwargs) {
1151 Py_ssize_t pos = 0;
1152 PyObject *key, *value;
1153 while (PyDict_Next(kwargs, &pos, &key, &value))
1154 if (PyUnicode_CompareWithASCIIString(key, "parent") == 0 && !parent_obj) { parent_obj = value; }
1155 else if (PyUnicode_CompareWithASCIIString(key, "from") == 0 && !from_obj) { from_obj = value; }
1156 else if (PyUnicode_CompareWithASCIIString(key, "to") == 0 && !to_obj) { to_obj = value; }
1157 else if (PyErr_Format(PyExc_TypeError, "Got an unexpected keyword argument '%U'", key))
1158 return -1;
1159 }
1160
1161 // Now, layout-check and cast each argument
1162 Py_ssize_t from = 0, to = PY_SSIZE_T_MAX;
1163 if (from_obj) {
1164 from = PyLong_AsSsize_t(from_obj);
1165 if (from == -1 && PyErr_Occurred()) {
1166 PyErr_SetString(PyExc_TypeError, "The `from` argument must be an integer");
1167 return -1;
1168 }
1169 }
1170 if (to_obj) {
1171 to = PyLong_AsSsize_t(to_obj);
1172 if (to == -1 && PyErr_Occurred()) {
1173 PyErr_SetString(PyExc_TypeError, "The `to` argument must be an integer");
1174 return -1;
1175 }
1176 }
1177
1178 // Handle empty string
1179 if (parent_obj == NULL) {
1180 self->memory.start = NULL;
1181 self->memory.length = 0;
1182 }
1183 // Increment the reference count of the parent
1184 else if (sz_py_export_string_like(parent_obj, &self->memory.start, &self->memory.length)) {
1185 self->parent = parent_obj;
1186 Py_INCREF(parent_obj);
1187 }
1188 else {
1189 wrap_current_exception("Unsupported parent type");
1190 return -1;
1191 }
1192
1193 // Apply slicing
1194 sz_size_t normalized_offset, normalized_length;

Callers

nothing calls this directly

Calls 3

sz_py_export_string_likeFunction · 0.85
wrap_current_exceptionFunction · 0.85
sz_ssize_clamp_intervalFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…