bytearrayobject.c 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488
  1. /* PyByteArray (bytearray) implementation */
  2. #define PY_SSIZE_T_CLEAN
  3. #include "Python.h"
  4. #include "pycore_abstract.h" // _PyIndex_Check()
  5. #include "pycore_bytes_methods.h"
  6. #include "pycore_bytesobject.h"
  7. #include "pycore_object.h" // _PyObject_GC_UNTRACK()
  8. #include "pycore_strhex.h" // _Py_strhex_with_sep()
  9. #include "pycore_long.h" // _PyLong_FromUnsignedChar()
  10. #include "bytesobject.h"
  11. /*[clinic input]
  12. class bytearray "PyByteArrayObject *" "&PyByteArray_Type"
  13. [clinic start generated code]*/
  14. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=5535b77c37a119e0]*/
  15. /* For PyByteArray_AS_STRING(). */
  16. char _PyByteArray_empty_string[] = "";
  17. /* Helpers */
  18. static int
  19. _getbytevalue(PyObject* arg, int *value)
  20. {
  21. int overflow;
  22. long face_value = PyLong_AsLongAndOverflow(arg, &overflow);
  23. if (face_value == -1 && PyErr_Occurred()) {
  24. *value = -1;
  25. return 0;
  26. }
  27. if (face_value < 0 || face_value >= 256) {
  28. /* this includes an overflow in converting to C long */
  29. PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
  30. *value = -1;
  31. return 0;
  32. }
  33. *value = face_value;
  34. return 1;
  35. }
  36. static int
  37. bytearray_getbuffer(PyByteArrayObject *obj, Py_buffer *view, int flags)
  38. {
  39. void *ptr;
  40. if (view == NULL) {
  41. PyErr_SetString(PyExc_BufferError,
  42. "bytearray_getbuffer: view==NULL argument is obsolete");
  43. return -1;
  44. }
  45. ptr = (void *) PyByteArray_AS_STRING(obj);
  46. /* cannot fail if view != NULL and readonly == 0 */
  47. (void)PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags);
  48. obj->ob_exports++;
  49. return 0;
  50. }
  51. static void
  52. bytearray_releasebuffer(PyByteArrayObject *obj, Py_buffer *view)
  53. {
  54. obj->ob_exports--;
  55. assert(obj->ob_exports >= 0);
  56. }
  57. static int
  58. _canresize(PyByteArrayObject *self)
  59. {
  60. if (self->ob_exports > 0) {
  61. PyErr_SetString(PyExc_BufferError,
  62. "Existing exports of data: object cannot be re-sized");
  63. return 0;
  64. }
  65. return 1;
  66. }
  67. #include "clinic/bytearrayobject.c.h"
  68. /* Direct API functions */
  69. PyObject *
  70. PyByteArray_FromObject(PyObject *input)
  71. {
  72. return PyObject_CallOneArg((PyObject *)&PyByteArray_Type, input);
  73. }
  74. static PyObject *
  75. _PyByteArray_FromBufferObject(PyObject *obj)
  76. {
  77. PyObject *result;
  78. Py_buffer view;
  79. if (PyObject_GetBuffer(obj, &view, PyBUF_FULL_RO) < 0) {
  80. return NULL;
  81. }
  82. result = PyByteArray_FromStringAndSize(NULL, view.len);
  83. if (result != NULL &&
  84. PyBuffer_ToContiguous(PyByteArray_AS_STRING(result),
  85. &view, view.len, 'C') < 0)
  86. {
  87. Py_CLEAR(result);
  88. }
  89. PyBuffer_Release(&view);
  90. return result;
  91. }
  92. PyObject *
  93. PyByteArray_FromStringAndSize(const char *bytes, Py_ssize_t size)
  94. {
  95. PyByteArrayObject *new;
  96. Py_ssize_t alloc;
  97. if (size < 0) {
  98. PyErr_SetString(PyExc_SystemError,
  99. "Negative size passed to PyByteArray_FromStringAndSize");
  100. return NULL;
  101. }
  102. /* Prevent buffer overflow when setting alloc to size+1. */
  103. if (size == PY_SSIZE_T_MAX) {
  104. return PyErr_NoMemory();
  105. }
  106. new = PyObject_New(PyByteArrayObject, &PyByteArray_Type);
  107. if (new == NULL)
  108. return NULL;
  109. if (size == 0) {
  110. new->ob_bytes = NULL;
  111. alloc = 0;
  112. }
  113. else {
  114. alloc = size + 1;
  115. new->ob_bytes = PyObject_Malloc(alloc);
  116. if (new->ob_bytes == NULL) {
  117. Py_DECREF(new);
  118. return PyErr_NoMemory();
  119. }
  120. if (bytes != NULL && size > 0)
  121. memcpy(new->ob_bytes, bytes, size);
  122. new->ob_bytes[size] = '\0'; /* Trailing null byte */
  123. }
  124. Py_SET_SIZE(new, size);
  125. new->ob_alloc = alloc;
  126. new->ob_start = new->ob_bytes;
  127. new->ob_exports = 0;
  128. return (PyObject *)new;
  129. }
  130. Py_ssize_t
  131. PyByteArray_Size(PyObject *self)
  132. {
  133. assert(self != NULL);
  134. assert(PyByteArray_Check(self));
  135. return PyByteArray_GET_SIZE(self);
  136. }
  137. char *
  138. PyByteArray_AsString(PyObject *self)
  139. {
  140. assert(self != NULL);
  141. assert(PyByteArray_Check(self));
  142. return PyByteArray_AS_STRING(self);
  143. }
  144. int
  145. PyByteArray_Resize(PyObject *self, Py_ssize_t requested_size)
  146. {
  147. void *sval;
  148. PyByteArrayObject *obj = ((PyByteArrayObject *)self);
  149. /* All computations are done unsigned to avoid integer overflows
  150. (see issue #22335). */
  151. size_t alloc = (size_t) obj->ob_alloc;
  152. size_t logical_offset = (size_t) (obj->ob_start - obj->ob_bytes);
  153. size_t size = (size_t) requested_size;
  154. assert(self != NULL);
  155. assert(PyByteArray_Check(self));
  156. assert(logical_offset <= alloc);
  157. assert(requested_size >= 0);
  158. if (requested_size == Py_SIZE(self)) {
  159. return 0;
  160. }
  161. if (!_canresize(obj)) {
  162. return -1;
  163. }
  164. if (size + logical_offset + 1 <= alloc) {
  165. /* Current buffer is large enough to host the requested size,
  166. decide on a strategy. */
  167. if (size < alloc / 2) {
  168. /* Major downsize; resize down to exact size */
  169. alloc = size + 1;
  170. }
  171. else {
  172. /* Minor downsize; quick exit */
  173. Py_SET_SIZE(self, size);
  174. PyByteArray_AS_STRING(self)[size] = '\0'; /* Trailing null */
  175. return 0;
  176. }
  177. }
  178. else {
  179. /* Need growing, decide on a strategy */
  180. if (size <= alloc * 1.125) {
  181. /* Moderate upsize; overallocate similar to list_resize() */
  182. alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
  183. }
  184. else {
  185. /* Major upsize; resize up to exact size */
  186. alloc = size + 1;
  187. }
  188. }
  189. if (alloc > PY_SSIZE_T_MAX) {
  190. PyErr_NoMemory();
  191. return -1;
  192. }
  193. if (logical_offset > 0) {
  194. sval = PyObject_Malloc(alloc);
  195. if (sval == NULL) {
  196. PyErr_NoMemory();
  197. return -1;
  198. }
  199. memcpy(sval, PyByteArray_AS_STRING(self),
  200. Py_MIN((size_t)requested_size, (size_t)Py_SIZE(self)));
  201. PyObject_Free(obj->ob_bytes);
  202. }
  203. else {
  204. sval = PyObject_Realloc(obj->ob_bytes, alloc);
  205. if (sval == NULL) {
  206. PyErr_NoMemory();
  207. return -1;
  208. }
  209. }
  210. obj->ob_bytes = obj->ob_start = sval;
  211. Py_SET_SIZE(self, size);
  212. obj->ob_alloc = alloc;
  213. obj->ob_bytes[size] = '\0'; /* Trailing null byte */
  214. return 0;
  215. }
  216. PyObject *
  217. PyByteArray_Concat(PyObject *a, PyObject *b)
  218. {
  219. Py_buffer va, vb;
  220. PyByteArrayObject *result = NULL;
  221. va.len = -1;
  222. vb.len = -1;
  223. if (PyObject_GetBuffer(a, &va, PyBUF_SIMPLE) != 0 ||
  224. PyObject_GetBuffer(b, &vb, PyBUF_SIMPLE) != 0) {
  225. PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
  226. Py_TYPE(b)->tp_name, Py_TYPE(a)->tp_name);
  227. goto done;
  228. }
  229. if (va.len > PY_SSIZE_T_MAX - vb.len) {
  230. PyErr_NoMemory();
  231. goto done;
  232. }
  233. result = (PyByteArrayObject *) \
  234. PyByteArray_FromStringAndSize(NULL, va.len + vb.len);
  235. // result->ob_bytes is NULL if result is an empty bytearray:
  236. // if va.len + vb.len equals zero.
  237. if (result != NULL && result->ob_bytes != NULL) {
  238. memcpy(result->ob_bytes, va.buf, va.len);
  239. memcpy(result->ob_bytes + va.len, vb.buf, vb.len);
  240. }
  241. done:
  242. if (va.len != -1)
  243. PyBuffer_Release(&va);
  244. if (vb.len != -1)
  245. PyBuffer_Release(&vb);
  246. return (PyObject *)result;
  247. }
  248. /* Functions stuffed into the type object */
  249. static Py_ssize_t
  250. bytearray_length(PyByteArrayObject *self)
  251. {
  252. return Py_SIZE(self);
  253. }
  254. static PyObject *
  255. bytearray_iconcat(PyByteArrayObject *self, PyObject *other)
  256. {
  257. Py_ssize_t size;
  258. Py_buffer vo;
  259. if (PyObject_GetBuffer(other, &vo, PyBUF_SIMPLE) != 0) {
  260. PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
  261. Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name);
  262. return NULL;
  263. }
  264. size = Py_SIZE(self);
  265. if (size > PY_SSIZE_T_MAX - vo.len) {
  266. PyBuffer_Release(&vo);
  267. return PyErr_NoMemory();
  268. }
  269. if (PyByteArray_Resize((PyObject *)self, size + vo.len) < 0) {
  270. PyBuffer_Release(&vo);
  271. return NULL;
  272. }
  273. memcpy(PyByteArray_AS_STRING(self) + size, vo.buf, vo.len);
  274. PyBuffer_Release(&vo);
  275. return Py_NewRef(self);
  276. }
  277. static PyObject *
  278. bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
  279. {
  280. if (count < 0)
  281. count = 0;
  282. const Py_ssize_t mysize = Py_SIZE(self);
  283. if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
  284. return PyErr_NoMemory();
  285. Py_ssize_t size = mysize * count;
  286. PyByteArrayObject* result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
  287. const char* buf = PyByteArray_AS_STRING(self);
  288. if (result != NULL && size != 0) {
  289. _PyBytes_Repeat(result->ob_bytes, size, buf, mysize);
  290. }
  291. return (PyObject *)result;
  292. }
  293. static PyObject *
  294. bytearray_irepeat(PyByteArrayObject *self, Py_ssize_t count)
  295. {
  296. if (count < 0)
  297. count = 0;
  298. else if (count == 1) {
  299. return Py_NewRef(self);
  300. }
  301. const Py_ssize_t mysize = Py_SIZE(self);
  302. if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
  303. return PyErr_NoMemory();
  304. const Py_ssize_t size = mysize * count;
  305. if (PyByteArray_Resize((PyObject *)self, size) < 0)
  306. return NULL;
  307. char* buf = PyByteArray_AS_STRING(self);
  308. _PyBytes_Repeat(buf, size, buf, mysize);
  309. return Py_NewRef(self);
  310. }
  311. static PyObject *
  312. bytearray_getitem(PyByteArrayObject *self, Py_ssize_t i)
  313. {
  314. if (i < 0 || i >= Py_SIZE(self)) {
  315. PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
  316. return NULL;
  317. }
  318. return _PyLong_FromUnsignedChar((unsigned char)(self->ob_start[i]));
  319. }
  320. static PyObject *
  321. bytearray_subscript(PyByteArrayObject *self, PyObject *index)
  322. {
  323. if (_PyIndex_Check(index)) {
  324. Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
  325. if (i == -1 && PyErr_Occurred())
  326. return NULL;
  327. if (i < 0)
  328. i += PyByteArray_GET_SIZE(self);
  329. if (i < 0 || i >= Py_SIZE(self)) {
  330. PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
  331. return NULL;
  332. }
  333. return _PyLong_FromUnsignedChar((unsigned char)(self->ob_start[i]));
  334. }
  335. else if (PySlice_Check(index)) {
  336. Py_ssize_t start, stop, step, slicelength, i;
  337. size_t cur;
  338. if (PySlice_Unpack(index, &start, &stop, &step) < 0) {
  339. return NULL;
  340. }
  341. slicelength = PySlice_AdjustIndices(PyByteArray_GET_SIZE(self),
  342. &start, &stop, step);
  343. if (slicelength <= 0)
  344. return PyByteArray_FromStringAndSize("", 0);
  345. else if (step == 1) {
  346. return PyByteArray_FromStringAndSize(
  347. PyByteArray_AS_STRING(self) + start, slicelength);
  348. }
  349. else {
  350. char *source_buf = PyByteArray_AS_STRING(self);
  351. char *result_buf;
  352. PyObject *result;
  353. result = PyByteArray_FromStringAndSize(NULL, slicelength);
  354. if (result == NULL)
  355. return NULL;
  356. result_buf = PyByteArray_AS_STRING(result);
  357. for (cur = start, i = 0; i < slicelength;
  358. cur += step, i++) {
  359. result_buf[i] = source_buf[cur];
  360. }
  361. return result;
  362. }
  363. }
  364. else {
  365. PyErr_Format(PyExc_TypeError,
  366. "bytearray indices must be integers or slices, not %.200s",
  367. Py_TYPE(index)->tp_name);
  368. return NULL;
  369. }
  370. }
  371. static int
  372. bytearray_setslice_linear(PyByteArrayObject *self,
  373. Py_ssize_t lo, Py_ssize_t hi,
  374. char *bytes, Py_ssize_t bytes_len)
  375. {
  376. Py_ssize_t avail = hi - lo;
  377. char *buf = PyByteArray_AS_STRING(self);
  378. Py_ssize_t growth = bytes_len - avail;
  379. int res = 0;
  380. assert(avail >= 0);
  381. if (growth < 0) {
  382. if (!_canresize(self))
  383. return -1;
  384. if (lo == 0) {
  385. /* Shrink the buffer by advancing its logical start */
  386. self->ob_start -= growth;
  387. /*
  388. 0 lo hi old_size
  389. | |<----avail----->|<-----tail------>|
  390. | |<-bytes_len->|<-----tail------>|
  391. 0 new_lo new_hi new_size
  392. */
  393. }
  394. else {
  395. /*
  396. 0 lo hi old_size
  397. | |<----avail----->|<-----tomove------>|
  398. | |<-bytes_len->|<-----tomove------>|
  399. 0 lo new_hi new_size
  400. */
  401. memmove(buf + lo + bytes_len, buf + hi,
  402. Py_SIZE(self) - hi);
  403. }
  404. if (PyByteArray_Resize((PyObject *)self,
  405. Py_SIZE(self) + growth) < 0) {
  406. /* Issue #19578: Handling the memory allocation failure here is
  407. tricky here because the bytearray object has already been
  408. modified. Depending on growth and lo, the behaviour is
  409. different.
  410. If growth < 0 and lo != 0, the operation is completed, but a
  411. MemoryError is still raised and the memory block is not
  412. shrunk. Otherwise, the bytearray is restored in its previous
  413. state and a MemoryError is raised. */
  414. if (lo == 0) {
  415. self->ob_start += growth;
  416. return -1;
  417. }
  418. /* memmove() removed bytes, the bytearray object cannot be
  419. restored in its previous state. */
  420. Py_SET_SIZE(self, Py_SIZE(self) + growth);
  421. res = -1;
  422. }
  423. buf = PyByteArray_AS_STRING(self);
  424. }
  425. else if (growth > 0) {
  426. if (Py_SIZE(self) > (Py_ssize_t)PY_SSIZE_T_MAX - growth) {
  427. PyErr_NoMemory();
  428. return -1;
  429. }
  430. if (PyByteArray_Resize((PyObject *)self,
  431. Py_SIZE(self) + growth) < 0) {
  432. return -1;
  433. }
  434. buf = PyByteArray_AS_STRING(self);
  435. /* Make the place for the additional bytes */
  436. /*
  437. 0 lo hi old_size
  438. | |<-avail->|<-----tomove------>|
  439. | |<---bytes_len-->|<-----tomove------>|
  440. 0 lo new_hi new_size
  441. */
  442. memmove(buf + lo + bytes_len, buf + hi,
  443. Py_SIZE(self) - lo - bytes_len);
  444. }
  445. if (bytes_len > 0)
  446. memcpy(buf + lo, bytes, bytes_len);
  447. return res;
  448. }
  449. static int
  450. bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,
  451. PyObject *values)
  452. {
  453. Py_ssize_t needed;
  454. void *bytes;
  455. Py_buffer vbytes;
  456. int res = 0;
  457. vbytes.len = -1;
  458. if (values == (PyObject *)self) {
  459. /* Make a copy and call this function recursively */
  460. int err;
  461. values = PyByteArray_FromStringAndSize(PyByteArray_AS_STRING(values),
  462. PyByteArray_GET_SIZE(values));
  463. if (values == NULL)
  464. return -1;
  465. err = bytearray_setslice(self, lo, hi, values);
  466. Py_DECREF(values);
  467. return err;
  468. }
  469. if (values == NULL) {
  470. /* del b[lo:hi] */
  471. bytes = NULL;
  472. needed = 0;
  473. }
  474. else {
  475. if (PyObject_GetBuffer(values, &vbytes, PyBUF_SIMPLE) != 0) {
  476. PyErr_Format(PyExc_TypeError,
  477. "can't set bytearray slice from %.100s",
  478. Py_TYPE(values)->tp_name);
  479. return -1;
  480. }
  481. needed = vbytes.len;
  482. bytes = vbytes.buf;
  483. }
  484. if (lo < 0)
  485. lo = 0;
  486. if (hi < lo)
  487. hi = lo;
  488. if (hi > Py_SIZE(self))
  489. hi = Py_SIZE(self);
  490. res = bytearray_setslice_linear(self, lo, hi, bytes, needed);
  491. if (vbytes.len != -1)
  492. PyBuffer_Release(&vbytes);
  493. return res;
  494. }
  495. static int
  496. bytearray_setitem(PyByteArrayObject *self, Py_ssize_t i, PyObject *value)
  497. {
  498. int ival = -1;
  499. // GH-91153: We need to do this *before* the size check, in case value has a
  500. // nasty __index__ method that changes the size of the bytearray:
  501. if (value && !_getbytevalue(value, &ival)) {
  502. return -1;
  503. }
  504. if (i < 0) {
  505. i += Py_SIZE(self);
  506. }
  507. if (i < 0 || i >= Py_SIZE(self)) {
  508. PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
  509. return -1;
  510. }
  511. if (value == NULL) {
  512. return bytearray_setslice(self, i, i+1, NULL);
  513. }
  514. assert(0 <= ival && ival < 256);
  515. PyByteArray_AS_STRING(self)[i] = ival;
  516. return 0;
  517. }
  518. static int
  519. bytearray_ass_subscript(PyByteArrayObject *self, PyObject *index, PyObject *values)
  520. {
  521. Py_ssize_t start, stop, step, slicelen, needed;
  522. char *buf, *bytes;
  523. buf = PyByteArray_AS_STRING(self);
  524. if (_PyIndex_Check(index)) {
  525. Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
  526. if (i == -1 && PyErr_Occurred()) {
  527. return -1;
  528. }
  529. int ival = -1;
  530. // GH-91153: We need to do this *before* the size check, in case values
  531. // has a nasty __index__ method that changes the size of the bytearray:
  532. if (values && !_getbytevalue(values, &ival)) {
  533. return -1;
  534. }
  535. if (i < 0) {
  536. i += PyByteArray_GET_SIZE(self);
  537. }
  538. if (i < 0 || i >= Py_SIZE(self)) {
  539. PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
  540. return -1;
  541. }
  542. if (values == NULL) {
  543. /* Fall through to slice assignment */
  544. start = i;
  545. stop = i + 1;
  546. step = 1;
  547. slicelen = 1;
  548. }
  549. else {
  550. assert(0 <= ival && ival < 256);
  551. buf[i] = (char)ival;
  552. return 0;
  553. }
  554. }
  555. else if (PySlice_Check(index)) {
  556. if (PySlice_Unpack(index, &start, &stop, &step) < 0) {
  557. return -1;
  558. }
  559. slicelen = PySlice_AdjustIndices(PyByteArray_GET_SIZE(self), &start,
  560. &stop, step);
  561. }
  562. else {
  563. PyErr_Format(PyExc_TypeError,
  564. "bytearray indices must be integers or slices, not %.200s",
  565. Py_TYPE(index)->tp_name);
  566. return -1;
  567. }
  568. if (values == NULL) {
  569. bytes = NULL;
  570. needed = 0;
  571. }
  572. else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
  573. int err;
  574. if (PyNumber_Check(values) || PyUnicode_Check(values)) {
  575. PyErr_SetString(PyExc_TypeError,
  576. "can assign only bytes, buffers, or iterables "
  577. "of ints in range(0, 256)");
  578. return -1;
  579. }
  580. /* Make a copy and call this function recursively */
  581. values = PyByteArray_FromObject(values);
  582. if (values == NULL)
  583. return -1;
  584. err = bytearray_ass_subscript(self, index, values);
  585. Py_DECREF(values);
  586. return err;
  587. }
  588. else {
  589. assert(PyByteArray_Check(values));
  590. bytes = PyByteArray_AS_STRING(values);
  591. needed = Py_SIZE(values);
  592. }
  593. /* Make sure b[5:2] = ... inserts before 5, not before 2. */
  594. if ((step < 0 && start < stop) ||
  595. (step > 0 && start > stop))
  596. stop = start;
  597. if (step == 1) {
  598. return bytearray_setslice_linear(self, start, stop, bytes, needed);
  599. }
  600. else {
  601. if (needed == 0) {
  602. /* Delete slice */
  603. size_t cur;
  604. Py_ssize_t i;
  605. if (!_canresize(self))
  606. return -1;
  607. if (slicelen == 0)
  608. /* Nothing to do here. */
  609. return 0;
  610. if (step < 0) {
  611. stop = start + 1;
  612. start = stop + step * (slicelen - 1) - 1;
  613. step = -step;
  614. }
  615. for (cur = start, i = 0;
  616. i < slicelen; cur += step, i++) {
  617. Py_ssize_t lim = step - 1;
  618. if (cur + step >= (size_t)PyByteArray_GET_SIZE(self))
  619. lim = PyByteArray_GET_SIZE(self) - cur - 1;
  620. memmove(buf + cur - i,
  621. buf + cur + 1, lim);
  622. }
  623. /* Move the tail of the bytes, in one chunk */
  624. cur = start + (size_t)slicelen*step;
  625. if (cur < (size_t)PyByteArray_GET_SIZE(self)) {
  626. memmove(buf + cur - slicelen,
  627. buf + cur,
  628. PyByteArray_GET_SIZE(self) - cur);
  629. }
  630. if (PyByteArray_Resize((PyObject *)self,
  631. PyByteArray_GET_SIZE(self) - slicelen) < 0)
  632. return -1;
  633. return 0;
  634. }
  635. else {
  636. /* Assign slice */
  637. Py_ssize_t i;
  638. size_t cur;
  639. if (needed != slicelen) {
  640. PyErr_Format(PyExc_ValueError,
  641. "attempt to assign bytes of size %zd "
  642. "to extended slice of size %zd",
  643. needed, slicelen);
  644. return -1;
  645. }
  646. for (cur = start, i = 0; i < slicelen; cur += step, i++)
  647. buf[cur] = bytes[i];
  648. return 0;
  649. }
  650. }
  651. }
  652. /*[clinic input]
  653. bytearray.__init__
  654. source as arg: object = NULL
  655. encoding: str = NULL
  656. errors: str = NULL
  657. [clinic start generated code]*/
  658. static int
  659. bytearray___init___impl(PyByteArrayObject *self, PyObject *arg,
  660. const char *encoding, const char *errors)
  661. /*[clinic end generated code: output=4ce1304649c2f8b3 input=1141a7122eefd7b9]*/
  662. {
  663. Py_ssize_t count;
  664. PyObject *it;
  665. PyObject *(*iternext)(PyObject *);
  666. if (Py_SIZE(self) != 0) {
  667. /* Empty previous contents (yes, do this first of all!) */
  668. if (PyByteArray_Resize((PyObject *)self, 0) < 0)
  669. return -1;
  670. }
  671. /* Make a quick exit if no first argument */
  672. if (arg == NULL) {
  673. if (encoding != NULL || errors != NULL) {
  674. PyErr_SetString(PyExc_TypeError,
  675. encoding != NULL ?
  676. "encoding without a string argument" :
  677. "errors without a string argument");
  678. return -1;
  679. }
  680. return 0;
  681. }
  682. if (PyUnicode_Check(arg)) {
  683. /* Encode via the codec registry */
  684. PyObject *encoded, *new;
  685. if (encoding == NULL) {
  686. PyErr_SetString(PyExc_TypeError,
  687. "string argument without an encoding");
  688. return -1;
  689. }
  690. encoded = PyUnicode_AsEncodedString(arg, encoding, errors);
  691. if (encoded == NULL)
  692. return -1;
  693. assert(PyBytes_Check(encoded));
  694. new = bytearray_iconcat(self, encoded);
  695. Py_DECREF(encoded);
  696. if (new == NULL)
  697. return -1;
  698. Py_DECREF(new);
  699. return 0;
  700. }
  701. /* If it's not unicode, there can't be encoding or errors */
  702. if (encoding != NULL || errors != NULL) {
  703. PyErr_SetString(PyExc_TypeError,
  704. encoding != NULL ?
  705. "encoding without a string argument" :
  706. "errors without a string argument");
  707. return -1;
  708. }
  709. /* Is it an int? */
  710. if (_PyIndex_Check(arg)) {
  711. count = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
  712. if (count == -1 && PyErr_Occurred()) {
  713. if (!PyErr_ExceptionMatches(PyExc_TypeError))
  714. return -1;
  715. PyErr_Clear(); /* fall through */
  716. }
  717. else {
  718. if (count < 0) {
  719. PyErr_SetString(PyExc_ValueError, "negative count");
  720. return -1;
  721. }
  722. if (count > 0) {
  723. if (PyByteArray_Resize((PyObject *)self, count))
  724. return -1;
  725. memset(PyByteArray_AS_STRING(self), 0, count);
  726. }
  727. return 0;
  728. }
  729. }
  730. /* Use the buffer API */
  731. if (PyObject_CheckBuffer(arg)) {
  732. Py_ssize_t size;
  733. Py_buffer view;
  734. if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0)
  735. return -1;
  736. size = view.len;
  737. if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;
  738. if (PyBuffer_ToContiguous(PyByteArray_AS_STRING(self),
  739. &view, size, 'C') < 0)
  740. goto fail;
  741. PyBuffer_Release(&view);
  742. return 0;
  743. fail:
  744. PyBuffer_Release(&view);
  745. return -1;
  746. }
  747. if (PyList_CheckExact(arg) || PyTuple_CheckExact(arg)) {
  748. Py_ssize_t size = PySequence_Fast_GET_SIZE(arg);
  749. if (PyByteArray_Resize((PyObject *)self, size) < 0) {
  750. return -1;
  751. }
  752. PyObject **items = PySequence_Fast_ITEMS(arg);
  753. char *s = PyByteArray_AS_STRING(self);
  754. for (Py_ssize_t i = 0; i < size; i++) {
  755. int value;
  756. if (!PyLong_CheckExact(items[i])) {
  757. /* Resize to 0 and go through slowpath */
  758. if (Py_SIZE(self) != 0) {
  759. if (PyByteArray_Resize((PyObject *)self, 0) < 0) {
  760. return -1;
  761. }
  762. }
  763. goto slowpath;
  764. }
  765. int rc = _getbytevalue(items[i], &value);
  766. if (!rc) {
  767. return -1;
  768. }
  769. s[i] = value;
  770. }
  771. return 0;
  772. }
  773. slowpath:
  774. /* Get the iterator */
  775. it = PyObject_GetIter(arg);
  776. if (it == NULL) {
  777. if (PyErr_ExceptionMatches(PyExc_TypeError)) {
  778. PyErr_Format(PyExc_TypeError,
  779. "cannot convert '%.200s' object to bytearray",
  780. Py_TYPE(arg)->tp_name);
  781. }
  782. return -1;
  783. }
  784. iternext = *Py_TYPE(it)->tp_iternext;
  785. /* Run the iterator to exhaustion */
  786. for (;;) {
  787. PyObject *item;
  788. int rc, value;
  789. /* Get the next item */
  790. item = iternext(it);
  791. if (item == NULL) {
  792. if (PyErr_Occurred()) {
  793. if (!PyErr_ExceptionMatches(PyExc_StopIteration))
  794. goto error;
  795. PyErr_Clear();
  796. }
  797. break;
  798. }
  799. /* Interpret it as an int (__index__) */
  800. rc = _getbytevalue(item, &value);
  801. Py_DECREF(item);
  802. if (!rc)
  803. goto error;
  804. /* Append the byte */
  805. if (Py_SIZE(self) + 1 < self->ob_alloc) {
  806. Py_SET_SIZE(self, Py_SIZE(self) + 1);
  807. PyByteArray_AS_STRING(self)[Py_SIZE(self)] = '\0';
  808. }
  809. else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0)
  810. goto error;
  811. PyByteArray_AS_STRING(self)[Py_SIZE(self)-1] = value;
  812. }
  813. /* Clean up and return success */
  814. Py_DECREF(it);
  815. return 0;
  816. error:
  817. /* Error handling when it != NULL */
  818. Py_DECREF(it);
  819. return -1;
  820. }
  821. /* Mostly copied from string_repr, but without the
  822. "smart quote" functionality. */
  823. static PyObject *
  824. bytearray_repr(PyByteArrayObject *self)
  825. {
  826. const char *className = _PyType_Name(Py_TYPE(self));
  827. const char *quote_prefix = "(b";
  828. const char *quote_postfix = ")";
  829. Py_ssize_t length = Py_SIZE(self);
  830. /* 6 == strlen(quote_prefix) + 2 + strlen(quote_postfix) + 1 */
  831. Py_ssize_t newsize;
  832. PyObject *v;
  833. Py_ssize_t i;
  834. char *bytes;
  835. char c;
  836. char *p;
  837. int quote;
  838. char *test, *start;
  839. char *buffer;
  840. newsize = strlen(className);
  841. if (length > (PY_SSIZE_T_MAX - 6 - newsize) / 4) {
  842. PyErr_SetString(PyExc_OverflowError,
  843. "bytearray object is too large to make repr");
  844. return NULL;
  845. }
  846. newsize += 6 + length * 4;
  847. buffer = PyObject_Malloc(newsize);
  848. if (buffer == NULL) {
  849. PyErr_NoMemory();
  850. return NULL;
  851. }
  852. /* Figure out which quote to use; single is preferred */
  853. quote = '\'';
  854. start = PyByteArray_AS_STRING(self);
  855. for (test = start; test < start+length; ++test) {
  856. if (*test == '"') {
  857. quote = '\''; /* back to single */
  858. break;
  859. }
  860. else if (*test == '\'')
  861. quote = '"';
  862. }
  863. p = buffer;
  864. while (*className)
  865. *p++ = *className++;
  866. while (*quote_prefix)
  867. *p++ = *quote_prefix++;
  868. *p++ = quote;
  869. bytes = PyByteArray_AS_STRING(self);
  870. for (i = 0; i < length; i++) {
  871. /* There's at least enough room for a hex escape
  872. and a closing quote. */
  873. assert(newsize - (p - buffer) >= 5);
  874. c = bytes[i];
  875. if (c == '\'' || c == '\\')
  876. *p++ = '\\', *p++ = c;
  877. else if (c == '\t')
  878. *p++ = '\\', *p++ = 't';
  879. else if (c == '\n')
  880. *p++ = '\\', *p++ = 'n';
  881. else if (c == '\r')
  882. *p++ = '\\', *p++ = 'r';
  883. else if (c == 0)
  884. *p++ = '\\', *p++ = 'x', *p++ = '0', *p++ = '0';
  885. else if (c < ' ' || c >= 0x7f) {
  886. *p++ = '\\';
  887. *p++ = 'x';
  888. *p++ = Py_hexdigits[(c & 0xf0) >> 4];
  889. *p++ = Py_hexdigits[c & 0xf];
  890. }
  891. else
  892. *p++ = c;
  893. }
  894. assert(newsize - (p - buffer) >= 1);
  895. *p++ = quote;
  896. while (*quote_postfix) {
  897. *p++ = *quote_postfix++;
  898. }
  899. v = PyUnicode_FromStringAndSize(buffer, p - buffer);
  900. PyObject_Free(buffer);
  901. return v;
  902. }
  903. static PyObject *
  904. bytearray_str(PyObject *op)
  905. {
  906. if (_Py_GetConfig()->bytes_warning) {
  907. if (PyErr_WarnEx(PyExc_BytesWarning,
  908. "str() on a bytearray instance", 1)) {
  909. return NULL;
  910. }
  911. }
  912. return bytearray_repr((PyByteArrayObject*)op);
  913. }
  914. static PyObject *
  915. bytearray_richcompare(PyObject *self, PyObject *other, int op)
  916. {
  917. Py_ssize_t self_size, other_size;
  918. Py_buffer self_bytes, other_bytes;
  919. int cmp;
  920. if (!PyObject_CheckBuffer(self) || !PyObject_CheckBuffer(other)) {
  921. if (PyUnicode_Check(self) || PyUnicode_Check(other)) {
  922. if (_Py_GetConfig()->bytes_warning && (op == Py_EQ || op == Py_NE)) {
  923. if (PyErr_WarnEx(PyExc_BytesWarning,
  924. "Comparison between bytearray and string", 1))
  925. return NULL;
  926. }
  927. }
  928. Py_RETURN_NOTIMPLEMENTED;
  929. }
  930. /* Bytearrays can be compared to anything that supports the buffer API. */
  931. if (PyObject_GetBuffer(self, &self_bytes, PyBUF_SIMPLE) != 0) {
  932. PyErr_Clear();
  933. Py_RETURN_NOTIMPLEMENTED;
  934. }
  935. self_size = self_bytes.len;
  936. if (PyObject_GetBuffer(other, &other_bytes, PyBUF_SIMPLE) != 0) {
  937. PyErr_Clear();
  938. PyBuffer_Release(&self_bytes);
  939. Py_RETURN_NOTIMPLEMENTED;
  940. }
  941. other_size = other_bytes.len;
  942. if (self_size != other_size && (op == Py_EQ || op == Py_NE)) {
  943. /* Shortcut: if the lengths differ, the objects differ */
  944. PyBuffer_Release(&self_bytes);
  945. PyBuffer_Release(&other_bytes);
  946. return PyBool_FromLong((op == Py_NE));
  947. }
  948. else {
  949. cmp = memcmp(self_bytes.buf, other_bytes.buf,
  950. Py_MIN(self_size, other_size));
  951. /* In ISO C, memcmp() guarantees to use unsigned bytes! */
  952. PyBuffer_Release(&self_bytes);
  953. PyBuffer_Release(&other_bytes);
  954. if (cmp != 0) {
  955. Py_RETURN_RICHCOMPARE(cmp, 0, op);
  956. }
  957. Py_RETURN_RICHCOMPARE(self_size, other_size, op);
  958. }
  959. }
  960. static void
  961. bytearray_dealloc(PyByteArrayObject *self)
  962. {
  963. if (self->ob_exports > 0) {
  964. PyErr_SetString(PyExc_SystemError,
  965. "deallocated bytearray object has exported buffers");
  966. PyErr_Print();
  967. }
  968. if (self->ob_bytes != 0) {
  969. PyObject_Free(self->ob_bytes);
  970. }
  971. Py_TYPE(self)->tp_free((PyObject *)self);
  972. }
  973. /* -------------------------------------------------------------------- */
  974. /* Methods */
  975. #define STRINGLIB_IS_UNICODE 0
  976. #define FASTSEARCH fastsearch
  977. #define STRINGLIB(F) stringlib_##F
  978. #define STRINGLIB_CHAR char
  979. #define STRINGLIB_SIZEOF_CHAR 1
  980. #define STRINGLIB_LEN PyByteArray_GET_SIZE
  981. #define STRINGLIB_STR PyByteArray_AS_STRING
  982. #define STRINGLIB_NEW PyByteArray_FromStringAndSize
  983. #define STRINGLIB_ISSPACE Py_ISSPACE
  984. #define STRINGLIB_ISLINEBREAK(x) ((x == '\n') || (x == '\r'))
  985. #define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact
  986. #define STRINGLIB_FAST_MEMCHR memchr
  987. #define STRINGLIB_MUTABLE 1
  988. #include "stringlib/fastsearch.h"
  989. #include "stringlib/count.h"
  990. #include "stringlib/find.h"
  991. #include "stringlib/join.h"
  992. #include "stringlib/partition.h"
  993. #include "stringlib/split.h"
  994. #include "stringlib/ctype.h"
  995. #include "stringlib/transmogrify.h"
  996. static PyObject *
  997. bytearray_find(PyByteArrayObject *self, PyObject *args)
  998. {
  999. return _Py_bytes_find(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
  1000. }
  1001. static PyObject *
  1002. bytearray_count(PyByteArrayObject *self, PyObject *args)
  1003. {
  1004. return _Py_bytes_count(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
  1005. }
  1006. /*[clinic input]
  1007. bytearray.clear
  1008. Remove all items from the bytearray.
  1009. [clinic start generated code]*/
  1010. static PyObject *
  1011. bytearray_clear_impl(PyByteArrayObject *self)
  1012. /*[clinic end generated code: output=85c2fe6aede0956c input=ed6edae9de447ac4]*/
  1013. {
  1014. if (PyByteArray_Resize((PyObject *)self, 0) < 0)
  1015. return NULL;
  1016. Py_RETURN_NONE;
  1017. }
  1018. /*[clinic input]
  1019. bytearray.copy
  1020. Return a copy of B.
  1021. [clinic start generated code]*/
  1022. static PyObject *
  1023. bytearray_copy_impl(PyByteArrayObject *self)
  1024. /*[clinic end generated code: output=68cfbcfed484c132 input=6597b0c01bccaa9e]*/
  1025. {
  1026. return PyByteArray_FromStringAndSize(PyByteArray_AS_STRING((PyObject *)self),
  1027. PyByteArray_GET_SIZE(self));
  1028. }
  1029. static PyObject *
  1030. bytearray_index(PyByteArrayObject *self, PyObject *args)
  1031. {
  1032. return _Py_bytes_index(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
  1033. }
  1034. static PyObject *
  1035. bytearray_rfind(PyByteArrayObject *self, PyObject *args)
  1036. {
  1037. return _Py_bytes_rfind(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
  1038. }
  1039. static PyObject *
  1040. bytearray_rindex(PyByteArrayObject *self, PyObject *args)
  1041. {
  1042. return _Py_bytes_rindex(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
  1043. }
  1044. static int
  1045. bytearray_contains(PyObject *self, PyObject *arg)
  1046. {
  1047. return _Py_bytes_contains(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), arg);
  1048. }
  1049. static PyObject *
  1050. bytearray_startswith(PyByteArrayObject *self, PyObject *args)
  1051. {
  1052. return _Py_bytes_startswith(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
  1053. }
  1054. static PyObject *
  1055. bytearray_endswith(PyByteArrayObject *self, PyObject *args)
  1056. {
  1057. return _Py_bytes_endswith(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
  1058. }
  1059. /*[clinic input]
  1060. bytearray.removeprefix as bytearray_removeprefix
  1061. prefix: Py_buffer
  1062. /
  1063. Return a bytearray with the given prefix string removed if present.
  1064. If the bytearray starts with the prefix string, return
  1065. bytearray[len(prefix):]. Otherwise, return a copy of the original
  1066. bytearray.
  1067. [clinic start generated code]*/
  1068. static PyObject *
  1069. bytearray_removeprefix_impl(PyByteArrayObject *self, Py_buffer *prefix)
  1070. /*[clinic end generated code: output=6cabc585e7f502e0 input=968aada38aedd262]*/
  1071. {
  1072. const char *self_start = PyByteArray_AS_STRING(self);
  1073. Py_ssize_t self_len = PyByteArray_GET_SIZE(self);
  1074. const char *prefix_start = prefix->buf;
  1075. Py_ssize_t prefix_len = prefix->len;
  1076. if (self_len >= prefix_len
  1077. && memcmp(self_start, prefix_start, prefix_len) == 0)
  1078. {
  1079. return PyByteArray_FromStringAndSize(self_start + prefix_len,
  1080. self_len - prefix_len);
  1081. }
  1082. return PyByteArray_FromStringAndSize(self_start, self_len);
  1083. }
  1084. /*[clinic input]
  1085. bytearray.removesuffix as bytearray_removesuffix
  1086. suffix: Py_buffer
  1087. /
  1088. Return a bytearray with the given suffix string removed if present.
  1089. If the bytearray ends with the suffix string and that suffix is not
  1090. empty, return bytearray[:-len(suffix)]. Otherwise, return a copy of
  1091. the original bytearray.
  1092. [clinic start generated code]*/
  1093. static PyObject *
  1094. bytearray_removesuffix_impl(PyByteArrayObject *self, Py_buffer *suffix)
  1095. /*[clinic end generated code: output=2bc8cfb79de793d3 input=c1827e810b2f6b99]*/
  1096. {
  1097. const char *self_start = PyByteArray_AS_STRING(self);
  1098. Py_ssize_t self_len = PyByteArray_GET_SIZE(self);
  1099. const char *suffix_start = suffix->buf;
  1100. Py_ssize_t suffix_len = suffix->len;
  1101. if (self_len >= suffix_len
  1102. && memcmp(self_start + self_len - suffix_len,
  1103. suffix_start, suffix_len) == 0)
  1104. {
  1105. return PyByteArray_FromStringAndSize(self_start,
  1106. self_len - suffix_len);
  1107. }
  1108. return PyByteArray_FromStringAndSize(self_start, self_len);
  1109. }
  1110. /*[clinic input]
  1111. bytearray.translate
  1112. table: object
  1113. Translation table, which must be a bytes object of length 256.
  1114. /
  1115. delete as deletechars: object(c_default="NULL") = b''
  1116. Return a copy with each character mapped by the given translation table.
  1117. All characters occurring in the optional argument delete are removed.
  1118. The remaining characters are mapped through the given translation table.
  1119. [clinic start generated code]*/
  1120. static PyObject *
  1121. bytearray_translate_impl(PyByteArrayObject *self, PyObject *table,
  1122. PyObject *deletechars)
  1123. /*[clinic end generated code: output=b6a8f01c2a74e446 input=cfff956d4d127a9b]*/
  1124. {
  1125. char *input, *output;
  1126. const char *table_chars;
  1127. Py_ssize_t i, c;
  1128. PyObject *input_obj = (PyObject*)self;
  1129. const char *output_start;
  1130. Py_ssize_t inlen;
  1131. PyObject *result = NULL;
  1132. int trans_table[256];
  1133. Py_buffer vtable, vdel;
  1134. if (table == Py_None) {
  1135. table_chars = NULL;
  1136. table = NULL;
  1137. } else if (PyObject_GetBuffer(table, &vtable, PyBUF_SIMPLE) != 0) {
  1138. return NULL;
  1139. } else {
  1140. if (vtable.len != 256) {
  1141. PyErr_SetString(PyExc_ValueError,
  1142. "translation table must be 256 characters long");
  1143. PyBuffer_Release(&vtable);
  1144. return NULL;
  1145. }
  1146. table_chars = (const char*)vtable.buf;
  1147. }
  1148. if (deletechars != NULL) {
  1149. if (PyObject_GetBuffer(deletechars, &vdel, PyBUF_SIMPLE) != 0) {
  1150. if (table != NULL)
  1151. PyBuffer_Release(&vtable);
  1152. return NULL;
  1153. }
  1154. }
  1155. else {
  1156. vdel.buf = NULL;
  1157. vdel.len = 0;
  1158. }
  1159. inlen = PyByteArray_GET_SIZE(input_obj);
  1160. result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
  1161. if (result == NULL)
  1162. goto done;
  1163. output_start = output = PyByteArray_AS_STRING(result);
  1164. input = PyByteArray_AS_STRING(input_obj);
  1165. if (vdel.len == 0 && table_chars != NULL) {
  1166. /* If no deletions are required, use faster code */
  1167. for (i = inlen; --i >= 0; ) {
  1168. c = Py_CHARMASK(*input++);
  1169. *output++ = table_chars[c];
  1170. }
  1171. goto done;
  1172. }
  1173. if (table_chars == NULL) {
  1174. for (i = 0; i < 256; i++)
  1175. trans_table[i] = Py_CHARMASK(i);
  1176. } else {
  1177. for (i = 0; i < 256; i++)
  1178. trans_table[i] = Py_CHARMASK(table_chars[i]);
  1179. }
  1180. for (i = 0; i < vdel.len; i++)
  1181. trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
  1182. for (i = inlen; --i >= 0; ) {
  1183. c = Py_CHARMASK(*input++);
  1184. if (trans_table[c] != -1)
  1185. *output++ = (char)trans_table[c];
  1186. }
  1187. /* Fix the size of the resulting bytearray */
  1188. if (inlen > 0)
  1189. if (PyByteArray_Resize(result, output - output_start) < 0) {
  1190. Py_CLEAR(result);
  1191. goto done;
  1192. }
  1193. done:
  1194. if (table != NULL)
  1195. PyBuffer_Release(&vtable);
  1196. if (deletechars != NULL)
  1197. PyBuffer_Release(&vdel);
  1198. return result;
  1199. }
  1200. /*[clinic input]
  1201. @staticmethod
  1202. bytearray.maketrans
  1203. frm: Py_buffer
  1204. to: Py_buffer
  1205. /
  1206. Return a translation table useable for the bytes or bytearray translate method.
  1207. The returned table will be one where each byte in frm is mapped to the byte at
  1208. the same position in to.
  1209. The bytes objects frm and to must be of the same length.
  1210. [clinic start generated code]*/
  1211. static PyObject *
  1212. bytearray_maketrans_impl(Py_buffer *frm, Py_buffer *to)
  1213. /*[clinic end generated code: output=1df267d99f56b15e input=5925a81d2fbbf151]*/
  1214. {
  1215. return _Py_bytes_maketrans(frm, to);
  1216. }
  1217. /*[clinic input]
  1218. bytearray.replace
  1219. old: Py_buffer
  1220. new: Py_buffer
  1221. count: Py_ssize_t = -1
  1222. Maximum number of occurrences to replace.
  1223. -1 (the default value) means replace all occurrences.
  1224. /
  1225. Return a copy with all occurrences of substring old replaced by new.
  1226. If the optional argument count is given, only the first count occurrences are
  1227. replaced.
  1228. [clinic start generated code]*/
  1229. static PyObject *
  1230. bytearray_replace_impl(PyByteArrayObject *self, Py_buffer *old,
  1231. Py_buffer *new, Py_ssize_t count)
  1232. /*[clinic end generated code: output=d39884c4dc59412a input=aa379d988637c7fb]*/
  1233. {
  1234. return stringlib_replace((PyObject *)self,
  1235. (const char *)old->buf, old->len,
  1236. (const char *)new->buf, new->len, count);
  1237. }
  1238. /*[clinic input]
  1239. bytearray.split
  1240. sep: object = None
  1241. The delimiter according which to split the bytearray.
  1242. None (the default value) means split on ASCII whitespace characters
  1243. (space, tab, return, newline, formfeed, vertical tab).
  1244. maxsplit: Py_ssize_t = -1
  1245. Maximum number of splits to do.
  1246. -1 (the default value) means no limit.
  1247. Return a list of the sections in the bytearray, using sep as the delimiter.
  1248. [clinic start generated code]*/
  1249. static PyObject *
  1250. bytearray_split_impl(PyByteArrayObject *self, PyObject *sep,
  1251. Py_ssize_t maxsplit)
  1252. /*[clinic end generated code: output=833e2cf385d9a04d input=24f82669f41bf523]*/
  1253. {
  1254. Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
  1255. const char *s = PyByteArray_AS_STRING(self), *sub;
  1256. PyObject *list;
  1257. Py_buffer vsub;
  1258. if (maxsplit < 0)
  1259. maxsplit = PY_SSIZE_T_MAX;
  1260. if (sep == Py_None)
  1261. return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
  1262. if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
  1263. return NULL;
  1264. sub = vsub.buf;
  1265. n = vsub.len;
  1266. list = stringlib_split(
  1267. (PyObject*) self, s, len, sub, n, maxsplit
  1268. );
  1269. PyBuffer_Release(&vsub);
  1270. return list;
  1271. }
  1272. /*[clinic input]
  1273. bytearray.partition
  1274. sep: object
  1275. /
  1276. Partition the bytearray into three parts using the given separator.
  1277. This will search for the separator sep in the bytearray. If the separator is
  1278. found, returns a 3-tuple containing the part before the separator, the
  1279. separator itself, and the part after it as new bytearray objects.
  1280. If the separator is not found, returns a 3-tuple containing the copy of the
  1281. original bytearray object and two empty bytearray objects.
  1282. [clinic start generated code]*/
  1283. static PyObject *
  1284. bytearray_partition(PyByteArrayObject *self, PyObject *sep)
  1285. /*[clinic end generated code: output=45d2525ddd35f957 input=8f644749ee4fc83a]*/
  1286. {
  1287. PyObject *bytesep, *result;
  1288. bytesep = _PyByteArray_FromBufferObject(sep);
  1289. if (! bytesep)
  1290. return NULL;
  1291. result = stringlib_partition(
  1292. (PyObject*) self,
  1293. PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
  1294. bytesep,
  1295. PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
  1296. );
  1297. Py_DECREF(bytesep);
  1298. return result;
  1299. }
  1300. /*[clinic input]
  1301. bytearray.rpartition
  1302. sep: object
  1303. /
  1304. Partition the bytearray into three parts using the given separator.
  1305. This will search for the separator sep in the bytearray, starting at the end.
  1306. If the separator is found, returns a 3-tuple containing the part before the
  1307. separator, the separator itself, and the part after it as new bytearray
  1308. objects.
  1309. If the separator is not found, returns a 3-tuple containing two empty bytearray
  1310. objects and the copy of the original bytearray object.
  1311. [clinic start generated code]*/
  1312. static PyObject *
  1313. bytearray_rpartition(PyByteArrayObject *self, PyObject *sep)
  1314. /*[clinic end generated code: output=440de3c9426115e8 input=7e3df3e6cb8fa0ac]*/
  1315. {
  1316. PyObject *bytesep, *result;
  1317. bytesep = _PyByteArray_FromBufferObject(sep);
  1318. if (! bytesep)
  1319. return NULL;
  1320. result = stringlib_rpartition(
  1321. (PyObject*) self,
  1322. PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
  1323. bytesep,
  1324. PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
  1325. );
  1326. Py_DECREF(bytesep);
  1327. return result;
  1328. }
  1329. /*[clinic input]
  1330. bytearray.rsplit = bytearray.split
  1331. Return a list of the sections in the bytearray, using sep as the delimiter.
  1332. Splitting is done starting at the end of the bytearray and working to the front.
  1333. [clinic start generated code]*/
  1334. static PyObject *
  1335. bytearray_rsplit_impl(PyByteArrayObject *self, PyObject *sep,
  1336. Py_ssize_t maxsplit)
  1337. /*[clinic end generated code: output=a55e0b5a03cb6190 input=a68286e4dd692ffe]*/
  1338. {
  1339. Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
  1340. const char *s = PyByteArray_AS_STRING(self), *sub;
  1341. PyObject *list;
  1342. Py_buffer vsub;
  1343. if (maxsplit < 0)
  1344. maxsplit = PY_SSIZE_T_MAX;
  1345. if (sep == Py_None)
  1346. return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
  1347. if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
  1348. return NULL;
  1349. sub = vsub.buf;
  1350. n = vsub.len;
  1351. list = stringlib_rsplit(
  1352. (PyObject*) self, s, len, sub, n, maxsplit
  1353. );
  1354. PyBuffer_Release(&vsub);
  1355. return list;
  1356. }
  1357. /*[clinic input]
  1358. bytearray.reverse
  1359. Reverse the order of the values in B in place.
  1360. [clinic start generated code]*/
  1361. static PyObject *
  1362. bytearray_reverse_impl(PyByteArrayObject *self)
  1363. /*[clinic end generated code: output=9f7616f29ab309d3 input=543356319fc78557]*/
  1364. {
  1365. char swap, *head, *tail;
  1366. Py_ssize_t i, j, n = Py_SIZE(self);
  1367. j = n / 2;
  1368. head = PyByteArray_AS_STRING(self);
  1369. tail = head + n - 1;
  1370. for (i = 0; i < j; i++) {
  1371. swap = *head;
  1372. *head++ = *tail;
  1373. *tail-- = swap;
  1374. }
  1375. Py_RETURN_NONE;
  1376. }
  1377. /*[python input]
  1378. class bytesvalue_converter(CConverter):
  1379. type = 'int'
  1380. converter = '_getbytevalue'
  1381. [python start generated code]*/
  1382. /*[python end generated code: output=da39a3ee5e6b4b0d input=29c2e7c26c212812]*/
  1383. /*[clinic input]
  1384. bytearray.insert
  1385. index: Py_ssize_t
  1386. The index where the value is to be inserted.
  1387. item: bytesvalue
  1388. The item to be inserted.
  1389. /
  1390. Insert a single item into the bytearray before the given index.
  1391. [clinic start generated code]*/
  1392. static PyObject *
  1393. bytearray_insert_impl(PyByteArrayObject *self, Py_ssize_t index, int item)
  1394. /*[clinic end generated code: output=76c775a70e7b07b7 input=b2b5d07e9de6c070]*/
  1395. {
  1396. Py_ssize_t n = Py_SIZE(self);
  1397. char *buf;
  1398. if (n == PY_SSIZE_T_MAX) {
  1399. PyErr_SetString(PyExc_OverflowError,
  1400. "cannot add more objects to bytearray");
  1401. return NULL;
  1402. }
  1403. if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
  1404. return NULL;
  1405. buf = PyByteArray_AS_STRING(self);
  1406. if (index < 0) {
  1407. index += n;
  1408. if (index < 0)
  1409. index = 0;
  1410. }
  1411. if (index > n)
  1412. index = n;
  1413. memmove(buf + index + 1, buf + index, n - index);
  1414. buf[index] = item;
  1415. Py_RETURN_NONE;
  1416. }
  1417. /*[clinic input]
  1418. bytearray.append
  1419. item: bytesvalue
  1420. The item to be appended.
  1421. /
  1422. Append a single item to the end of the bytearray.
  1423. [clinic start generated code]*/
  1424. static PyObject *
  1425. bytearray_append_impl(PyByteArrayObject *self, int item)
  1426. /*[clinic end generated code: output=a154e19ed1886cb6 input=20d6bec3d1340593]*/
  1427. {
  1428. Py_ssize_t n = Py_SIZE(self);
  1429. if (n == PY_SSIZE_T_MAX) {
  1430. PyErr_SetString(PyExc_OverflowError,
  1431. "cannot add more objects to bytearray");
  1432. return NULL;
  1433. }
  1434. if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
  1435. return NULL;
  1436. PyByteArray_AS_STRING(self)[n] = item;
  1437. Py_RETURN_NONE;
  1438. }
  1439. /*[clinic input]
  1440. bytearray.extend
  1441. iterable_of_ints: object
  1442. The iterable of items to append.
  1443. /
  1444. Append all the items from the iterator or sequence to the end of the bytearray.
  1445. [clinic start generated code]*/
  1446. static PyObject *
  1447. bytearray_extend(PyByteArrayObject *self, PyObject *iterable_of_ints)
  1448. /*[clinic end generated code: output=98155dbe249170b1 input=c617b3a93249ba28]*/
  1449. {
  1450. PyObject *it, *item, *bytearray_obj;
  1451. Py_ssize_t buf_size = 0, len = 0;
  1452. int value;
  1453. char *buf;
  1454. /* bytearray_setslice code only accepts something supporting PEP 3118. */
  1455. if (PyObject_CheckBuffer(iterable_of_ints)) {
  1456. if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), iterable_of_ints) == -1)
  1457. return NULL;
  1458. Py_RETURN_NONE;
  1459. }
  1460. it = PyObject_GetIter(iterable_of_ints);
  1461. if (it == NULL) {
  1462. if (PyErr_ExceptionMatches(PyExc_TypeError)) {
  1463. PyErr_Format(PyExc_TypeError,
  1464. "can't extend bytearray with %.100s",
  1465. Py_TYPE(iterable_of_ints)->tp_name);
  1466. }
  1467. return NULL;
  1468. }
  1469. /* Try to determine the length of the argument. 32 is arbitrary. */
  1470. buf_size = PyObject_LengthHint(iterable_of_ints, 32);
  1471. if (buf_size == -1) {
  1472. Py_DECREF(it);
  1473. return NULL;
  1474. }
  1475. bytearray_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
  1476. if (bytearray_obj == NULL) {
  1477. Py_DECREF(it);
  1478. return NULL;
  1479. }
  1480. buf = PyByteArray_AS_STRING(bytearray_obj);
  1481. while ((item = PyIter_Next(it)) != NULL) {
  1482. if (! _getbytevalue(item, &value)) {
  1483. Py_DECREF(item);
  1484. Py_DECREF(it);
  1485. Py_DECREF(bytearray_obj);
  1486. return NULL;
  1487. }
  1488. buf[len++] = value;
  1489. Py_DECREF(item);
  1490. if (len >= buf_size) {
  1491. Py_ssize_t addition;
  1492. if (len == PY_SSIZE_T_MAX) {
  1493. Py_DECREF(it);
  1494. Py_DECREF(bytearray_obj);
  1495. return PyErr_NoMemory();
  1496. }
  1497. addition = len >> 1;
  1498. if (addition > PY_SSIZE_T_MAX - len - 1)
  1499. buf_size = PY_SSIZE_T_MAX;
  1500. else
  1501. buf_size = len + addition + 1;
  1502. if (PyByteArray_Resize((PyObject *)bytearray_obj, buf_size) < 0) {
  1503. Py_DECREF(it);
  1504. Py_DECREF(bytearray_obj);
  1505. return NULL;
  1506. }
  1507. /* Recompute the `buf' pointer, since the resizing operation may
  1508. have invalidated it. */
  1509. buf = PyByteArray_AS_STRING(bytearray_obj);
  1510. }
  1511. }
  1512. Py_DECREF(it);
  1513. if (PyErr_Occurred()) {
  1514. Py_DECREF(bytearray_obj);
  1515. return NULL;
  1516. }
  1517. /* Resize down to exact size. */
  1518. if (PyByteArray_Resize((PyObject *)bytearray_obj, len) < 0) {
  1519. Py_DECREF(bytearray_obj);
  1520. return NULL;
  1521. }
  1522. if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), bytearray_obj) == -1) {
  1523. Py_DECREF(bytearray_obj);
  1524. return NULL;
  1525. }
  1526. Py_DECREF(bytearray_obj);
  1527. assert(!PyErr_Occurred());
  1528. Py_RETURN_NONE;
  1529. }
  1530. /*[clinic input]
  1531. bytearray.pop
  1532. index: Py_ssize_t = -1
  1533. The index from where to remove the item.
  1534. -1 (the default value) means remove the last item.
  1535. /
  1536. Remove and return a single item from B.
  1537. If no index argument is given, will pop the last item.
  1538. [clinic start generated code]*/
  1539. static PyObject *
  1540. bytearray_pop_impl(PyByteArrayObject *self, Py_ssize_t index)
  1541. /*[clinic end generated code: output=e0ccd401f8021da8 input=3591df2d06c0d237]*/
  1542. {
  1543. int value;
  1544. Py_ssize_t n = Py_SIZE(self);
  1545. char *buf;
  1546. if (n == 0) {
  1547. PyErr_SetString(PyExc_IndexError,
  1548. "pop from empty bytearray");
  1549. return NULL;
  1550. }
  1551. if (index < 0)
  1552. index += Py_SIZE(self);
  1553. if (index < 0 || index >= Py_SIZE(self)) {
  1554. PyErr_SetString(PyExc_IndexError, "pop index out of range");
  1555. return NULL;
  1556. }
  1557. if (!_canresize(self))
  1558. return NULL;
  1559. buf = PyByteArray_AS_STRING(self);
  1560. value = buf[index];
  1561. memmove(buf + index, buf + index + 1, n - index);
  1562. if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
  1563. return NULL;
  1564. return _PyLong_FromUnsignedChar((unsigned char)value);
  1565. }
  1566. /*[clinic input]
  1567. bytearray.remove
  1568. value: bytesvalue
  1569. The value to remove.
  1570. /
  1571. Remove the first occurrence of a value in the bytearray.
  1572. [clinic start generated code]*/
  1573. static PyObject *
  1574. bytearray_remove_impl(PyByteArrayObject *self, int value)
  1575. /*[clinic end generated code: output=d659e37866709c13 input=121831240cd51ddf]*/
  1576. {
  1577. Py_ssize_t where, n = Py_SIZE(self);
  1578. char *buf = PyByteArray_AS_STRING(self);
  1579. where = stringlib_find_char(buf, n, value);
  1580. if (where < 0) {
  1581. PyErr_SetString(PyExc_ValueError, "value not found in bytearray");
  1582. return NULL;
  1583. }
  1584. if (!_canresize(self))
  1585. return NULL;
  1586. memmove(buf + where, buf + where + 1, n - where);
  1587. if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
  1588. return NULL;
  1589. Py_RETURN_NONE;
  1590. }
  1591. #define LEFTSTRIP 0
  1592. #define RIGHTSTRIP 1
  1593. #define BOTHSTRIP 2
  1594. static PyObject*
  1595. bytearray_strip_impl_helper(PyByteArrayObject* self, PyObject* bytes, int striptype)
  1596. {
  1597. Py_ssize_t mysize, byteslen;
  1598. const char* myptr;
  1599. const char* bytesptr;
  1600. Py_buffer vbytes;
  1601. if (bytes == Py_None) {
  1602. bytesptr = "\t\n\r\f\v ";
  1603. byteslen = 6;
  1604. }
  1605. else {
  1606. if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
  1607. return NULL;
  1608. bytesptr = (const char*)vbytes.buf;
  1609. byteslen = vbytes.len;
  1610. }
  1611. myptr = PyByteArray_AS_STRING(self);
  1612. mysize = Py_SIZE(self);
  1613. Py_ssize_t left = 0;
  1614. if (striptype != RIGHTSTRIP) {
  1615. while (left < mysize && memchr(bytesptr, (unsigned char)myptr[left], byteslen))
  1616. left++;
  1617. }
  1618. Py_ssize_t right = mysize;
  1619. if (striptype != LEFTSTRIP) {
  1620. do {
  1621. right--;
  1622. } while (right >= left && memchr(bytesptr, (unsigned char)myptr[right], byteslen));
  1623. right++;
  1624. }
  1625. if (bytes != Py_None)
  1626. PyBuffer_Release(&vbytes);
  1627. return PyByteArray_FromStringAndSize(myptr + left, right - left);
  1628. }
  1629. /*[clinic input]
  1630. bytearray.strip
  1631. bytes: object = None
  1632. /
  1633. Strip leading and trailing bytes contained in the argument.
  1634. If the argument is omitted or None, strip leading and trailing ASCII whitespace.
  1635. [clinic start generated code]*/
  1636. static PyObject *
  1637. bytearray_strip_impl(PyByteArrayObject *self, PyObject *bytes)
  1638. /*[clinic end generated code: output=760412661a34ad5a input=ef7bb59b09c21d62]*/
  1639. {
  1640. return bytearray_strip_impl_helper(self, bytes, BOTHSTRIP);
  1641. }
  1642. /*[clinic input]
  1643. bytearray.lstrip
  1644. bytes: object = None
  1645. /
  1646. Strip leading bytes contained in the argument.
  1647. If the argument is omitted or None, strip leading ASCII whitespace.
  1648. [clinic start generated code]*/
  1649. static PyObject *
  1650. bytearray_lstrip_impl(PyByteArrayObject *self, PyObject *bytes)
  1651. /*[clinic end generated code: output=d005c9d0ab909e66 input=80843f975dd7c480]*/
  1652. {
  1653. return bytearray_strip_impl_helper(self, bytes, LEFTSTRIP);
  1654. }
  1655. /*[clinic input]
  1656. bytearray.rstrip
  1657. bytes: object = None
  1658. /
  1659. Strip trailing bytes contained in the argument.
  1660. If the argument is omitted or None, strip trailing ASCII whitespace.
  1661. [clinic start generated code]*/
  1662. static PyObject *
  1663. bytearray_rstrip_impl(PyByteArrayObject *self, PyObject *bytes)
  1664. /*[clinic end generated code: output=030e2fbd2f7276bd input=e728b994954cfd91]*/
  1665. {
  1666. return bytearray_strip_impl_helper(self, bytes, RIGHTSTRIP);
  1667. }
  1668. /*[clinic input]
  1669. bytearray.decode
  1670. encoding: str(c_default="NULL") = 'utf-8'
  1671. The encoding with which to decode the bytearray.
  1672. errors: str(c_default="NULL") = 'strict'
  1673. The error handling scheme to use for the handling of decoding errors.
  1674. The default is 'strict' meaning that decoding errors raise a
  1675. UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
  1676. as well as any other name registered with codecs.register_error that
  1677. can handle UnicodeDecodeErrors.
  1678. Decode the bytearray using the codec registered for encoding.
  1679. [clinic start generated code]*/
  1680. static PyObject *
  1681. bytearray_decode_impl(PyByteArrayObject *self, const char *encoding,
  1682. const char *errors)
  1683. /*[clinic end generated code: output=f57d43f4a00b42c5 input=f28d8f903020257b]*/
  1684. {
  1685. if (encoding == NULL)
  1686. encoding = PyUnicode_GetDefaultEncoding();
  1687. return PyUnicode_FromEncodedObject((PyObject*)self, encoding, errors);
  1688. }
  1689. PyDoc_STRVAR(alloc_doc,
  1690. "B.__alloc__() -> int\n\
  1691. \n\
  1692. Return the number of bytes actually allocated.");
  1693. static PyObject *
  1694. bytearray_alloc(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
  1695. {
  1696. return PyLong_FromSsize_t(self->ob_alloc);
  1697. }
  1698. /*[clinic input]
  1699. bytearray.join
  1700. iterable_of_bytes: object
  1701. /
  1702. Concatenate any number of bytes/bytearray objects.
  1703. The bytearray whose method is called is inserted in between each pair.
  1704. The result is returned as a new bytearray object.
  1705. [clinic start generated code]*/
  1706. static PyObject *
  1707. bytearray_join(PyByteArrayObject *self, PyObject *iterable_of_bytes)
  1708. /*[clinic end generated code: output=a8516370bf68ae08 input=aba6b1f9b30fcb8e]*/
  1709. {
  1710. self->ob_exports++; // this protects `self` from being cleared/resized if `iterable_of_bytes` is a custom iterator
  1711. PyObject* ret = stringlib_bytes_join((PyObject*)self, iterable_of_bytes);
  1712. self->ob_exports--; // unexport `self`
  1713. return ret;
  1714. }
  1715. /*[clinic input]
  1716. bytearray.splitlines
  1717. keepends: bool = False
  1718. Return a list of the lines in the bytearray, breaking at line boundaries.
  1719. Line breaks are not included in the resulting list unless keepends is given and
  1720. true.
  1721. [clinic start generated code]*/
  1722. static PyObject *
  1723. bytearray_splitlines_impl(PyByteArrayObject *self, int keepends)
  1724. /*[clinic end generated code: output=4223c94b895f6ad9 input=66b2dcdea8d093bf]*/
  1725. {
  1726. return stringlib_splitlines(
  1727. (PyObject*) self, PyByteArray_AS_STRING(self),
  1728. PyByteArray_GET_SIZE(self), keepends
  1729. );
  1730. }
  1731. /*[clinic input]
  1732. @classmethod
  1733. bytearray.fromhex
  1734. string: unicode
  1735. /
  1736. Create a bytearray object from a string of hexadecimal numbers.
  1737. Spaces between two numbers are accepted.
  1738. Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef')
  1739. [clinic start generated code]*/
  1740. static PyObject *
  1741. bytearray_fromhex_impl(PyTypeObject *type, PyObject *string)
  1742. /*[clinic end generated code: output=8f0f0b6d30fb3ba0 input=f033a16d1fb21f48]*/
  1743. {
  1744. PyObject *result = _PyBytes_FromHex(string, type == &PyByteArray_Type);
  1745. if (type != &PyByteArray_Type && result != NULL) {
  1746. Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result));
  1747. }
  1748. return result;
  1749. }
  1750. /*[clinic input]
  1751. bytearray.hex
  1752. sep: object = NULL
  1753. An optional single character or byte to separate hex bytes.
  1754. bytes_per_sep: int = 1
  1755. How many bytes between separators. Positive values count from the
  1756. right, negative values count from the left.
  1757. Create a string of hexadecimal numbers from a bytearray object.
  1758. Example:
  1759. >>> value = bytearray([0xb9, 0x01, 0xef])
  1760. >>> value.hex()
  1761. 'b901ef'
  1762. >>> value.hex(':')
  1763. 'b9:01:ef'
  1764. >>> value.hex(':', 2)
  1765. 'b9:01ef'
  1766. >>> value.hex(':', -2)
  1767. 'b901:ef'
  1768. [clinic start generated code]*/
  1769. static PyObject *
  1770. bytearray_hex_impl(PyByteArrayObject *self, PyObject *sep, int bytes_per_sep)
  1771. /*[clinic end generated code: output=29c4e5ef72c565a0 input=808667e49bcccb54]*/
  1772. {
  1773. char* argbuf = PyByteArray_AS_STRING(self);
  1774. Py_ssize_t arglen = PyByteArray_GET_SIZE(self);
  1775. return _Py_strhex_with_sep(argbuf, arglen, sep, bytes_per_sep);
  1776. }
  1777. static PyObject *
  1778. _common_reduce(PyByteArrayObject *self, int proto)
  1779. {
  1780. PyObject *state;
  1781. const char *buf;
  1782. state = _PyObject_GetState((PyObject *)self);
  1783. if (state == NULL) {
  1784. return NULL;
  1785. }
  1786. if (!Py_SIZE(self)) {
  1787. return Py_BuildValue("(O()N)", Py_TYPE(self), state);
  1788. }
  1789. buf = PyByteArray_AS_STRING(self);
  1790. if (proto < 3) {
  1791. /* use str based reduction for backwards compatibility with Python 2.x */
  1792. PyObject *latin1 = PyUnicode_DecodeLatin1(buf, Py_SIZE(self), NULL);
  1793. return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", state);
  1794. }
  1795. else {
  1796. /* use more efficient byte based reduction */
  1797. return Py_BuildValue("(O(y#)N)", Py_TYPE(self), buf, Py_SIZE(self), state);
  1798. }
  1799. }
  1800. /*[clinic input]
  1801. bytearray.__reduce__ as bytearray_reduce
  1802. Return state information for pickling.
  1803. [clinic start generated code]*/
  1804. static PyObject *
  1805. bytearray_reduce_impl(PyByteArrayObject *self)
  1806. /*[clinic end generated code: output=52bf304086464cab input=44b5737ada62dd3f]*/
  1807. {
  1808. return _common_reduce(self, 2);
  1809. }
  1810. /*[clinic input]
  1811. bytearray.__reduce_ex__ as bytearray_reduce_ex
  1812. proto: int = 0
  1813. /
  1814. Return state information for pickling.
  1815. [clinic start generated code]*/
  1816. static PyObject *
  1817. bytearray_reduce_ex_impl(PyByteArrayObject *self, int proto)
  1818. /*[clinic end generated code: output=52eac33377197520 input=f129bc1a1aa151ee]*/
  1819. {
  1820. return _common_reduce(self, proto);
  1821. }
  1822. /*[clinic input]
  1823. bytearray.__sizeof__ as bytearray_sizeof
  1824. Returns the size of the bytearray object in memory, in bytes.
  1825. [clinic start generated code]*/
  1826. static PyObject *
  1827. bytearray_sizeof_impl(PyByteArrayObject *self)
  1828. /*[clinic end generated code: output=738abdd17951c427 input=e27320fd98a4bc5a]*/
  1829. {
  1830. size_t res = _PyObject_SIZE(Py_TYPE(self));
  1831. res += (size_t)self->ob_alloc * sizeof(char);
  1832. return PyLong_FromSize_t(res);
  1833. }
  1834. static PySequenceMethods bytearray_as_sequence = {
  1835. (lenfunc)bytearray_length, /* sq_length */
  1836. (binaryfunc)PyByteArray_Concat, /* sq_concat */
  1837. (ssizeargfunc)bytearray_repeat, /* sq_repeat */
  1838. (ssizeargfunc)bytearray_getitem, /* sq_item */
  1839. 0, /* sq_slice */
  1840. (ssizeobjargproc)bytearray_setitem, /* sq_ass_item */
  1841. 0, /* sq_ass_slice */
  1842. (objobjproc)bytearray_contains, /* sq_contains */
  1843. (binaryfunc)bytearray_iconcat, /* sq_inplace_concat */
  1844. (ssizeargfunc)bytearray_irepeat, /* sq_inplace_repeat */
  1845. };
  1846. static PyMappingMethods bytearray_as_mapping = {
  1847. (lenfunc)bytearray_length,
  1848. (binaryfunc)bytearray_subscript,
  1849. (objobjargproc)bytearray_ass_subscript,
  1850. };
  1851. static PyBufferProcs bytearray_as_buffer = {
  1852. (getbufferproc)bytearray_getbuffer,
  1853. (releasebufferproc)bytearray_releasebuffer,
  1854. };
  1855. static PyMethodDef
  1856. bytearray_methods[] = {
  1857. {"__alloc__", (PyCFunction)bytearray_alloc, METH_NOARGS, alloc_doc},
  1858. BYTEARRAY_REDUCE_METHODDEF
  1859. BYTEARRAY_REDUCE_EX_METHODDEF
  1860. BYTEARRAY_SIZEOF_METHODDEF
  1861. BYTEARRAY_APPEND_METHODDEF
  1862. {"capitalize", stringlib_capitalize, METH_NOARGS,
  1863. _Py_capitalize__doc__},
  1864. STRINGLIB_CENTER_METHODDEF
  1865. BYTEARRAY_CLEAR_METHODDEF
  1866. BYTEARRAY_COPY_METHODDEF
  1867. {"count", (PyCFunction)bytearray_count, METH_VARARGS,
  1868. _Py_count__doc__},
  1869. BYTEARRAY_DECODE_METHODDEF
  1870. {"endswith", (PyCFunction)bytearray_endswith, METH_VARARGS,
  1871. _Py_endswith__doc__},
  1872. STRINGLIB_EXPANDTABS_METHODDEF
  1873. BYTEARRAY_EXTEND_METHODDEF
  1874. {"find", (PyCFunction)bytearray_find, METH_VARARGS,
  1875. _Py_find__doc__},
  1876. BYTEARRAY_FROMHEX_METHODDEF
  1877. BYTEARRAY_HEX_METHODDEF
  1878. {"index", (PyCFunction)bytearray_index, METH_VARARGS, _Py_index__doc__},
  1879. BYTEARRAY_INSERT_METHODDEF
  1880. {"isalnum", stringlib_isalnum, METH_NOARGS,
  1881. _Py_isalnum__doc__},
  1882. {"isalpha", stringlib_isalpha, METH_NOARGS,
  1883. _Py_isalpha__doc__},
  1884. {"isascii", stringlib_isascii, METH_NOARGS,
  1885. _Py_isascii__doc__},
  1886. {"isdigit", stringlib_isdigit, METH_NOARGS,
  1887. _Py_isdigit__doc__},
  1888. {"islower", stringlib_islower, METH_NOARGS,
  1889. _Py_islower__doc__},
  1890. {"isspace", stringlib_isspace, METH_NOARGS,
  1891. _Py_isspace__doc__},
  1892. {"istitle", stringlib_istitle, METH_NOARGS,
  1893. _Py_istitle__doc__},
  1894. {"isupper", stringlib_isupper, METH_NOARGS,
  1895. _Py_isupper__doc__},
  1896. BYTEARRAY_JOIN_METHODDEF
  1897. STRINGLIB_LJUST_METHODDEF
  1898. {"lower", stringlib_lower, METH_NOARGS, _Py_lower__doc__},
  1899. BYTEARRAY_LSTRIP_METHODDEF
  1900. BYTEARRAY_MAKETRANS_METHODDEF
  1901. BYTEARRAY_PARTITION_METHODDEF
  1902. BYTEARRAY_POP_METHODDEF
  1903. BYTEARRAY_REMOVE_METHODDEF
  1904. BYTEARRAY_REPLACE_METHODDEF
  1905. BYTEARRAY_REMOVEPREFIX_METHODDEF
  1906. BYTEARRAY_REMOVESUFFIX_METHODDEF
  1907. BYTEARRAY_REVERSE_METHODDEF
  1908. {"rfind", (PyCFunction)bytearray_rfind, METH_VARARGS, _Py_rfind__doc__},
  1909. {"rindex", (PyCFunction)bytearray_rindex, METH_VARARGS, _Py_rindex__doc__},
  1910. STRINGLIB_RJUST_METHODDEF
  1911. BYTEARRAY_RPARTITION_METHODDEF
  1912. BYTEARRAY_RSPLIT_METHODDEF
  1913. BYTEARRAY_RSTRIP_METHODDEF
  1914. BYTEARRAY_SPLIT_METHODDEF
  1915. BYTEARRAY_SPLITLINES_METHODDEF
  1916. {"startswith", (PyCFunction)bytearray_startswith, METH_VARARGS ,
  1917. _Py_startswith__doc__},
  1918. BYTEARRAY_STRIP_METHODDEF
  1919. {"swapcase", stringlib_swapcase, METH_NOARGS,
  1920. _Py_swapcase__doc__},
  1921. {"title", stringlib_title, METH_NOARGS, _Py_title__doc__},
  1922. BYTEARRAY_TRANSLATE_METHODDEF
  1923. {"upper", stringlib_upper, METH_NOARGS, _Py_upper__doc__},
  1924. STRINGLIB_ZFILL_METHODDEF
  1925. {NULL}
  1926. };
  1927. static PyObject *
  1928. bytearray_mod(PyObject *v, PyObject *w)
  1929. {
  1930. if (!PyByteArray_Check(v))
  1931. Py_RETURN_NOTIMPLEMENTED;
  1932. return _PyBytes_FormatEx(PyByteArray_AS_STRING(v), PyByteArray_GET_SIZE(v), w, 1);
  1933. }
  1934. static PyNumberMethods bytearray_as_number = {
  1935. 0, /*nb_add*/
  1936. 0, /*nb_subtract*/
  1937. 0, /*nb_multiply*/
  1938. bytearray_mod, /*nb_remainder*/
  1939. };
  1940. PyDoc_STRVAR(bytearray_doc,
  1941. "bytearray(iterable_of_ints) -> bytearray\n\
  1942. bytearray(string, encoding[, errors]) -> bytearray\n\
  1943. bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer\n\
  1944. bytearray(int) -> bytes array of size given by the parameter initialized with null bytes\n\
  1945. bytearray() -> empty bytes array\n\
  1946. \n\
  1947. Construct a mutable bytearray object from:\n\
  1948. - an iterable yielding integers in range(256)\n\
  1949. - a text string encoded using the specified encoding\n\
  1950. - a bytes or a buffer object\n\
  1951. - any object implementing the buffer API.\n\
  1952. - an integer");
  1953. static PyObject *bytearray_iter(PyObject *seq);
  1954. PyTypeObject PyByteArray_Type = {
  1955. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1956. "bytearray",
  1957. sizeof(PyByteArrayObject),
  1958. 0,
  1959. (destructor)bytearray_dealloc, /* tp_dealloc */
  1960. 0, /* tp_vectorcall_offset */
  1961. 0, /* tp_getattr */
  1962. 0, /* tp_setattr */
  1963. 0, /* tp_as_async */
  1964. (reprfunc)bytearray_repr, /* tp_repr */
  1965. &bytearray_as_number, /* tp_as_number */
  1966. &bytearray_as_sequence, /* tp_as_sequence */
  1967. &bytearray_as_mapping, /* tp_as_mapping */
  1968. 0, /* tp_hash */
  1969. 0, /* tp_call */
  1970. bytearray_str, /* tp_str */
  1971. PyObject_GenericGetAttr, /* tp_getattro */
  1972. 0, /* tp_setattro */
  1973. &bytearray_as_buffer, /* tp_as_buffer */
  1974. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
  1975. _Py_TPFLAGS_MATCH_SELF, /* tp_flags */
  1976. bytearray_doc, /* tp_doc */
  1977. 0, /* tp_traverse */
  1978. 0, /* tp_clear */
  1979. (richcmpfunc)bytearray_richcompare, /* tp_richcompare */
  1980. 0, /* tp_weaklistoffset */
  1981. bytearray_iter, /* tp_iter */
  1982. 0, /* tp_iternext */
  1983. bytearray_methods, /* tp_methods */
  1984. 0, /* tp_members */
  1985. 0, /* tp_getset */
  1986. 0, /* tp_base */
  1987. 0, /* tp_dict */
  1988. 0, /* tp_descr_get */
  1989. 0, /* tp_descr_set */
  1990. 0, /* tp_dictoffset */
  1991. (initproc)bytearray___init__, /* tp_init */
  1992. PyType_GenericAlloc, /* tp_alloc */
  1993. PyType_GenericNew, /* tp_new */
  1994. PyObject_Del, /* tp_free */
  1995. };
  1996. /*********************** Bytearray Iterator ****************************/
  1997. typedef struct {
  1998. PyObject_HEAD
  1999. Py_ssize_t it_index;
  2000. PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */
  2001. } bytesiterobject;
  2002. static void
  2003. bytearrayiter_dealloc(bytesiterobject *it)
  2004. {
  2005. _PyObject_GC_UNTRACK(it);
  2006. Py_XDECREF(it->it_seq);
  2007. PyObject_GC_Del(it);
  2008. }
  2009. static int
  2010. bytearrayiter_traverse(bytesiterobject *it, visitproc visit, void *arg)
  2011. {
  2012. Py_VISIT(it->it_seq);
  2013. return 0;
  2014. }
  2015. static PyObject *
  2016. bytearrayiter_next(bytesiterobject *it)
  2017. {
  2018. PyByteArrayObject *seq;
  2019. assert(it != NULL);
  2020. seq = it->it_seq;
  2021. if (seq == NULL)
  2022. return NULL;
  2023. assert(PyByteArray_Check(seq));
  2024. if (it->it_index < PyByteArray_GET_SIZE(seq)) {
  2025. return _PyLong_FromUnsignedChar(
  2026. (unsigned char)PyByteArray_AS_STRING(seq)[it->it_index++]);
  2027. }
  2028. it->it_seq = NULL;
  2029. Py_DECREF(seq);
  2030. return NULL;
  2031. }
  2032. static PyObject *
  2033. bytearrayiter_length_hint(bytesiterobject *it, PyObject *Py_UNUSED(ignored))
  2034. {
  2035. Py_ssize_t len = 0;
  2036. if (it->it_seq) {
  2037. len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index;
  2038. if (len < 0) {
  2039. len = 0;
  2040. }
  2041. }
  2042. return PyLong_FromSsize_t(len);
  2043. }
  2044. PyDoc_STRVAR(length_hint_doc,
  2045. "Private method returning an estimate of len(list(it)).");
  2046. static PyObject *
  2047. bytearrayiter_reduce(bytesiterobject *it, PyObject *Py_UNUSED(ignored))
  2048. {
  2049. PyObject *iter = _PyEval_GetBuiltin(&_Py_ID(iter));
  2050. /* _PyEval_GetBuiltin can invoke arbitrary code,
  2051. * call must be before access of iterator pointers.
  2052. * see issue #101765 */
  2053. if (it->it_seq != NULL) {
  2054. return Py_BuildValue("N(O)n", iter, it->it_seq, it->it_index);
  2055. } else {
  2056. return Py_BuildValue("N(())", iter);
  2057. }
  2058. }
  2059. static PyObject *
  2060. bytearrayiter_setstate(bytesiterobject *it, PyObject *state)
  2061. {
  2062. Py_ssize_t index = PyLong_AsSsize_t(state);
  2063. if (index == -1 && PyErr_Occurred())
  2064. return NULL;
  2065. if (it->it_seq != NULL) {
  2066. if (index < 0)
  2067. index = 0;
  2068. else if (index > PyByteArray_GET_SIZE(it->it_seq))
  2069. index = PyByteArray_GET_SIZE(it->it_seq); /* iterator exhausted */
  2070. it->it_index = index;
  2071. }
  2072. Py_RETURN_NONE;
  2073. }
  2074. PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
  2075. static PyMethodDef bytearrayiter_methods[] = {
  2076. {"__length_hint__", (PyCFunction)bytearrayiter_length_hint, METH_NOARGS,
  2077. length_hint_doc},
  2078. {"__reduce__", (PyCFunction)bytearrayiter_reduce, METH_NOARGS,
  2079. bytearray_reduce__doc__},
  2080. {"__setstate__", (PyCFunction)bytearrayiter_setstate, METH_O,
  2081. setstate_doc},
  2082. {NULL, NULL} /* sentinel */
  2083. };
  2084. PyTypeObject PyByteArrayIter_Type = {
  2085. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  2086. "bytearray_iterator", /* tp_name */
  2087. sizeof(bytesiterobject), /* tp_basicsize */
  2088. 0, /* tp_itemsize */
  2089. /* methods */
  2090. (destructor)bytearrayiter_dealloc, /* tp_dealloc */
  2091. 0, /* tp_vectorcall_offset */
  2092. 0, /* tp_getattr */
  2093. 0, /* tp_setattr */
  2094. 0, /* tp_as_async */
  2095. 0, /* tp_repr */
  2096. 0, /* tp_as_number */
  2097. 0, /* tp_as_sequence */
  2098. 0, /* tp_as_mapping */
  2099. 0, /* tp_hash */
  2100. 0, /* tp_call */
  2101. 0, /* tp_str */
  2102. PyObject_GenericGetAttr, /* tp_getattro */
  2103. 0, /* tp_setattro */
  2104. 0, /* tp_as_buffer */
  2105. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  2106. 0, /* tp_doc */
  2107. (traverseproc)bytearrayiter_traverse, /* tp_traverse */
  2108. 0, /* tp_clear */
  2109. 0, /* tp_richcompare */
  2110. 0, /* tp_weaklistoffset */
  2111. PyObject_SelfIter, /* tp_iter */
  2112. (iternextfunc)bytearrayiter_next, /* tp_iternext */
  2113. bytearrayiter_methods, /* tp_methods */
  2114. 0,
  2115. };
  2116. static PyObject *
  2117. bytearray_iter(PyObject *seq)
  2118. {
  2119. bytesiterobject *it;
  2120. if (!PyByteArray_Check(seq)) {
  2121. PyErr_BadInternalCall();
  2122. return NULL;
  2123. }
  2124. it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);
  2125. if (it == NULL)
  2126. return NULL;
  2127. it->it_index = 0;
  2128. it->it_seq = (PyByteArrayObject *)Py_NewRef(seq);
  2129. _PyObject_GC_TRACK(it);
  2130. return (PyObject *)it;
  2131. }